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 { TooltipModule } from 'primeng/tooltip';
import { MessageService } from 'primeng/api';
import { PageHeaderComponent } from '../../../shared';
import { SalesSettingsService } from '../../../core/services/sales-settings.service';
import { AccountsActions, selectAllAccounts } from '../../../core/store';
import { LanguageService } from '../../../core/services/language.service';

interface SettingItem {
  key: string;
  label: string;
  description: string;
  value_type: string;
  current_value: any;
  allowed_values?: string[];
  display_group: string;
}

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

  accounts$ = this.store.select(selectAllAccounts);

  loading = signal(true);
  saving = signal(false);
  settings = signal<SettingItem[]>([]);
  editValues = signal<Record<string, any>>({});

  // Group definitions
  groups = [
    { 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' },
  ];

  // Map setting keys to groups
  private groupMap: 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.invoice_print_template': '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',
  };

  ngOnInit(): void {
    this.store.dispatch(AccountsActions.loadAccounts({}));
    this.loadSettings();
  }

  loadSettings(): void {
    this.loading.set(true);
    this.service.getSettings().subscribe({
      next: (res) => {
        const items: SettingItem[] = (res.data || []).map((item: any) => {
          const def = item.definition || {};
          const isAr = this.lang.currentLang() === 'ar';
          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 || [],
            display_group: this.groupMap[def.setting_key] || 'general',
          };
        });
        this.settings.set(items);

        const vals: Record<string, any> = {};
        items.forEach((s) => {
          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 {
            vals[s.key] = s.current_value;
          }
        });
        this.editValues.set(vals);
        this.loading.set(false);
      },
      error: () => this.loading.set(false),
    });
  }

  getGroupSettings(groupKey: string): SettingItem[] {
    return this.settings().filter((s) => s.display_group === groupKey);
  }

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

  isAccountSetting(key: string): boolean {
    return key.endsWith('_account_id');
  }

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

  saveSettings(): void {
    this.saving.set(true);
    const payload: Record<string, any> = {};
    const vals = this.editValues();
    this.settings().forEach((s) => {
      const shortKey = s.key.replace('sales.', '');
      payload[shortKey] = vals[s.key];
    });

    this.service.updateSettings(payload).subscribe({
      next: () => {
        this.saving.set(false);
        this.messageService.add({
          severity: 'success',
          summary: this.translate.instant('COMMON.SUCCESS'),
          detail: this.translate.instant('COMMON.SAVED'),
        });
        this.loadSettings();
      },
      error: (err) => {
        this.saving.set(false);
        this.messageService.add({
          severity: 'error',
          summary: this.translate.instant('COMMON.ERROR'),
          detail: err.error?.message || 'Save failed',
        });
      },
    });
  }

  retry(): void {
    this.loadSettings();
  }
}
