import { Component, inject, OnInit, OnDestroy, signal, ElementRef } from '@angular/core';
import { CommonModule } from '@angular/common';
import {
  FormBuilder,
  FormGroup,
  FormArray,
  ReactiveFormsModule,
  FormsModule,
  Validators,
} from '@angular/forms';
import { Store } from '@ngrx/store';
import { TranslateModule, TranslateService } from '@ngx-translate/core';
import { Subject, debounceTime, filter, switchMap, Subscription } from 'rxjs';
import { ProductService } from '../../../core/services/product.service';
import { PartnerService } from '../../../core/services/partner.service';
import { SettingService } from '../../../core/services/setting.service';
import { Product } from '../../../core/models/product.model';
import { TableModule } from 'primeng/table';
import { ButtonModule } from 'primeng/button';
import { DialogModule } from 'primeng/dialog';
import { InputTextModule } from 'primeng/inputtext';
import { InputNumberModule } from 'primeng/inputnumber';
import { TextareaModule } from 'primeng/textarea';
import { SelectModule } from 'primeng/select';
import { DatePickerModule } from 'primeng/datepicker';
import { TagModule } from 'primeng/tag';
import { ToastModule } from 'primeng/toast';
import { ConfirmDialogModule } from 'primeng/confirmdialog';
import { TooltipModule } from 'primeng/tooltip';
import { MessageService, ConfirmationService } from 'primeng/api';
import {
  PageHeaderComponent,
  DataTableComponent,
  FormDialogComponent,
  TableColumn,
  SalesFilterBarComponent,
} from '../../../shared';
import {
  CurrenciesActions,
  selectAllCurrencies,
  TaxRatesActions,
  selectAllTaxRates,
  UnitsActions,
  selectAllUnits,
  WarehousesActions,
  selectAllWarehouses,
} from '../../../core/store';
import {
  PurchaseOrder,
  PurchaseOrderItemPayload,
} from '../../../core/models/purchase-order.model';
import { PurchaseOrderService } from '../../../core/services/purchase-order.service';
import { PurchaseGrnService } from '../../../core/services/purchase-grn.service';
import { CreatePurchaseGrn, PurchaseGrnItemPayload } from '../../../core/models/purchase-grn.model';
import { PrintService } from '../../../shared/print/print.service';
import { ModuleColorService } from '../../../core/services/module-color.service';
import { PURCHASE_ORDER_PRINT_CONFIG } from './order-print.config';

@Component({
  selector: 'app-purchase-orders',
  standalone: true,
  imports: [
    CommonModule,
    ReactiveFormsModule,
    FormsModule,
    TranslateModule,
    TableModule,
    ButtonModule,
    DialogModule,
    InputTextModule,
    InputNumberModule,
    TextareaModule,
    SelectModule,
    DatePickerModule,
    TagModule,
    ToastModule,
    ConfirmDialogModule,
    TooltipModule,
    PageHeaderComponent,
    DataTableComponent,
    FormDialogComponent,
    SalesFilterBarComponent,
  ],
  providers: [MessageService, ConfirmationService],
  templateUrl: './orders.component.html',
  styleUrl: './orders.component.scss',
})
export class PurchaseOrdersComponent implements OnInit, OnDestroy {
  private fb = inject(FormBuilder);
  private store = inject(Store);
  private messageService = inject(MessageService);
  private confirmationService = inject(ConfirmationService);
  private translate = inject(TranslateService);
  private service = inject(PurchaseOrderService);
  private grnService = inject(PurchaseGrnService);
  private productService = inject(ProductService);
  private partnerService = inject(PartnerService);
  private settingService = inject(SettingService);
  private printService = inject(PrintService);
  private moduleColorService = inject(ModuleColorService);
  private elRef = inject(ElementRef);
  private langSub!: Subscription;

