import { Injectable, inject, signal } from '@angular/core';
import { SettingService } from './setting.service';

const SALES_KEY = 'sales.accent_color';
const PURCHASES_KEY = 'purchases.accent_color';
const DEFAULT_COLOR = '#1a237e';

const CACHE_SALES = 'moon_erp_sales_accent_color';
const CACHE_PURCHASES = 'moon_erp_purchases_accent_color';

@Injectable({ providedIn: 'root' })
export class ModuleColorService {
  private settingService = inject(SettingService);

  salesColor = signal(DEFAULT_COLOR);
  purchasesColor = signal(DEFAULT_COLOR);

  constructor() {
    // Load from cache first for instant rendering
    const cs = localStorage.getItem(CACHE_SALES);
    const cp = localStorage.getItem(CACHE_PURCHASES);
    if (cs) this.salesColor.set(cs);
    if (cp) this.purchasesColor.set(cp);

    // Then load from backend (source of truth)
    this.loadFromBackend();
  }

  private loadFromBackend(): void {
    this.settingService.getByKey(SALES_KEY).subscribe({
      next: (res) => {
        const val = res?.value;
        if (val && val !== '0' && val !== '') {
          this.salesColor.set(val);
          localStorage.setItem(CACHE_SALES, val);
        }
      },
      error: () => {},
    });

    this.settingService.getByKey(PURCHASES_KEY).subscribe({
      next: (res) => {
        const val = res?.value;
        if (val && val !== '0' && val !== '') {
          this.purchasesColor.set(val);
          localStorage.setItem(CACHE_PURCHASES, val);
        }
      },
      error: () => {},
    });
  }

  setSalesColor(color: string): void {
    this.salesColor.set(color);
    localStorage.setItem(CACHE_SALES, color);
    this.settingService.update({ setting_key: SALES_KEY, value: color }).subscribe();
  }

  setPurchasesColor(color: string): void {
    this.purchasesColor.set(color);
    localStorage.setItem(CACHE_PURCHASES, color);
    this.settingService.update({ setting_key: PURCHASES_KEY, value: color }).subscribe();
  }

  getModuleColor(module: 'sales' | 'purchases'): string {
    return module === 'sales' ? this.salesColor() : this.purchasesColor();
  }
}
