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 {
  PartnersActions,
  selectAllPartners,
  CurrenciesActions,
  selectAllCurrencies,
  UsersActions,
  selectAllUsers,
  TaxRatesActions,
  selectAllTaxRates,
  UnitsActions,
  selectAllUnits,
} from '../../../core/store';
import {
  SalesOrder,
  SalesOrderItemPayload,
} from '../../../core/models/sales-order.model';
import { SalesOrderService } from '../../../core/services/sales-order.service';
import { SalesDeliveryNoteService } from '../../../core/services/sales-delivery-note.service';
import { CreateSalesDeliveryNote } from '../../../core/models/sales-delivery-note.model';
import { PrintService } from '../../../shared/print/print.service';
import { ModuleColorService } from '../../../core/services/module-color.service';
import { ORDER_PRINT_CONFIG } from './order-print.config';

@Component({
  selector: 'app-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 OrdersComponent 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(SalesOrderService);
  private deliveryNoteService = inject(SalesDeliveryNoteService);
  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: 'SALES.ORDER_NUMBER' },
    { field: 'date', header: 'SALES.DATE', sortable: true },
    { field: 'expected_delivery_date', header: 'SALES.EXPECTED_DELIVERY', sortable: true },
    { field: 'customer_name', header: 'SALES.CUSTOMER' },
    { field: 'salesperson_name', header: 'SALES.SALESPERSON' },
    { field: 'total', header: 'SALES.TOTAL', sortable: true },
    { field: 'status', header: 'SALES.STATUS' },
    { field: 'delivery_status', header: 'SALES.DELIVERY_STATUS' },
    { field: 'invoice_status', header: 'SALES.INVOICE_STATUS' },
    { field: 'actions', header: 'COMMON.ACTIONS' },
  ];

  partners$ = this.store.select(selectAllPartners);
  currencies$ = this.store.select(selectAllCurrencies);
  users$ = this.store.select(selectAllUsers);
  taxRates$ = this.store.select(selectAllTaxRates);
  units$ = this.store.select(selectAllUnits);

  // 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<SalesOrder[]>([]);
  totalRecords = signal(0);
  tableLoading = signal(false);
  first = 0;
  rows = 25;

  // Filter bar
  activeFilters: Record<string, any> = {};
  filterCustomers = signal<any[]>([]);
  readonly statusOptions = [
    { label: 'مسودة', value: 'draft' },
    { label: 'مؤكد', value: 'confirmed' },
    { label: 'قيد التنفيذ', value: 'in_progress' },
    { label: 'مكتمل', value: 'completed' },
    { label: 'ملغي', value: 'cancelled' },
  ];

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

  companyInfo = signal<any>(null);

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

  // Server-side customer search
  searchedCustomers = signal<any[]>([]);
  customerSearchLoading = signal(false);
  private customerSearchSubject = new Subject<string>();
  private customerSearchSub!: Subscription;

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

  ngOnInit(): void {
    this.elRef.nativeElement.style.setProperty('--module-color', this.moduleColorService.salesColor());
    this.initForm();
    this.initQuickAddForm();
    this.langSub = this.translate.onLangChange.subscribe(() => {});
    this.printService.getCompanyWithLogo().subscribe(c => { if (c) this.companyInfo.set(c); });
    this.loadPage();
    this.store.dispatch(PartnersActions.loadPartners({}));
    this.partners$.subscribe(p => this.filterCustomers.set(p));
    this.store.dispatch(CurrenciesActions.loadCurrencies({}));
    this.store.dispatch(UsersActions.loadUsers({}));
    this.store.dispatch(TaxRatesActions.loadTaxRates({}));
    this.store.dispatch(UnitsActions.loadUnits({}));

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

    // Server-side customer search
    this.customerSearchSub = this.customerSearchSubject.pipe(
      debounceTime(300),
      filter(q => q.length >= 2),
      switchMap(q => {
        this.customerSearchLoading.set(true);
        return this.partnerService.searchForDropdown(q, { is_customer: '1' });
      }),
    ).subscribe({
      next: (res) => {
        this.searchedCustomers.set(res.data);
        this.customerSearchLoading.set(false);
      },
      error: () => this.customerSearchLoading.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.customerSearchSub?.unsubscribe();
  }

  onCustomerSearch(event: { filter: string }): void {
    const q = event.filter?.trim() || '';
    if (q.length < 2) {
      this.searchedCustomers.set([]);
      return;
    }
    this.customerSearchSubject.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({
      customer_id: [null, Validators.required],
      date: [today, Validators.required],
      expected_delivery_date: [expectedDelivery],
      currency_code: ['SAR'],
      exchange_rate: [1],
      salesperson_id: [null],
      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_price: [item?.unit_price || 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_price')?.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_price')?.value) || 0;
      const discountPct = parseFloat(line.get('discount_percent')?.value) || 0;
      totalDiscount += qty * price * (discountPct / 100);
    }
    return totalDiscount;
  }

  get taxAmount(): number {
    return 0;
  }

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

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

  editOrder(order: SalesOrder): void {
    if (order.status !== 'draft') return;
    this.editingOrder.set(order);
    this.dialogVisible.set(true);
    // Fetch full detail to get items
    this.service.getById(order.id).subscribe({
      next: (res) => {
        const o = res.data;
        this.orderForm.patchValue({
          customer_id: o.customer_id,
          date: new Date(o.date),
          expected_delivery_date: o.expected_delivery_date
            ? new Date(o.expected_delivery_date)
            : null,
          currency_code: o.currency_code || 'SAR',
          exchange_rate: parseFloat(o.exchange_rate) || 1,
          salesperson_id: o.salesperson_id,
          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_price: parseFloat(item.unit_price),
              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 customer is in dropdown
        if (o.customer_id) {
          const existing = this.searchedCustomers();
          if (!existing.find(c => c.id === o.customer_id)) {
            this.partnerService.getById(o.customer_id).subscribe({
              next: (r) => this.searchedCustomers.set([...this.searchedCustomers(), 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: SalesOrder): 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: SalesOrder): 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('SALES.ORDER_DELETED'),
            });
            this.reloadCurrentPage();
          },
          error: (err) => {
            this.messageService.add({
              severity: 'error',
              summary: this.translate.instant('COMMON.ERROR'),
              detail: err.error?.message || 'Failed to delete',
            });
          },
        });
      },
    });
  }

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

  createDelivery(order: SalesOrder): void {
    // Fetch full order to get items with remaining delivery quantities
    this.service.getById(order.id).subscribe({
      next: (res) => {
        const fullOrder = res.data;
        const today = new Date().toISOString().slice(0, 10);
        const deliveryData: CreateSalesDeliveryNote = {
          date: today,
          order_id: fullOrder.id,
          customer_id: fullOrder.customer_id,
          warehouse_id: fullOrder.warehouse_id || 1,
          items: (fullOrder.items || [])
            .filter((i: any) => {
              const remaining = parseFloat(i.quantity) - parseFloat(i.delivered_quantity || '0');
              return remaining > 0;
            })
            .map((i: any) => ({
              product_id: i.product_id,
              product_variant_id: i.product_variant_id,
              unit_id: i.unit_id,
              warehouse_id: i.warehouse_id,
              order_item_id: i.id,
              quantity: parseFloat(i.quantity) - parseFloat(i.delivered_quantity || '0'),
            })),
        };
        this.deliveryNoteService.create(deliveryData).subscribe({
          next: () => {
            this.messageService.add({
              severity: 'success',
              summary: this.translate.instant('COMMON.SUCCESS'),
              detail: this.translate.instant('SALES.CREATE_DELIVERY') + ' - OK',
            });
            this.reloadCurrentPage();
          },
          error: (err) => this.showError(err),
        });
      },
      error: (err) => this.showError(err),
    });
  }

  createInvoice(order: SalesOrder): void {
    this.service.createInvoice(order.id, {}).subscribe({
      next: () => {
        this.messageService.add({
          severity: 'success',
          summary: this.translate.instant('COMMON.SUCCESS'),
          detail: this.translate.instant('SALES.CREATE_INVOICE') + ' - OK',
        });
        this.reloadCurrentPage();
      },
      error: (err) => this.showError(err),
    });
  }

  closeOrder(order: SalesOrder): 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('SALES.ORDER_CLOSED'),
            });
            this.reloadCurrentPage();
          },
          error: (err) => this.showError(err),
        });
      },
    });
  }

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

  cancelOrder(order: SalesOrder): 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('SALES.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: SalesOrderItemPayload[] = formValue.items.map(
        (item: any, idx: number) => ({
          product_id: item.product_id,
          unit_id: item.unit_id,
          quantity: item.quantity,
          unit_price: item.unit_price,
          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,
        customer_id: formValue.customer_id,
        salesperson_id: formValue.salesperson_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() ? 'SALES.ORDER_UPDATED' : 'SALES.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('SALES.NO_ITEMS'),
        });
      }
    }
  }

  onFiltersChange(filters: Record<string, any>): void {
    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 'in_delivery':
        return 'info';
      case 'partially_delivered':
        return 'warn';
      case 'delivered':
        return 'success';
      case 'partially_invoiced':
        return 'warn';
      case 'invoiced':
        return 'success';
      case 'cancelled':
        return 'danger';
      case 'closed':
        return 'secondary';
      default:
        return 'secondary';
    }
  }

  getStatusLabel(status: string): string {
    const key = 'SALES.' + 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 {
    // Check if product already exists in items - if so, increment quantity
    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;
      }
    }
    // Ensure product is in searchedProducts so dropdown can display it
    const current = this.searchedProducts();
    if (!current.find((p) => p.id === product.id)) {
      this.searchedProducts.set([...current, product]);
    }
    // If the last row is empty (no product selected), use it instead of adding a new row
    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_price: parseFloat(product.sale_price) || 0,
          quantity: 1,
        });
        return;
      }
    }
    // Add a brand new row
    this.items.push(
      this.createItem({
        product_id: product.id,
        unit_id: product.base_unit_id || null,
        unit_price: parseFloat(product.sale_price) || 0,
        quantity: 1,
      }),
    );
  }

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

  saveQuickCustomer(): 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: 'individual',
      is_customer: 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 newCustomer = res.data;
        this.searchedCustomers.set([...this.searchedCustomers(), newCustomer]);
        this.orderForm.patchValue({ customer_id: newCustomer.id });
        this.messageService.add({
          severity: 'success',
          summary: this.translate.instant('COMMON.SUCCESS'),
          detail: this.translate.instant('SALES.CUSTOMER_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 customer',
        });
      },
    });
  }

  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}`;
  }

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

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