  readonly columns: TableColumn[] = [
    { field: 'order_number', header: 'PURCHASES.ORDER_NUMBER' },
    { field: 'date', header: 'PURCHASES.DATE', sortable: true },
    { field: 'expected_delivery_date', header: 'PURCHASES.EXPECTED_DELIVERY', sortable: true },
    { field: 'supplier_name', header: 'PURCHASES.SUPPLIER' },
    { field: 'total', header: 'PURCHASES.TOTAL', sortable: true },
    { field: 'status', header: 'PURCHASES.STATUS' },
    { field: 'receive_status', header: 'PURCHASES.RECEIVE_STATUS' },
    { field: 'bill_status', header: 'PURCHASES.BILL_STATUS' },
    { field: 'actions', header: 'COMMON.ACTIONS' },
  ];

  currencies$ = this.store.select(selectAllCurrencies);
  taxRates$ = this.store.select(selectAllTaxRates);
  units$ = this.store.select(selectAllUnits);
  warehouses$ = this.store.select(selectAllWarehouses);

  companyInfo = signal<any>(null);

  // Server-side product search
  searchedProducts = signal<Product[]>([]);
  searchLoading = signal(false);
  minSearchChars = signal(3);
  private searchSubject = new Subject<string>();
  private searchSub!: Subscription;

  // Server-side pagination
  tableData = signal<PurchaseOrder[]>([]);
  totalRecords = signal(0);
  tableLoading = signal(false);
  first = 0;
  rows = 25;

  // Filter bar
  activeFilters: Record<string, any> = {};
  filterSuppliers = signal<any[]>([]);
  readonly statusOptions = [
    { label: 'مسودة', value: 'draft' },
    { label: 'بانتظار الموافقة', value: 'pending_approval' },
    { label: 'معتمد', value: 'approved' },
    { label: 'مؤكد', value: 'confirmed' },
    { label: 'مستلم جزئياً', value: 'partially_received' },
    { label: 'مستلم', value: 'received' },
    { label: 'مفوتر جزئياً', value: 'partially_billed' },
    { label: 'مفوتر', value: 'billed' },
    { label: 'مغلق', value: 'closed' },
    { label: 'ملغي', value: 'cancelled' },
  ];

  dialogVisible = signal(false);
  viewDialogVisible = signal(false);
  editingOrder = signal<PurchaseOrder | null>(null);
  viewingOrder = signal<PurchaseOrder | null>(null);
  saving = signal(false);
  orderForm!: FormGroup;

  // Barcode scanner
  barcodeValue = signal('');
  barcodeLoading = signal(false);

  // Server-side supplier search
  searchedSuppliers = signal<any[]>([]);
  supplierSearchLoading = signal(false);
  private supplierSearchSubject = new Subject<string>();
  private supplierSearchSub!: Subscription;

  // Quick add supplier dialog
  quickAddVisible = signal(false);
  quickAddSaving = signal(false);
  quickAddForm!: FormGroup;

  // Create GRN dialog
  grnDialogVisible = signal(false);
  grnSaving = signal(false);
  grnWarehouseId = signal<number | null>(null);
  grnItems = signal<{ product_name: string; remaining: number; quantity: number; item_id: number; product_id: number; unit_id: number; unit_cost: number }[]>([]);
  grnOrderId = signal<number | null>(null);
  grnSupplierId = signal<number | null>(null);

  // Create Bill dialog
  billDialogVisible = signal(false);
  billSaving = signal(false);
  billItems = signal<{ product_name: string; remaining: number; quantity: number; item_id: number }[]>([]);
  billOrderId = signal<number | null>(null);

