import { Component, inject, OnInit, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
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 { ToggleSwitchModule } from 'primeng/toggleswitch';
import { TextareaModule } from 'primeng/textarea';
import { DialogModule } from 'primeng/dialog';
import { TagModule } from 'primeng/tag';
import { ToastModule } from 'primeng/toast';
import { TabsModule } from 'primeng/tabs';
import { TooltipModule } from 'primeng/tooltip';
import { DatePickerModule } from 'primeng/datepicker';
import { ConfirmDialogModule } from 'primeng/confirmdialog';
import { ConfirmationService, MessageService } from 'primeng/api';
import { PageHeaderComponent } from '../../../shared';
import { PosTerminalService } from '../services/pos-terminal.service';
import { PosCouponService } from '../services/pos-coupon.service';
import { PosTerminal, Coupon } from '../models/pos.model';
import { LanguageService } from '../../../core/services/language.service';
import { Store } from '@ngrx/store';
import {
  selectAllBranches,
  BranchesActions,
  WarehousesActions,
  selectAllWarehouses,
  BankAccountsActions,
  selectAllBankAccounts,
} from '../../../core/store';

@Component({
  selector: 'app-pos-settings',
  standalone: true,
  imports: [
    CommonModule, FormsModule, TranslateModule,
    ButtonModule, InputTextModule, InputNumberModule,
    SelectModule, ToggleSwitchModule, TextareaModule,
    DialogModule, TagModule, ToastModule, TabsModule,
    TooltipModule, DatePickerModule, ConfirmDialogModule,
    PageHeaderComponent,
  ],
  providers: [MessageService, ConfirmationService],
  templateUrl: './pos-settings.component.html',
  styleUrl: './pos-settings.component.scss',
})
export class PosSettingsComponent implements OnInit {
  private terminalService = inject(PosTerminalService);
  private couponService = inject(PosCouponService);
  private message = inject(MessageService);
  private confirm = inject(ConfirmationService);
  private translate = inject(TranslateService);
  private store = inject(Store);
  lang = inject(LanguageService);

  activeTab = 'terminals';

  // Terminals
  terminals = signal<PosTerminal[]>([]);
  terminalsLoading = signal(true);
  showTerminalDialog = signal(false);
  terminalSaving = signal(false);
  editingTerminal = signal<PosTerminal | null>(null);
  terminalForm: any = {};

  // Coupons
  coupons = signal<Coupon[]>([]);
  couponsLoading = signal(true);
  showCouponDialog = signal(false);
  couponSaving = signal(false);
  editingCoupon = signal<Coupon | null>(null);
  couponForm: any = {};

  // Dropdowns
  branches = signal<any[]>([]);
  warehouses = signal<any[]>([]);
  bankAccounts = signal<any[]>([]);

  couponTypes = [
    { label: 'POS.PERCENTAGE', value: 'percentage' },
    { label: 'POS.FIXED_AMOUNT', value: 'fixed' },
  ];

  ngOnInit(): void {
    this.store.dispatch(BranchesActions.loadBranches({}));
    this.store.dispatch(WarehousesActions.loadWarehouses({}));
    this.store.dispatch(BankAccountsActions.loadBankAccounts({}));
    this.store.select(selectAllBranches).subscribe(b => this.branches.set(b));
    this.store.select(selectAllWarehouses).subscribe(w => this.warehouses.set(w));
    this.store.select(selectAllBankAccounts).subscribe(a => this.bankAccounts.set(a));
    this.loadTerminals();
    this.loadCoupons();
  }

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

  // ── Terminals ──
  loadTerminals(): void {
    this.terminalsLoading.set(true);
    this.terminalService.listAll().subscribe({
      next: (data) => { this.terminals.set(data); this.terminalsLoading.set(false); },
      error: () => this.terminalsLoading.set(false),
    });
  }

  openNewTerminal(): void {
    this.editingTerminal.set(null);
    this.terminalForm = {
      name: '', name_ar: '', code: '', is_active: true,
      branch_id: null, warehouse_id: null, receiving_account_id: null,
      allow_negative_stock: false, require_customer: true,
      default_tax_rate: null, receipt_header: '', receipt_footer: '',
      allow_discount: true, allow_price_override: false,
    };
    this.showTerminalDialog.set(true);
  }

  editTerminal(t: PosTerminal): void {
    this.editingTerminal.set(t);
    this.terminalForm = {
      name: t.name, name_ar: t.name_ar, code: t.code, is_active: t.is_active,
      branch_id: t.branch?.id, warehouse_id: t.warehouse?.id,
      receiving_account_id: this.getTerminalAccount(t.id),
      allow_negative_stock: t.settings?.allow_negative_stock ?? false,
      require_customer: t.settings?.require_customer ?? true,
      default_tax_rate: t.settings?.default_tax_rate,
      receipt_header: t.settings?.receipt_header ?? '',
      receipt_footer: t.settings?.receipt_footer ?? '',
      allow_discount: t.settings?.allow_discount ?? true,
      allow_price_override: t.settings?.allow_price_override ?? false,
    };
    this.showTerminalDialog.set(true);
  }

  saveTerminal(): void {
    const payload = {
      name: this.terminalForm.name,
      name_ar: this.terminalForm.name_ar,
      code: this.terminalForm.code,
      is_active: this.terminalForm.is_active,
      branch_id: this.terminalForm.branch_id,
      warehouse_id: this.terminalForm.warehouse_id,
      settings: {
        allow_negative_stock: this.terminalForm.allow_negative_stock,
        require_customer: this.terminalForm.require_customer,
        default_tax_rate: this.terminalForm.default_tax_rate,
        receipt_header: this.terminalForm.receipt_header,
        receipt_footer: this.terminalForm.receipt_footer,
        allow_discount: this.terminalForm.allow_discount,
        allow_price_override: this.terminalForm.allow_price_override,
      },
    };
    this.terminalSaving.set(true);
    const editing = this.editingTerminal();
    const obs = editing
      ? this.terminalService.update(editing.id, payload)
      : this.terminalService.create(payload);

    obs.subscribe({
      next: (res: any) => {
        this.terminalSaving.set(false);
        this.showTerminalDialog.set(false);
        // Save receiving_account_id locally (API doesn't support this field)
        const terminalId = editing?.id || res?.data?.id;
        if (terminalId) {
          this.setTerminalAccount(terminalId, this.terminalForm.receiving_account_id);
        }
        this.loadTerminals();
        this.message.add({
          severity: 'success',
          summary: this.translate.instant('COMMON.SUCCESS'),
          detail: this.translate.instant(editing ? 'COMMON.UPDATED' : 'COMMON.CREATED'),
        });
      },
      error: (err) => {
        this.terminalSaving.set(false);
        this.message.add({
          severity: 'error',
          summary: this.translate.instant('COMMON.ERROR'),
          detail: err.error?.message || 'Failed',
        });
      },
    });
  }

  // Store receiving_account_id per terminal in localStorage
  private getTerminalAccount(terminalId: number): number | null {
    try {
      const map = JSON.parse(localStorage.getItem('pos_terminal_accounts') || '{}');
      return map[terminalId] || null;
    } catch { return null; }
  }

  private setTerminalAccount(terminalId: number, accountId: number | null): void {
    try {
      const map = JSON.parse(localStorage.getItem('pos_terminal_accounts') || '{}');
      if (accountId) { map[terminalId] = accountId; } else { delete map[terminalId]; }
      localStorage.setItem('pos_terminal_accounts', JSON.stringify(map));
    } catch {}
  }

  getAccountName(terminalId: number): string {
    const accountId = this.getTerminalAccount(terminalId);
    if (!accountId) return '';
    const account = this.bankAccounts().find((a: any) => a.id === accountId);
    return account?.bank_name || account?.bank_name_ar || '';
  }

  deleteTerminal(t: PosTerminal): void {
    this.confirm.confirm({
      message: this.translate.instant('COMMON.CONFIRM_DELETE'),
      header: this.translate.instant('COMMON.DELETE'),
      icon: 'pi pi-trash',
      acceptButtonStyleClass: 'p-button-danger',
      accept: () => {
        this.terminalService.delete(t.id).subscribe({
          next: () => {
            this.loadTerminals();
            this.message.add({
              severity: 'success',
              summary: this.translate.instant('COMMON.SUCCESS'),
              detail: this.translate.instant('COMMON.DELETED'),
            });
          },
        });
      },
    });
  }

  // ── Coupons ──
  loadCoupons(): void {
    this.couponsLoading.set(true);
    this.couponService.getActiveCoupons().subscribe({
      next: (data) => { this.coupons.set(data); this.couponsLoading.set(false); },
      error: () => this.couponsLoading.set(false),
    });
  }

  openNewCoupon(): void {
    this.editingCoupon.set(null);
    this.couponForm = {
      code: '', type: 'percentage', value: 0,
      max_discount: null, min_order_amount: null,
      usage_limit: null, is_active: true,
      valid_from: new Date(), valid_to: new Date(),
    };
    this.showCouponDialog.set(true);
  }

  editCoupon(c: Coupon): void {
    this.editingCoupon.set(c);
    this.couponForm = {
      code: c.code, type: c.type, value: c.value,
      max_discount: c.max_discount, min_order_amount: c.min_order_amount,
      usage_limit: c.usage_limit, is_active: c.is_active ?? true,
      valid_from: c.valid_from ? new Date(c.valid_from) : new Date(),
      valid_to: c.valid_to ? new Date(c.valid_to) : new Date(),
    };
    this.showCouponDialog.set(true);
  }

  saveCoupon(): void {
    const f = this.couponForm;
    const payload = {
      code: f.code,
      type: f.type,
      value: f.value,
      max_discount: f.max_discount,
      min_order_amount: f.min_order_amount,
      usage_limit: f.usage_limit,
      is_active: f.is_active,
      valid_from: this.formatDate(f.valid_from),
      valid_to: this.formatDate(f.valid_to),
    };
    this.couponSaving.set(true);
    const editing = this.editingCoupon();
    const obs = editing
      ? this.couponService.update(editing.id, payload)
      : this.couponService.create(payload);

    obs.subscribe({
      next: () => {
        this.couponSaving.set(false);
        this.showCouponDialog.set(false);
        this.loadCoupons();
        this.message.add({
          severity: 'success',
          summary: this.translate.instant('COMMON.SUCCESS'),
          detail: this.translate.instant(editing ? 'COMMON.UPDATED' : 'COMMON.CREATED'),
        });
      },
      error: (err) => {
        this.couponSaving.set(false);
        this.message.add({
          severity: 'error',
          summary: this.translate.instant('COMMON.ERROR'),
          detail: err.error?.message || 'Failed',
        });
      },
    });
  }

  deleteCoupon(c: Coupon): void {
    this.confirm.confirm({
      message: this.translate.instant('COMMON.CONFIRM_DELETE'),
      header: this.translate.instant('COMMON.DELETE'),
      icon: 'pi pi-trash',
      acceptButtonStyleClass: 'p-button-danger',
      accept: () => {
        this.couponService.delete(c.id).subscribe({
          next: () => {
            this.loadCoupons();
            this.message.add({
              severity: 'success',
              summary: this.translate.instant('COMMON.SUCCESS'),
              detail: this.translate.instant('COMMON.DELETED'),
            });
          },
        });
      },
    });
  }

  private formatDate(d: Date): string {
    if (!d) return '';
    const y = d.getFullYear();
    const m = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    return `${y}-${m}-${day}`;
  }
}
