import { Component, inject, OnInit, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { Store } from '@ngrx/store';
import { TranslateModule, TranslateService } from '@ngx-translate/core';
import { ButtonModule } from 'primeng/button';
import { InputTextModule } from 'primeng/inputtext';
import { InputNumberModule } from 'primeng/inputnumber';
import { SelectModule } from 'primeng/select';
import { TagModule } from 'primeng/tag';
import { ToastModule } from 'primeng/toast';
import { ProgressSpinnerModule } from 'primeng/progressspinner';
import { ToggleSwitchModule } from 'primeng/toggleswitch';
import { TextareaModule } from 'primeng/textarea';
import { TooltipModule } from 'primeng/tooltip';
import { TabsModule } from 'primeng/tabs';
import { MessageService } from 'primeng/api';
import { PageHeaderComponent } from '../../shared';
import {
  SettingsActions,
  selectAllSettings,
  selectSettingsLoading,
  selectSettingsError,
  AccountsActions,
  selectAllAccounts,
  WarehousesActions,
  selectAllWarehouses,
  TaxRatesActions,
  selectAllTaxRates,
} from '../../core/store';
import { Setting, UpdateSetting } from '../../core/models/setting.model';
import { Account } from '../../core/models/account.model';
import { SettingService } from '../../core/services/setting.service';
import { SalesSettingsService } from '../../core/services/sales-settings.service';
import { PurchasesSettingsService } from '../../core/services/purchases-settings.service';
import { LanguageService } from '../../core/services/language.service';
import { ModuleColorService } from '../../core/services/module-color.service';

@Component({
  selector: 'app-settings',
  standalone: true,
  imports: [
    CommonModule, FormsModule, TranslateModule,
    ButtonModule, InputTextModule, InputNumberModule,
    SelectModule, TagModule, ToastModule, ProgressSpinnerModule,
    ToggleSwitchModule, TooltipModule, TabsModule, TextareaModule,
    PageHeaderComponent,
  ],
  providers: [MessageService],
  templateUrl: './settings.component.html',
  styleUrl: './settings.component.scss',
})
export class SettingsComponent implements OnInit {
  private store = inject(Store);
  private messageService = inject(MessageService);
  private settingService = inject(SettingService);
  private salesSettingsService = inject(SalesSettingsService);
  private purchasesSettingsService = inject(PurchasesSettingsService);
  private translate = inject(TranslateService);
  lang = inject(LanguageService);
  moduleColorService = inject(ModuleColorService);

  settings$ = this.store.select(selectAllSettings);
  loading$ = this.store.select(selectSettingsLoading);
  error$ = this.store.select(selectSettingsError);

  activeTab = 'accounting';
  editingKey = signal<string | null>(null);
  editValue: any = null;
  saving = signal(false);
  allSettings = signal<Setting[]>([]);
  accounts = signal<Account[]>([]);
  searchQuery = '';

  moduleTabs = [
    { label: 'Accounting', value: 'accounting', icon: 'pi pi-calculator' },
    { label: 'Sales', value: 'sales', icon: 'pi pi-shopping-cart' },
    { label: 'Purchases', value: 'purchases', icon: 'pi pi-truck' },
    { label: 'Inventory', value: 'inventory', icon: 'pi pi-box' },
    { label: 'Products', value: 'products', icon: 'pi pi-tags' },
  ];

  // Custom product display settings
  showCategoryInName = signal(false);
  minSearchChars = signal(3);
  productSettingsSaving = signal(false);

  // Auto-approve settings
  expenseAutoApprove = signal(false);
  revenueAutoApprove = signal(false);
  paymentVoucherAutoApprove = signal(false);
  receiptVoucherAutoApprove = signal(false);
  approveSettingSaving = signal(false);

  // Inventory custom settings
  countAutoApprove = signal(false);
  receiptAutoApprove = signal(false);
  issueAutoApprove = signal(false);
  invSettingSaving = signal(false);

  // Feedback button toggle
  showFeedbackButton = signal(true);
  feedbackButtonSaving = signal(false);

  // Perpetual inventory toggle (uses core settings endpoint for reliable update)
  perpetualInventory = signal(false);
  perpetualInventorySaving = signal(false);

  // Sales settings (loaded from /api/sales/settings)
  salesSettingsLoading = signal(false);
  salesSettingsSaving = signal(false);
  salesSettings = signal<{ key: string; label: string; description: string; value_type: string; current_value: any; allowed_values: string[]; group: string }[]>([]);
  salesEditValues = signal<Record<string, any>>({});

  salesGroups = [
    { key: 'general', label: 'SALES.GENERAL_SETTINGS', icon: 'pi pi-cog' },
    { key: 'pricing', label: 'SALES.PRICING_SETTINGS', icon: 'pi pi-dollar' },
    { key: 'delivery', label: 'SALES.DELIVERY_SETTINGS', icon: 'pi pi-truck' },
    { key: 'commissions', label: 'SALES.COMMISSION_SETTINGS', icon: 'pi pi-percentage' },
    { key: 'approval', label: 'SALES.APPROVAL_SETTINGS', icon: 'pi pi-check-circle' },
    { key: 'gl_accounts', label: 'SALES.GL_ACCOUNTS', icon: 'pi pi-book' },
  ];

  private salesGroupMap: Record<string, string> = {
    'sales.default_warehouse_id': 'general',
    'sales.default_tax_id': 'general',
    'sales.default_cost_center_id': 'general',
    'sales.default_payment_terms_days': 'general',
    'sales.quotation_validity_days': 'general',
    'sales.default_price_type': 'pricing',
    'sales.price_includes_tax': 'pricing',
    'sales.vat_inclusive': 'pricing',
    'sales.vat_rate': 'pricing',
    'sales.allow_below_min_price': 'pricing',
    'sales.stock_deduction_point': 'delivery',
    'sales.enable_delivery_notes': 'delivery',
    'sales.auto_generate_delivery': 'delivery',
    'sales.allow_negative_stock': 'delivery',
    'sales.commission_enabled': 'commissions',
    'sales.default_commission_rate': 'commissions',
    'sales.approval_workflow': 'approval',
    'sales.auto_approve_limit': 'approval',
    'sales.approval_thresholds': 'approval',
    'sales.revenue_account_id': 'gl_accounts',
    'sales.cogs_account_id': 'gl_accounts',
    'sales.receivable_account_id': 'gl_accounts',
    'sales.tax_payable_account_id': 'gl_accounts',
    'sales.discount_account_id': 'gl_accounts',
    'sales.revenue_account': 'gl_accounts',
    'sales.returns_account': 'gl_accounts',
    'sales.discount_account': 'gl_accounts',
  };

  // Purchases settings (loaded from /api/purchases/settings)
  purchasesSettingsLoading = signal(false);
  purchasesSettingsSaving = signal(false);
  purchasesSettings = signal<{ key: string; label: string; description: string; value_type: string; current_value: any; allowed_values: string[]; group: string }[]>([]);
  purchasesEditValues = signal<Record<string, any>>({});

  purchasesGroups = [
    { key: 'general', label: 'PURCHASES.GENERAL_SETTINGS', icon: 'pi pi-cog' },
    { key: 'pricing', label: 'PURCHASES.PRICING_SETTINGS', icon: 'pi pi-dollar' },
    { key: 'features', label: 'PURCHASES.FEATURES_SETTINGS', icon: 'pi pi-th-large' },
    { key: 'approval', label: 'PURCHASES.APPROVAL_SETTINGS', icon: 'pi pi-check-circle' },
    { key: 'gl_accounts', label: 'PURCHASES.GL_ACCOUNTS', icon: 'pi pi-book' },
  ];

  private purchasesGroupMap: Record<string, string> = {
    'purchases.default_warehouse_id': 'general',
    'purchases.default_tax_id': 'general',
    'purchases.default_cost_center_id': 'general',
    'purchases.default_payment_terms_days': 'general',
    'purchases.grn_mode': 'general',
    'purchases.vat_inclusive': 'pricing',
    'purchases.price_includes_tax': 'pricing',
    'purchases.enable_purchase_requests': 'features',
    'purchases.enable_supplier_price_lists': 'features',
    'purchases.enable_supplier_comparison': 'features',
    'purchases.approval_workflow': 'approval',
    'purchases.approval_thresholds': 'approval',
    'purchases.expense_account': 'gl_accounts',
    'purchases.returns_account': 'gl_accounts',
    'purchases.inventory_account_id': 'gl_accounts',
    'purchases.expense_account_id': 'gl_accounts',
    'purchases.payable_account_id': 'gl_accounts',
    'purchases.tax_receivable_account_id': 'gl_accounts',
    'purchases.discount_account_id': 'gl_accounts',
  };

  // Default accounts
  defaultCashAccount = signal<number | null>(null);
  defaultBankAccount = signal<number | null>(null);
  defaultCheckAccount = signal<number | null>(null);
  defaultClientAccount = signal<number | null>(null);
  defaultSupplierAccount = signal<number | null>(null);
  defaultExpenseAccount = signal<number | null>(null);
  defaultRevenueAccount = signal<number | null>(null);
  cashBankAccounts = signal<Account[]>([]);
  allDetailAccounts = signal<Account[]>([]);
  /** Header accounts under assets (for client parent) */
  assetHeaderAccounts = signal<Account[]>([]);
  /** Header accounts under liabilities (for supplier parent) */
  liabilityHeaderAccounts = signal<Account[]>([]);
  expenseAccounts = signal<Account[]>([]);
  revenueAccounts = signal<Account[]>([]);

  // Warehouses & Tax Rates for sales settings dropdowns
  warehouses = signal<any[]>([]);
  taxRates = signal<any[]>([]);

  ngOnInit(): void {
    this.store.dispatch(SettingsActions.loadSettings({}));
    this.store.dispatch(AccountsActions.loadAccounts({}));
    this.store.dispatch(WarehousesActions.loadWarehouses({}));
    this.store.dispatch(TaxRatesActions.loadTaxRates({}));
    this.store.select(selectAllWarehouses).subscribe(w => this.warehouses.set(w));
    this.store.select(selectAllTaxRates).subscribe(t => this.taxRates.set(t));
    this.store.select(selectAllAccounts).subscribe(accs => {
      this.accounts.set(accs);
      this.cashBankAccounts.set(accs);
      this.allDetailAccounts.set(accs);
      this.assetHeaderAccounts.set(accs.filter(a => a.classification === 'assets'));
      this.liabilityHeaderAccounts.set(accs.filter(a => a.classification === 'liabilities'));
      this.expenseAccounts.set(accs.filter(a => a.classification === 'expenses'));
      this.revenueAccounts.set(accs.filter(a => a.classification === 'revenue'));
    });
    this.settings$.subscribe(s => this.allSettings.set(s));
    this.loadProductDisplaySettings();
    this.loadAutoApproveSettings();
    this.loadDefaultAccounts();
    this.loadInventorySettings();
    this.loadSalesSettings();
    this.loadPurchasesSettings();
    this.loadPerpetualInventory();
    this.loadFeedbackButtonSetting();
  }

  private loadPerpetualInventory(): void {
    this.settingService.getByKey('sales.auto_create_stock_issue_on_invoice').subscribe({
      next: (res: any) => {
        const val = res?.data?.value ?? res?.value;
        this.perpetualInventory.set(val === 'true' || val === true || val === 'True');
      },
      error: () => {},
    });
  }

  togglePerpetualInventory(): void {
    const newVal = !this.perpetualInventory();
    this.perpetualInventory.set(newVal);
    this.perpetualInventorySaving.set(true);
    this.settingService.update({
      setting_key: 'sales.auto_create_stock_issue_on_invoice',
      value: String(newVal),
    }).subscribe({
      next: () => {
        this.perpetualInventorySaving.set(false);
        this.messageService.add({
          severity: 'success',
          summary: this.translate.instant('COMMON.SUCCESS'),
          detail: this.translate.instant('SETTINGS.SETTING_UPDATED'),
        });
      },
      error: () => {
        this.perpetualInventorySaving.set(false);
        this.perpetualInventory.set(!newVal);
      },
    });
  }

  private loadFeedbackButtonSetting(): void {
    this.settingService.getByKey('core.show_feedback_button').subscribe({
      next: (res: any) => {
        const val = res?.data?.value ?? res?.value;
        this.showFeedbackButton.set(val === 'true' || val === true || val === 'True' || val == null);
      },
      error: () => {},
    });
  }

  toggleFeedbackButton(): void {
    const newVal = !this.showFeedbackButton();
    this.showFeedbackButton.set(newVal);
    this.feedbackButtonSaving.set(true);
    this.settingService.update({
      setting_key: 'core.show_feedback_button',
      value: String(newVal),
    }).subscribe({
      next: () => {
        this.feedbackButtonSaving.set(false);
        this.messageService.add({
          severity: 'success',
          summary: this.translate.instant('COMMON.SUCCESS'),
          detail: this.translate.instant('SETTINGS.SETTING_UPDATED'),
        });
      },
      error: () => {
        this.feedbackButtonSaving.set(false);
        this.showFeedbackButton.set(!newVal);
      },
    });
  }

  private loadProductDisplaySettings(): void {
    this.settingService.getByKey('products.show_category_in_name').subscribe({
      next: (res: any) => {
        const val = res?.data?.value ?? res?.value ?? 'false';
        this.showCategoryInName.set(val === 'true');
      },
      error: () => {},
    });
    this.settingService.getByKey('products.min_search_chars').subscribe({
      next: (res: any) => {
        const val = parseInt(res?.data?.value ?? res?.value, 10);
        if (!isNaN(val) && val > 0) this.minSearchChars.set(val);
      },
      error: () => {},
    });
  }

  saveMinSearchChars(value: number): void {
    const clamped = Math.max(1, Math.min(10, value || 3));
    this.minSearchChars.set(clamped);
    this.productSettingsSaving.set(true);
    this.settingService.update({ setting_key: 'products.min_search_chars', value: String(clamped) }).subscribe({
      next: () => {
        this.productSettingsSaving.set(false);
        this.messageService.add({
          severity: 'success',
          summary: this.translate.instant('COMMON.SUCCESS'),
          detail: this.translate.instant('SETTINGS.SETTING_UPDATED'),
        });
      },
      error: () => {
        this.productSettingsSaving.set(false);
      },
    });
  }

  private loadAutoApproveSettings(): void {
    this.settingService.getByKey('accounting.expense_auto_approve').subscribe({
      next: (res: any) => { this.expenseAutoApprove.set((res?.data?.value ?? res?.value) === 'true'); },
      error: () => {},
    });
    this.settingService.getByKey('accounting.revenue_auto_approve').subscribe({
      next: (res: any) => { this.revenueAutoApprove.set((res?.data?.value ?? res?.value) === 'true'); },
      error: () => {},
    });
    this.settingService.getByKey('accounting.payment_voucher_auto_approve').subscribe({
      next: (res: any) => { this.paymentVoucherAutoApprove.set((res?.data?.value ?? res?.value) === 'true'); },
      error: () => {},
    });
    this.settingService.getByKey('accounting.receipt_voucher_auto_approve').subscribe({
      next: (res: any) => { this.receiptVoucherAutoApprove.set((res?.data?.value ?? res?.value) === 'true'); },
      error: () => {},
    });
  }

  toggleAutoApprove(type: 'expense' | 'revenue' | 'payment_voucher' | 'receipt_voucher'): void {
    const sigMap: Record<string, any> = {
      expense: this.expenseAutoApprove,
      revenue: this.revenueAutoApprove,
      payment_voucher: this.paymentVoucherAutoApprove,
      receipt_voucher: this.receiptVoucherAutoApprove,
    };
    const sig = sigMap[type];
    const newVal = !sig();
    sig.set(newVal);
    this.approveSettingSaving.set(true);
    const key = `accounting.${type}_auto_approve`;
    this.settingService.update({ setting_key: key, value: String(newVal) }).subscribe({
      next: () => {
        this.approveSettingSaving.set(false);
        this.messageService.add({
          severity: 'success',
          summary: this.translate.instant('COMMON.SUCCESS'),
          detail: this.translate.instant('SETTINGS.SETTING_UPDATED'),
        });
      },
      error: () => {
        this.approveSettingSaving.set(false);
        sig.set(!newVal);
      },
    });
  }

  private loadInventorySettings(): void {
    this.settingService.getByKey('inventory.count_auto_approve').subscribe({
      next: (res: any) => { this.countAutoApprove.set((res?.data?.value ?? res?.value) === 'true'); },
      error: () => {},
    });
    this.settingService.getByKey('inventory.receipt_auto_approve').subscribe({
      next: (res: any) => { this.receiptAutoApprove.set((res?.data?.value ?? res?.value) === 'true'); },
      error: () => {},
    });
    this.settingService.getByKey('inventory.issue_auto_approve').subscribe({
      next: (res: any) => { this.issueAutoApprove.set((res?.data?.value ?? res?.value) === 'true'); },
      error: () => {},
    });
  }

  toggleInventorySetting(type: 'count' | 'receipt' | 'issue'): void {
    const sigMap: Record<string, any> = {
      count: this.countAutoApprove,
      receipt: this.receiptAutoApprove,
      issue: this.issueAutoApprove,
    };
    const sig = sigMap[type];
    const newVal = !sig();
    sig.set(newVal);
    this.invSettingSaving.set(true);
    const key = `inventory.${type}_auto_approve`;
    this.settingService.update({ setting_key: key, value: String(newVal) }).subscribe({
      next: () => {
        this.invSettingSaving.set(false);
        this.messageService.add({
          severity: 'success',
          summary: this.translate.instant('COMMON.SUCCESS'),
          detail: this.translate.instant('SETTINGS.SETTING_UPDATED'),
        });
      },
      error: () => {
        this.invSettingSaving.set(false);
        sig.set(!newVal);
      },
    });
  }

  private loadDefaultAccounts(): void {
    const keys = [
      { key: 'accounting.default_cash_account', sig: this.defaultCashAccount },
      { key: 'accounting.default_bank_account', sig: this.defaultBankAccount },
      { key: 'accounting.default_check_account', sig: this.defaultCheckAccount },
      { key: 'accounting.default_client_account', sig: this.defaultClientAccount },
      { key: 'accounting.default_supplier_account', sig: this.defaultSupplierAccount },
      { key: 'accounting.default_expense_account', sig: this.defaultExpenseAccount },
      { key: 'accounting.default_revenue_account', sig: this.defaultRevenueAccount },
    ];
    for (const { key, sig } of keys) {
      this.settingService.getByKey(key).subscribe({
        next: (res: any) => {
          const val = res?.data?.value ?? res?.value;
          sig.set(val && val !== '0' ? Number(val) : null);
        },
        error: () => {},
      });
    }
  }

  saveDefaultAccount(key: string, value: number | null): void {
    this.approveSettingSaving.set(true);
    this.settingService.update({ setting_key: key, value: String(value || 0) }).subscribe({
      next: () => {
        this.approveSettingSaving.set(false);
        this.messageService.add({
          severity: 'success',
          summary: this.translate.instant('COMMON.SUCCESS'),
          detail: this.translate.instant('SETTINGS.SETTING_UPDATED'),
        });
      },
      error: () => { this.approveSettingSaving.set(false); },
    });
  }

  toggleShowCategoryInName(): void {
    const newVal = !this.showCategoryInName();
    this.showCategoryInName.set(newVal);
    this.productSettingsSaving.set(true);
    this.settingService.update({ setting_key: 'products.show_category_in_name', value: String(newVal) }).subscribe({
      next: () => {
        this.productSettingsSaving.set(false);
        this.messageService.add({
          severity: 'success',
          summary: this.translate.instant('COMMON.SUCCESS'),
          detail: this.translate.instant('SETTINGS.SETTING_UPDATED'),
        });
      },
      error: () => {
        this.productSettingsSaving.set(false);
        this.showCategoryInName.set(!newVal);
      },
    });
  }

  private loadSalesSettings(): void {
    this.salesSettingsLoading.set(true);
    this.salesSettingsService.getSettings().subscribe({
      next: (res) => {
        const isAr = this.lang.currentLang() === 'ar';
        const items = (res.data || []).map((item: any) => {
          const def = item.definition || {};
          return {
            key: def.setting_key,
            label: isAr ? (def.label_ar || def.label_en || def.label) : (def.label_en || def.label),
            description: isAr ? (def.description_ar || def.description_en || '') : (def.description_en || def.description || ''),
            value_type: def.value_type,
            current_value: item.current_value,
            allowed_values: def.allowed_values || [],
            group: this.salesGroupMap[def.setting_key] || 'general',
          };
        });
        this.salesSettings.set(items);
        const vals: Record<string, any> = {};
        items.forEach((s: any) => {
          if (s.value_type === 'boolean') {
            vals[s.key] = s.current_value === true || s.current_value === 'True' || s.current_value === '1' || s.current_value === 1;
          } else if (s.value_type === 'integer' || s.value_type === 'decimal') {
            vals[s.key] = s.current_value != null ? parseFloat(s.current_value) : null;
          } else if (s.value_type === 'json') {
            // Stringify JSON values for display in textarea
            vals[s.key] = typeof s.current_value === 'string' ? s.current_value : JSON.stringify(s.current_value, null, 2);
          } else {
            vals[s.key] = s.current_value;
          }
        });
        this.salesEditValues.set(vals);
        this.salesSettingsLoading.set(false);
      },
      error: () => this.salesSettingsLoading.set(false),
    });
  }

  getSalesGroupSettings(groupKey: string): any[] {
    return this.salesSettings().filter(s => s.group === groupKey);
  }

  updateSalesValue(key: string, value: any): void {
    this.salesEditValues.update(vals => ({ ...vals, [key]: value }));
  }

  isSalesAccountSetting(key: string): boolean {
    return key.endsWith('_account_id') || key.endsWith('_account');
  }

  isSalesWarehouseSetting(key: string): boolean {
    return key.endsWith('_warehouse_id');
  }

  isSalesTaxSetting(key: string): boolean {
    return key.endsWith('_tax_id');
  }

  getSalesEnumOptions(setting: any): { label: string; value: string }[] {
    return (setting.allowed_values || []).map((v: string) => ({
      label: v.replace(/_/g, ' ').replace(/\b\w/g, (l: string) => l.toUpperCase()),
      value: v,
    }));
  }

  saveSalesSettings(): void {
    this.salesSettingsSaving.set(true);
    const payload: Record<string, any> = {};
    const vals = this.salesEditValues();
    this.salesSettings().forEach((s: any) => {
      const shortKey = s.key.replace('sales.', '');
      let value = vals[s.key];
      // Convert 0 to null for optional foreign key fields to avoid validation errors
      if (shortKey.endsWith('_id') && (value === 0 || value === '0')) {
        value = null;
      }
      // Parse JSON strings back to objects/arrays
      if (s.value_type === 'json' && typeof value === 'string') {
        try { value = JSON.parse(value); } catch { /* keep as-is */ }
      }
      payload[shortKey] = value;
    });
    this.salesSettingsService.updateSettings(payload).subscribe({
      next: () => {
        this.salesSettingsSaving.set(false);
        this.messageService.add({
          severity: 'success',
          summary: this.translate.instant('COMMON.SUCCESS'),
          detail: this.translate.instant('SETTINGS.SETTING_UPDATED'),
        });
        this.loadSalesSettings();
      },
      error: (err) => {
        this.salesSettingsSaving.set(false);
        this.messageService.add({
          severity: 'error',
          summary: this.translate.instant('COMMON.ERROR'),
          detail: err.error?.message || 'Save failed',
        });
      },
    });
  }

  private loadPurchasesSettings(): void {
    this.purchasesSettingsLoading.set(true);
    this.purchasesSettingsService.getSettings().subscribe({
      next: (res) => {
        const isAr = this.lang.currentLang() === 'ar';
        const items = (res.data || []).map((item: any) => {
          const def = item.definition || {};
          return {
            key: def.setting_key,
            label: isAr ? (def.label_ar || def.label_en || def.label) : (def.label_en || def.label),
            description: isAr ? (def.description_ar || def.description_en || '') : (def.description_en || def.description || ''),
            value_type: def.value_type,
            current_value: item.current_value,
            allowed_values: def.allowed_values || [],
            group: this.purchasesGroupMap[def.setting_key] || 'general',
          };
        });
        this.purchasesSettings.set(items);
        const vals: Record<string, any> = {};
        items.forEach((s: any) => {
          if (s.value_type === 'boolean') {
            vals[s.key] = s.current_value === true || s.current_value === 'True' || s.current_value === '1' || s.current_value === 1;
          } else if (s.value_type === 'integer' || s.value_type === 'decimal') {
            vals[s.key] = s.current_value != null ? parseFloat(s.current_value) : null;
          } else if (s.value_type === 'json') {
            vals[s.key] = typeof s.current_value === 'string' ? s.current_value : JSON.stringify(s.current_value, null, 2);
          } else {
            vals[s.key] = s.current_value;
          }
        });
        this.purchasesEditValues.set(vals);
        this.purchasesSettingsLoading.set(false);
      },
      error: () => this.purchasesSettingsLoading.set(false),
    });
  }

  getPurchasesGroupSettings(groupKey: string): any[] {
    return this.purchasesSettings().filter(s => s.group === groupKey);
  }

  updatePurchasesValue(key: string, value: any): void {
    this.purchasesEditValues.update(vals => ({ ...vals, [key]: value }));
  }

  isPurchasesAccountSetting(key: string): boolean {
    return key.endsWith('_account_id') || key.endsWith('_account');
  }

  isPurchasesWarehouseSetting(key: string): boolean {
    return key.endsWith('_warehouse_id');
  }

  isPurchasesTaxSetting(key: string): boolean {
    return key.endsWith('_tax_id');
  }

  getPurchasesEnumOptions(setting: any): { label: string; value: string }[] {
    return (setting.allowed_values || []).map((v: string) => ({
      label: v.replace(/_/g, ' ').replace(/\b\w/g, (l: string) => l.toUpperCase()),
      value: v,
    }));
  }

  savePurchasesSettings(): void {
    this.purchasesSettingsSaving.set(true);
    const payload: Record<string, any> = {};
    const vals = this.purchasesEditValues();
    this.purchasesSettings().forEach((s: any) => {
      const shortKey = s.key.replace('purchases.', '');
      let value = vals[s.key];
      if (shortKey.endsWith('_id') && (value === 0 || value === '0')) {
        value = null;
      }
      if (s.value_type === 'json' && typeof value === 'string') {
        try { value = JSON.parse(value); } catch { /* keep as-is */ }
      }
      payload[shortKey] = value;
    });
    this.purchasesSettingsService.updateSettings(payload).subscribe({
      next: () => {
        this.purchasesSettingsSaving.set(false);
        this.messageService.add({
          severity: 'success',
          summary: this.translate.instant('COMMON.SUCCESS'),
          detail: this.translate.instant('SETTINGS.SETTING_UPDATED'),
        });
        this.loadPurchasesSettings();
      },
      error: (err) => {
        this.purchasesSettingsSaving.set(false);
        this.messageService.add({
          severity: 'error',
          summary: this.translate.instant('COMMON.ERROR'),
          detail: err.error?.message || 'Save failed',
        });
      },
    });
  }

  getModuleSettings(module: string): Setting[] {
    let settings = this.allSettings().filter(s => s.module === module);
    if (this.searchQuery.trim()) {
      const q = this.searchQuery.trim().toLowerCase();
      settings = settings.filter(s =>
        s.setting_key.toLowerCase().includes(q) ||
        s.label_ar.toLowerCase().includes(q) ||
        s.label_en.toLowerCase().includes(q)
      );
    }
    return settings;
  }

  get hasSearchResults(): boolean {
    if (!this.searchQuery.trim()) return true;
    return this.moduleTabs.some(m => this.getModuleSettings(m.value).length > 0);
  }

  isAccountSetting(setting: Setting): boolean {
    return setting.value_type === 'string' && setting.setting_key.endsWith('_account');
  }

  getAccountName(code: string): string {
    const acc = this.accounts().find(a => a.code === code);
    if (!acc) return code;
    const name = this.lang.currentLang() === 'ar' ? (acc.name_ar || acc.name) : (acc.name_en || acc.name);
    return `${acc.code} - ${name}`;
  }

  getLabel(setting: Setting): string {
    return this.lang.currentLang() === 'ar' ? setting.label_ar : setting.label_en;
  }

  getScopeSeverity(scope: string): 'info' | 'success' | 'warn' | 'danger' | 'secondary' {
    switch (scope) {
      case 'global': return 'danger';
      case 'company': return 'info';
      case 'branch': return 'warn';
      case 'user': return 'success';
      default: return 'secondary';
    }
  }

  startEdit(setting: Setting): void {
    this.editingKey.set(setting.setting_key);
    this.editValue = setting.current_value;
  }

  cancelEdit(): void {
    this.editingKey.set(null);
    this.editValue = null;
  }

  saveEdit(setting: Setting): void {
    this.saving.set(true);
    const data: UpdateSetting = {
      setting_key: setting.setting_key,
      value: this.editValue,
    };
    this.settingService.update(data).subscribe({
      next: () => {
        this.saving.set(false);
        this.editingKey.set(null);
        this.messageService.add({
          severity: 'success',
          summary: this.translate.instant('COMMON.SUCCESS'),
          detail: this.translate.instant('SETTINGS.SETTING_UPDATED'),
        });
        this.store.dispatch(SettingsActions.loadSettings({ forceReload: true }));
      },
      error: (err) => {
        this.saving.set(false);
        this.messageService.add({
          severity: 'error',
          summary: this.translate.instant('COMMON.ERROR'),
          detail: err.error?.message || 'Failed to update setting',
        });
      },
    });
  }

  resetToDefault(setting: Setting): void {
    this.editValue = setting.default_value;
    this.saveEdit(setting);
  }

  onTabChange(tab: string | number | undefined): void {
    if (tab != null) this.activeTab = String(tab);
    this.cancelEdit();
  }

  retry(): void {
    this.store.dispatch(SettingsActions.loadSettings({ forceReload: true }));
  }

  onSalesColorChange(color: string): void {
    this.moduleColorService.setSalesColor(color);
    this.messageService.add({
      severity: 'success',
      summary: this.translate.instant('COMMON.SUCCESS'),
      detail: this.translate.instant('SETTINGS.SETTING_UPDATED'),
    });
  }

  onPurchasesColorChange(color: string): void {
    this.moduleColorService.setPurchasesColor(color);
    this.messageService.add({
      severity: 'success',
      summary: this.translate.instant('COMMON.SUCCESS'),
      detail: this.translate.instant('SETTINGS.SETTING_UPDATED'),
    });
  }

  resetSalesColor(): void {
    this.moduleColorService.setSalesColor('#1a237e');
    this.messageService.add({
      severity: 'info',
      summary: this.translate.instant('COMMON.SUCCESS'),
      detail: this.translate.instant('SETTINGS.SETTING_UPDATED'),
    });
  }

  resetPurchasesColor(): void {
    this.moduleColorService.setPurchasesColor('#1a237e');
    this.messageService.add({
      severity: 'info',
      summary: this.translate.instant('COMMON.SUCCESS'),
      detail: this.translate.instant('SETTINGS.SETTING_UPDATED'),
    });
  }
}