  ngOnInit(): void {
    this.elRef.nativeElement.style.setProperty('--module-color', this.moduleColorService.purchasesColor());
    this.initForm();
    this.initQuickAddForm();
    this.langSub = this.translate.onLangChange.subscribe(() => {});
    this.loadPage();
    this.printService.getCompanyWithLogo().subscribe(c => { if (c) this.companyInfo.set(c); });
    this.store.dispatch(CurrenciesActions.loadCurrencies({}));
    this.store.dispatch(TaxRatesActions.loadTaxRates({}));
    this.store.dispatch(UnitsActions.loadUnits({}));
    this.store.dispatch(WarehousesActions.loadWarehouses({}));

    // Load initial suppliers (filtered)
    this.partnerService.searchForDropdown('', { is_supplier: '1' }).subscribe({
      next: (res) => {
        if (res.data.length > 0) {
          this.searchedSuppliers.set(res.data);
          this.filterSuppliers.set(res.data);
        }
      },
      error: () => {},
    });

    // Server-side supplier search
    this.supplierSearchSub = this.supplierSearchSubject.pipe(
      debounceTime(300),
      filter(q => q.length >= 2),
      switchMap(q => {
        this.supplierSearchLoading.set(true);
        return this.partnerService.searchForDropdown(q, { is_supplier: '1' });
      }),
    ).subscribe({
      next: (res) => {
        this.searchedSuppliers.set(res.data);
        this.supplierSearchLoading.set(false);
      },
      error: () => this.supplierSearchLoading.set(false),
    });

    // Server-side product search
    this.searchSub = this.searchSubject.pipe(
      debounceTime(300),
      filter(q => q.length >= this.minSearchChars()),
      switchMap(q => {
        this.searchLoading.set(true);
        return this.productService.searchForDropdown(q);
      }),
    ).subscribe({
      next: (res) => {
        this.searchedProducts.set(res.data);
        this.searchLoading.set(false);
      },
      error: () => this.searchLoading.set(false),
    });

    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: () => {},
    });
  }

  ngOnDestroy(): void {
    this.langSub?.unsubscribe();
    this.searchSub?.unsubscribe();
    this.supplierSearchSub?.unsubscribe();
  }

  onSupplierSearch(event: { filter: string }): void {
    const q = event.filter?.trim() || '';
    if (q.length < 2) {
      this.searchedSuppliers.set([]);
      return;
    }
    this.supplierSearchSubject.next(q);
  }

  onProductSearch(event: { filter: string }): void {
    const q = event.filter?.trim() || '';
    if (q.length < this.minSearchChars()) {
      this.searchedProducts.set([]);
      return;
    }
    this.searchSubject.next(q);
  }

  private initForm(): void {
    const today = new Date();
    const expectedDelivery = new Date();
    expectedDelivery.setDate(expectedDelivery.getDate() + 14);

    this.orderForm = this.fb.group({
      supplier_id: [null, Validators.required],
      date: [today, Validators.required],
      expected_delivery_date: [expectedDelivery],
      warehouse_id: [null],
      currency_code: ['SAR'],
      exchange_rate: [1],
      payment_terms_days: [30],
      reference: [''],
      subject: [''],
      notes: [''],
      notes_ar: [''],
      terms: [''],
      terms_ar: [''],
      items: this.fb.array([]),
    });
  }

  private initQuickAddForm(): void {
    this.quickAddForm = this.fb.group({
      name_ar: ['', Validators.required],
      name_en: [''],
      phone: [''],
      email: [''],
    });
  }

  get items(): FormArray {
    return this.orderForm.get('items') as FormArray;
  }

  private createItem(item?: any): FormGroup {
    return this.fb.group({
      product_id: [item?.product_id || null, Validators.required],
      unit_id: [item?.unit_id || null, Validators.required],
      quantity: [item?.quantity || 1, [Validators.required, Validators.min(0.01)]],
      unit_cost: [item?.unit_cost || 0, [Validators.required, Validators.min(0)]],
      discount_percent: [item?.discount_percent || 0],
      tax_rate_id: [item?.tax_rate_id || null],
      description: [item?.description || ''],
      notes: [item?.notes || ''],
    });
  }

  addItem(): void {
    this.items.push(this.createItem());
  }

  removeItem(index: number): void {
    this.items.removeAt(index);
  }

  getLineTotal(index: number): number {
    const line = this.items.at(index);
    const qty = parseFloat(line.get('quantity')?.value) || 0;
    const price = parseFloat(line.get('unit_cost')?.value) || 0;
    const discountPct = parseFloat(line.get('discount_percent')?.value) || 0;
    const subtotal = qty * price;
    const discount = subtotal * (discountPct / 100);
    return subtotal - discount;
  }

  get subtotal(): number {
    let total = 0;
    for (let i = 0; i < this.items.length; i++) {
      total += this.getLineTotal(i);
    }
    return total;
  }

  get discountAmount(): number {
    let totalDiscount = 0;
    for (let i = 0; i < this.items.length; i++) {
      const line = this.items.at(i);
      const qty = parseFloat(line.get('quantity')?.value) || 0;
      const price = parseFloat(line.get('unit_cost')?.value) || 0;
      const discountPct = parseFloat(line.get('discount_percent')?.value) || 0;
      totalDiscount += qty * price * (discountPct / 100);
    }
    return totalDiscount;
  }

  get total(): number {
    return this.subtotal;
  }

  openNew(): void {
    this.editingOrder.set(null);
    const today = new Date();
    const expectedDelivery = new Date();
    expectedDelivery.setDate(expectedDelivery.getDate() + 14);
    this.orderForm.reset({
      supplier_id: null,
      date: today,
      expected_delivery_date: expectedDelivery,
      warehouse_id: null,
      currency_code: 'SAR',
      exchange_rate: 1,
      payment_terms_days: 30,
      reference: '',
      subject: '',
      notes: '',
      notes_ar: '',
      terms: '',
      terms_ar: '',
    });
    this.items.clear();
    this.addItem();
    this.dialogVisible.set(true);
  }

  editOrder(order: PurchaseOrder): void {
    if (order.status !== 'draft') return;
    this.editingOrder.set(order);
    this.dialogVisible.set(true);
    this.service.getById(order.id).subscribe({
      next: (res) => {
        const o = res.data;
        this.orderForm.patchValue({
          supplier_id: o.supplier_id,
          date: new Date(o.date),
          expected_delivery_date: o.expected_delivery_date
            ? new Date(o.expected_delivery_date)
            : null,
          warehouse_id: o.warehouse_id,
          currency_code: o.currency_code || 'SAR',
          exchange_rate: parseFloat(o.exchange_rate as any) || 1,
          payment_terms_days: o.payment_terms_days || 30,
          reference: o.reference || '',
          subject: o.subject || '',
          notes: o.notes || '',
          notes_ar: o.notes_ar || '',
          terms: o.terms || '',
          terms_ar: o.terms_ar || '',
        });
        this.items.clear();
        (o.items || []).forEach((item: any) => {
          this.items.push(
            this.createItem({
              product_id: item.product_id,
              unit_id: item.unit_id,
              quantity: parseFloat(item.quantity),
              unit_cost: parseFloat(item.unit_cost),
              discount_percent: parseFloat(item.discount_percent),
              tax_rate_id: item.tax_rate_id,
              description: item.description,
              notes: item.notes,
            })
          );
        });
        if (this.items.length === 0) {
          this.addItem();
        }
        // Ensure selected supplier is in dropdown
        if (o.supplier_id) {
          const existing = this.searchedSuppliers();
          if (!existing.find(s => s.id === o.supplier_id)) {
            this.partnerService.getById(o.supplier_id).subscribe({
              next: (r) => this.searchedSuppliers.set([...this.searchedSuppliers(), r.data]),
            });
          }
        }
        // Pre-load products for dropdown display
        const productIds = (o.items || []).map((i: any) => i.product_id).filter(Boolean);
        const uniqueIds = [...new Set(productIds)];
        if (uniqueIds.length > 0) {
          import('rxjs').then(({ forkJoin }) => {
            forkJoin(uniqueIds.map(id => this.productService.getById(id))).subscribe({
              next: (results) => {
                this.searchedProducts.set(results.map((r: any) => r.data));
              },
            });
          });
        }
      },
    });
  }

  viewOrder(order: PurchaseOrder): void {
    this.viewDialogVisible.set(true);
    this.viewingOrder.set(order);
    this.service.getById(order.id).subscribe({
      next: (res) => this.viewingOrder.set(res.data),
      error: () => {},
    });
  }

  loadPage(page = 1, perPage = this.rows): void {
    this.tableLoading.set(true);
    this.service.list(page, perPage, this.activeFilters).subscribe({
      next: (res) => {
        this.tableData.set(res.data);
        this.totalRecords.set(res.meta.total);
        this.tableLoading.set(false);
      },
      error: () => this.tableLoading.set(false),
    });
  }

  private reloadCurrentPage(): void {
    const currentPage = Math.floor(this.first / this.rows) + 1;
    this.loadPage(currentPage);
  }

  deleteOrder(order: PurchaseOrder): void {
    if (order.status !== 'draft') return;
    this.confirmationService.confirm({
      message: this.translate.instant('COMMON.CONFIRM_DELETE_MSG'),
      header: this.translate.instant('COMMON.CONFIRM'),
      icon: 'pi pi-exclamation-triangle',
      acceptButtonStyleClass: 'p-button-danger',
      accept: () => {
        this.service.delete(order.id).subscribe({
          next: () => {
            this.messageService.add({
              severity: 'success',
              summary: this.translate.instant('COMMON.SUCCESS'),
              detail: this.translate.instant('PURCHASES.ORDER_DELETED'),
            });
            this.reloadCurrentPage();
          },
          error: (err) => this.showError(err),
        });
      },
    });
  }

  submitApproval(order: PurchaseOrder): void {
    this.service.submitApproval(order.id).subscribe({
      next: () => {
        this.messageService.add({
          severity: 'success',
          summary: this.translate.instant('COMMON.SUCCESS'),
          detail: this.translate.instant('PURCHASES.SUBMITTED_APPROVAL'),
        });
        this.reloadCurrentPage();
      },
      error: (err) => this.showError(err),
    });
  }

  approveOrder(order: PurchaseOrder): void {
    this.service.approve(order.id).subscribe({
      next: () => {
        this.messageService.add({
          severity: 'success',
          summary: this.translate.instant('COMMON.SUCCESS'),
          detail: this.translate.instant('PURCHASES.ORDER_APPROVED'),
        });
        this.reloadCurrentPage();
      },
      error: (err) => this.showError(err),
    });
  }

  confirmOrder(order: PurchaseOrder): void {
    this.service.confirm(order.id).subscribe({
      next: () => {
        this.messageService.add({
          severity: 'success',
          summary: this.translate.instant('COMMON.SUCCESS'),
          detail: this.translate.instant('PURCHASES.ORDER_CONFIRMED'),
        });
        this.reloadCurrentPage();
      },
      error: (err) => this.showError(err),
    });
  }

  // --- Create GRN from PO ---
  openCreateGrn(order: PurchaseOrder): void {
    this.grnOrderId.set(order.id);
    this.grnSupplierId.set(order.supplier_id);
    this.grnWarehouseId.set(order.warehouse_id);
    this.service.getById(order.id).subscribe({
      next: (res) => {
        const items = (res.data.items || [])
          .filter((i: any) => i.remaining_receive_qty > 0)
          .map((i: any) => ({
            product_name: i.product_name,
            remaining: i.remaining_receive_qty,
            quantity: i.remaining_receive_qty,
            item_id: i.id,
            product_id: i.product_id,
            unit_id: i.unit_id,
            unit_cost: parseFloat(i.unit_cost) || 0,
          }));
        this.grnItems.set(items);
        this.grnDialogVisible.set(true);
      },
      error: (err) => this.showError(err),
    });
  }

  saveGrn(): void {
    const orderId = this.grnOrderId();
    const supplierId = this.grnSupplierId();
    const warehouseId = this.grnWarehouseId();
    if (!orderId || !supplierId || !warehouseId) return;
    this.grnSaving.set(true);
    const today = new Date().toISOString().slice(0, 10);
    const grnData: CreatePurchaseGrn = {
      date: today,
      purchase_order_id: orderId,
      supplier_id: supplierId,
      warehouse_id: warehouseId,
      items: this.grnItems()
        .filter(i => i.quantity > 0)
        .map(i => ({
          product_id: i.product_id,
          unit_id: i.unit_id,
          order_item_id: i.item_id,
          quantity: i.quantity,
          unit_cost: i.unit_cost,
        })),
    };
    this.grnService.create(grnData).subscribe({
      next: () => {
        this.grnSaving.set(false);
        this.grnDialogVisible.set(false);
        this.messageService.add({
          severity: 'success',
          summary: this.translate.instant('COMMON.SUCCESS'),
          detail: this.translate.instant('PURCHASES.GRN_CREATED'),
        });
        this.reloadCurrentPage();
      },
      error: (err) => {
        this.grnSaving.set(false);
        this.showError(err);
      },
    });
  }

  // --- Create Bill from PO ---
  openCreateBill(order: PurchaseOrder): void {
    this.billOrderId.set(order.id);
    this.service.getById(order.id).subscribe({
      next: (res) => {
        const items = (res.data.items || [])
          .filter((i: any) => i.remaining_bill_qty > 0)
          .map((i: any) => ({
            product_name: i.product_name,
            remaining: i.remaining_bill_qty,
            quantity: i.remaining_bill_qty,
            item_id: i.id,
          }));
        this.billItems.set(items);
        this.billDialogVisible.set(true);
      },
      error: (err) => this.showError(err),
    });
  }

  saveBill(): void {
    const orderId = this.billOrderId();
    if (!orderId) return;
    this.billSaving.set(true);
    const data: any = {
      items: this.billItems()
        .filter(i => i.quantity > 0)
        .map(i => ({ purchase_order_item_id: i.item_id, quantity: i.quantity })),
    };
    this.service.createBill(orderId, data).subscribe({
      next: () => {
        this.billSaving.set(false);
        this.billDialogVisible.set(false);
        this.messageService.add({
          severity: 'success',
          summary: this.translate.instant('COMMON.SUCCESS'),
          detail: this.translate.instant('PURCHASES.BILL_CREATED'),
        });
        this.reloadCurrentPage();
      },
      error: (err) => {
        this.billSaving.set(false);
        this.showError(err);
      },
    });
  }

  closeOrder(order: PurchaseOrder): void {
    this.confirmationService.confirm({
      message: this.translate.instant('COMMON.CONFIRM_ACTION'),
      header: this.translate.instant('COMMON.CONFIRM'),
      icon: 'pi pi-exclamation-triangle',
      accept: () => {
        this.service.close(order.id).subscribe({
          next: () => {
            this.messageService.add({
              severity: 'success',
              summary: this.translate.instant('COMMON.SUCCESS'),
              detail: this.translate.instant('PURCHASES.ORDER_CLOSED'),
            });
            this.reloadCurrentPage();
          },
          error: (err) => this.showError(err),
        });
      },
    });
  }

  duplicateOrder(order: PurchaseOrder): void {
    this.service.duplicate(order.id).subscribe({
      next: () => {
        this.messageService.add({
          severity: 'success',
          summary: this.translate.instant('COMMON.SUCCESS'),
          detail: this.translate.instant('PURCHASES.DUPLICATE') + ' - OK',
        });
        this.reloadCurrentPage();
      },
      error: (err) => this.showError(err),
    });
  }

  cancelOrder(order: PurchaseOrder): void {
    this.confirmationService.confirm({
      message: this.translate.instant('COMMON.CONFIRM_ACTION'),
      header: this.translate.instant('COMMON.CONFIRM'),
      icon: 'pi pi-exclamation-triangle',
      acceptButtonStyleClass: 'p-button-danger',
      accept: () => {
        this.service.cancel(order.id).subscribe({
          next: () => {
            this.messageService.add({
              severity: 'success',
              summary: this.translate.instant('COMMON.SUCCESS'),
              detail: this.translate.instant('PURCHASES.CANCEL') + ' - OK',
            });
            this.reloadCurrentPage();
          },
          error: (err) => this.showError(err),
        });
      },
    });
  }

  onSave(): void {
    if (this.orderForm.valid && this.items.length >= 1) {
      this.saving.set(true);
      const formValue = this.orderForm.value;
      const dateStr = this.formatDate(formValue.date);
      const expectedDeliveryStr = formValue.expected_delivery_date
        ? this.formatDate(formValue.expected_delivery_date)
        : undefined;

      const itemsPayload: PurchaseOrderItemPayload[] = formValue.items.map(
        (item: any, idx: number) => ({
          product_id: item.product_id,
          unit_id: item.unit_id,
          quantity: item.quantity,
          unit_cost: item.unit_cost,
          discount_percent: item.discount_percent || 0,
          tax_rate_id: item.tax_rate_id || undefined,
          description: item.description || undefined,
          notes: item.notes || undefined,
          sort_order: idx + 1,
        })
      );

      const data: any = {
        date: dateStr,
        expected_delivery_date: expectedDeliveryStr,
        supplier_id: formValue.supplier_id,
        warehouse_id: formValue.warehouse_id || undefined,
        currency_code: formValue.currency_code || undefined,
        exchange_rate: formValue.exchange_rate || undefined,
        payment_terms_days: formValue.payment_terms_days || undefined,
        reference: formValue.reference || undefined,
        subject: formValue.subject || undefined,
        notes: formValue.notes || undefined,
        notes_ar: formValue.notes_ar || undefined,
        terms: formValue.terms || undefined,
        terms_ar: formValue.terms_ar || undefined,
        items: itemsPayload,
      };

      const obs$ = this.editingOrder()
        ? this.service.update(this.editingOrder()!.id, data)
        : this.service.create(data);

      obs$.subscribe({
        next: () => {
          this.saving.set(false);
          this.dialogVisible.set(false);
          this.messageService.add({
            severity: 'success',
            summary: this.translate.instant('COMMON.SUCCESS'),
            detail: this.translate.instant(
              this.editingOrder() ? 'PURCHASES.ORDER_UPDATED' : 'PURCHASES.ORDER_CREATED'
            ),
          });
          this.reloadCurrentPage();
        },
        error: (err) => {
          this.saving.set(false);
          this.messageService.add({
            severity: 'error',
            summary: this.translate.instant('COMMON.ERROR'),
            detail: err.error?.message || 'Save failed',
          });
        },
      });
    } else {
      this.orderForm.markAllAsTouched();
      if (this.items.length === 0) {
        this.messageService.add({
          severity: 'warn',
          summary: this.translate.instant('COMMON.ERROR'),
          detail: this.translate.instant('PURCHASES.NO_ITEMS'),
        });
      }
    }
  }

  onFiltersChange(filters: Record<string, any>): void {
    // Remap customer_id to supplier_id for the filter bar
    if (filters['customer_id']) {
      filters['supplier_id'] = filters['customer_id'];
      delete filters['customer_id'];
    }
    this.activeFilters = filters;
    this.first = 0;
    this.loadPage(1);
  }

  onPageChange(event: any): void {
    this.first = event.first;
    this.rows = event.rows;
    const page = Math.floor(event.first / event.rows) + 1;
    this.loadPage(page, event.rows);
  }

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

  getStatusSeverity(
    status: string
  ): 'info' | 'warn' | 'success' | 'danger' | 'secondary' | 'contrast' {
    switch (status) {
      case 'draft':
        return 'secondary';
      case 'pending_approval':
        return 'warn';
      case 'approved':
        return 'success';
      case 'confirmed':
        return 'info';
      case 'partially_received':
        return 'warn';
      case 'received':
        return 'success';
      case 'partially_billed':
        return 'warn';
      case 'billed':
        return 'success';
      case 'cancelled':
        return 'danger';
      case 'closed':
        return 'secondary';
      default:
        return 'secondary';
    }
  }

  getStatusLabel(status: string): string {
    const key = 'PURCHASES.' + status.toUpperCase();
    const translated = this.translate.instant(key);
    return translated !== key ? translated : status.replace(/_/g, ' ');
  }

  getProductBarcode(productId: number): string | null {
    if (!productId) return null;
    const product = this.searchedProducts().find((p) => p.id === productId);
    return product?.barcode || null;
  }

  onBarcodeScan(event: Event): void {
    event.preventDefault();
    const barcode = this.barcodeValue().trim();
    if (!barcode) return;

    this.barcodeLoading.set(true);
    this.productService.lookupByBarcode(barcode).subscribe({
      next: (result) => {
        this.barcodeLoading.set(false);
        if (result) {
          this.addProductByBarcode(result.product);
        } else {
          this.messageService.add({
            severity: 'warn',
            summary: this.translate.instant('COMMON.WARNING'),
            detail: this.translate.instant('INVENTORY.BARCODE_NOT_FOUND'),
          });
        }
        this.barcodeValue.set('');
      },
      error: () => {
        this.barcodeLoading.set(false);
        this.barcodeValue.set('');
        this.messageService.add({
          severity: 'warn',
          summary: this.translate.instant('COMMON.WARNING'),
          detail: this.translate.instant('INVENTORY.BARCODE_NOT_FOUND'),
        });
      },
    });
  }

  private addProductByBarcode(product: Product): void {
    for (let i = 0; i < this.items.length; i++) {
      const row = this.items.at(i);
      if (row.get('product_id')?.value === product.id) {
        const currentQty = row.get('quantity')?.value || 0;
        row.patchValue({ quantity: currentQty + 1 });
        return;
      }
    }
    const current = this.searchedProducts();
    if (!current.find((p) => p.id === product.id)) {
      this.searchedProducts.set([...current, product]);
    }
    if (this.items.length > 0) {
      const lastRow = this.items.at(this.items.length - 1);
      if (!lastRow.get('product_id')?.value) {
        lastRow.patchValue({
          product_id: product.id,
          unit_id: product.base_unit_id || null,
          unit_cost: parseFloat(product.purchase_price) || 0,
          quantity: 1,
        });
        return;
      }
    }
    this.items.push(
      this.createItem({
        product_id: product.id,
        unit_id: product.base_unit_id || null,
        unit_cost: parseFloat(product.purchase_price) || 0,
        quantity: 1,
      }),
    );
  }

  openQuickAddSupplier(): void {
    this.quickAddForm.reset();
    this.quickAddVisible.set(true);
  }

  saveQuickSupplier(): void {
    if (!this.quickAddForm.valid) {
      this.quickAddForm.markAllAsTouched();
      return;
    }
    this.quickAddSaving.set(true);
    const val = this.quickAddForm.value;
    const data: any = {
      name: val.name_ar,
      name_ar: val.name_ar,
      name_en: val.name_en || val.name_ar,
      type: 'company',
      is_supplier: true,
    };
    if (val.phone) data.phone = val.phone;
    if (val.email) data.email = val.email;
    this.partnerService.create(data).subscribe({
      next: (res) => {
        this.quickAddSaving.set(false);
        this.quickAddVisible.set(false);
        const newSupplier = res.data;
        this.searchedSuppliers.set([...this.searchedSuppliers(), newSupplier]);
        this.orderForm.patchValue({ supplier_id: newSupplier.id });
        this.messageService.add({
          severity: 'success',
          summary: this.translate.instant('COMMON.SUCCESS'),
          detail: this.translate.instant('PURCHASES.SUPPLIER_ADDED'),
        });
      },
      error: (err) => {
        this.quickAddSaving.set(false);
        this.messageService.add({
          severity: 'error',
          summary: this.translate.instant('COMMON.ERROR'),
          detail: err.error?.message || 'Failed to create supplier',
        });
      },
    });
  }

  printOrder(o: any): void {
    this.printService.print(PURCHASE_ORDER_PRINT_CONFIG, o, this.companyInfo());
  }

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

  private showError(err: any): void {
    this.messageService.add({
      severity: 'error',
      summary: this.translate.instant('COMMON.ERROR'),
      detail: err.error?.message || 'Operation failed',
    });
  }
}
