import { Component, inject, OnInit, OnDestroy, signal, ElementRef } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ActivatedRoute, RouterLink } from '@angular/router';
import {
  FormBuilder,
  FormGroup,
  FormArray,
  ReactiveFormsModule,
  Validators,
} from '@angular/forms';
import { Store } from '@ngrx/store';
import { TranslateModule, TranslateService } from '@ngx-translate/core';
import { Subscription, switchMap, of, concat, EMPTY, forkJoin, map } from 'rxjs';
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,
  UnitsActions,
  selectAllUnits,
  TaxRatesActions,
  selectAllTaxRates,
} from '../../../core/store';
import { SalesReturn } from '../../../core/models/sales-return.model';
import { SalesInvoice } from '../../../core/models/sales-invoice.model';
import { SalesReturnService } from '../../../core/services/sales-return.service';
import { SalesInvoiceService } from '../../../core/services/sales-invoice.service';
import { JournalEntryService } from '../../../core/services/journal-entry.service';
import { ProductService } from '../../../core/services/product.service';
import { WarehouseService } from '../../../core/services/warehouse.service';
import { SettingService } from '../../../core/services/setting.service';
import { JournalEntry } from '../../../core/models/journal-entry.model';
import { PrintService } from '../../../shared/print/print.service';
import { ModuleColorService } from '../../../core/services/module-color.service';
import { RETURN_PRINT_CONFIG } from './return-print.config';

@Component({
  selector: 'app-returns',
  standalone: true,
  imports: [
    CommonModule,
    ReactiveFormsModule,
    TranslateModule,
    TableModule,
    ButtonModule,
    DialogModule,
    InputTextModule,
    InputNumberModule,
    TextareaModule,
    SelectModule,
    DatePickerModule,
    TagModule,
    ToastModule,
    ConfirmDialogModule,
    TooltipModule,
    PageHeaderComponent,
    DataTableComponent,
    FormDialogComponent,
    SalesFilterBarComponent,
    RouterLink,
  ],
  providers: [MessageService, ConfirmationService],
  templateUrl: './returns.component.html',
  styleUrl: './returns.component.scss',
})
export class ReturnsComponent 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(SalesReturnService);
  private route = inject(ActivatedRoute);
  private invoiceService = inject(SalesInvoiceService);
  private journalEntryService = inject(JournalEntryService);
  private printService = inject(PrintService);
  private productService = inject(ProductService);
  private warehouseService = inject(WarehouseService);
  private settingService = inject(SettingService);
  private moduleColorService = inject(ModuleColorService);
  private elRef = inject(ElementRef);
  private langSub!: Subscription;

  readonly columns: TableColumn[] = [
    { field: 'return_number', header: 'SALES.RETURN_NUMBER' },
    { field: 'date', header: 'SALES.DATE', sortable: true },
    { field: 'invoice_number', header: 'SALES.INVOICE_NUMBER' },
    { field: 'customer_name', header: 'SALES.CUSTOMER' },
    { field: 'total', header: 'SALES.TOTAL', sortable: true },
    { field: 'status', header: 'SALES.STATUS' },
    { field: 'actions', header: 'COMMON.ACTIONS' },
  ];

  partners$ = this.store.select(selectAllPartners);

  tableData = signal<SalesReturn[]>([]);
  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: 'pending_approval' },
    { label: 'موافق عليه', value: 'approved' },
    { label: 'مرحّل', value: 'posted' },
    { label: 'ملغي', value: 'cancelled' },
  ];

  dialogVisible = signal(false);
  viewDialogVisible = signal(false);
  editingReturn = signal<SalesReturn | null>(null);
  viewingReturn = signal<SalesReturn | null>(null);
  revenueJe = signal<JournalEntry | null>(null);
  cogsJe = signal<JournalEntry | null>(null);
  jeLoading = signal(false);
  saving = signal(false);
  returnForm!: FormGroup;

  companyInfo = signal<any>(null);

  // Invoice selector
  invoices = signal<SalesInvoice[]>([]);
  loadingInvoiceItems = signal(false);
  selectedInvoice = signal<SalesInvoice | null>(null);
  customers = signal<any[]>([]);
  invoiceFullyReturned = signal(false);

  // Standalone mode
  standaloneMode = signal(false);
  products = signal<any[]>([]);
  warehouses = signal<any[]>([]);
  units = signal<any[]>([]);
  taxRates = signal<any[]>([]);

  // Field visibility for standalone mode
  fieldVisibility = signal<Record<string, boolean>>({
    warehouse: true,
    tax: true,
    discount: true,
  });
  fieldSettingsVisible = signal(false);
  defaultWarehouse = signal<number | null>(null);

  ngOnInit(): void {
    this.elRef.nativeElement.style.setProperty('--module-color', this.moduleColorService.salesColor());
    this.initForm();
    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.customers.set(p);
      this.filterCustomers.set(p);
    });
    // Load all returnable invoices (posted, partially_paid, paid, overdue)
    this.loadReturnableInvoices();

    // Load units, tax rates, warehouses for standalone mode
    this.store.dispatch(UnitsActions.loadUnits({}));
    this.store.dispatch(TaxRatesActions.loadTaxRates({}));
    this.store.select(selectAllUnits).subscribe(u => this.units.set(u));
    this.store.select(selectAllTaxRates).subscribe(t => this.taxRates.set(t));
    this.warehouseService.listForCurrentBranch().subscribe({
      next: (res) => {
        this.warehouses.set(res.data || res);
        if ((res.data || res).length > 0) this.defaultWarehouse.set((res.data || res)[0].id);
      },
      error: () => {},
    });

    // Load field visibility settings for standalone mode
    this.settingService.getByKey('sales.return_visible_fields').subscribe({
      next: (res: any) => {
        try {
          const val = res?.data?.value ?? res?.value;
          const parsed = typeof val === 'string' ? JSON.parse(val) : val;
          if (parsed) this.fieldVisibility.set({ ...this.fieldVisibility(), ...parsed });
        } catch {}
      },
      error: () => {},
    });

    // Handle deep-link viewId query param
    this.route.queryParams.subscribe((params) => {
      const viewId = params['viewId'];
      if (viewId) {
        const id = parseInt(viewId, 10);
        if (!isNaN(id)) {
          this.service.getById(id).subscribe({
            next: (res) => {
              if (res.data) this.viewReturn(res.data);
            },
          });
        }
      }
    });
  }

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

  private initForm(): void {
    this.returnForm = this.fb.group({
      invoice_id: [null],
      customer_id: [null],
      date: [new Date(), Validators.required],
      reason: ['', Validators.required],
      reason_ar: [''],
      notes: [''],
      notes_ar: [''],
      items: this.fb.array([]),
    });
  }

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

  toggleStandaloneMode(): void {
    const newMode = !this.standaloneMode();
    this.standaloneMode.set(newMode);
    this.items.clear();
    this.selectedInvoice.set(null);
    this.invoiceFullyReturned.set(false);
    if (newMode) {
      this.returnForm.get('invoice_id')?.clearValidators();
      this.returnForm.get('invoice_id')?.setValue(null);
      this.returnForm.get('customer_id')?.setValidators(Validators.required);
      this.addStandaloneItem();
      // Load products for dropdown
      this.productService.searchForDropdown('').subscribe({
        next: (res) => this.products.set(res.data || res),
        error: () => {},
      });
    } else {
      this.returnForm.get('invoice_id')?.setValidators(Validators.required);
      this.returnForm.get('customer_id')?.clearValidators();
      this.returnForm.get('customer_id')?.setValue(null);
    }
    this.returnForm.get('invoice_id')?.updateValueAndValidity();
    this.returnForm.get('customer_id')?.updateValueAndValidity();
  }

  addStandaloneItem(): void {
    this.items.push(this.fb.group({
      product_id: [null, Validators.required],
      unit_id: [null, Validators.required],
      warehouse_id: [this.defaultWarehouse()],
      quantity: [1, [Validators.required, Validators.min(0.01)]],
      unit_price: [0, [Validators.required, Validators.min(0)]],
      discount_percent: [0],
      tax_rate_id: [null],
    }));
  }

  removeStandaloneItem(index: number): void {
    if (this.items.length > 1) {
      this.items.removeAt(index);
    }
  }

  onStandaloneProductSelect(index: number, productId: number): void {
    const product = this.products().find((p: any) => p.id === productId);
    if (!product) return;
    const item = this.items.at(index);
    item.patchValue({
      unit_id: product.base_unit_id || product.unit_id,
      unit_price: parseFloat(product.sale_price) || 0,
      warehouse_id: item.get('warehouse_id')?.value || this.defaultWarehouse(),
    });
  }

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

  onProductSearch(event: any): void {
    const query = event?.filter || '';
    if (query.length < 2) return;
    this.productService.searchForDropdown(query).subscribe({
      next: (res) => this.products.set(res.data || res),
      error: () => {},
    });
  }

  getStandaloneLineTotal(index: number): number {
    const item = this.items.at(index);
    const qty = parseFloat(item.get('quantity')?.value) || 0;
    const price = parseFloat(item.get('unit_price')?.value) || 0;
    const discPct = parseFloat(item.get('discount_percent')?.value) || 0;
    const gross = qty * price;
    return gross - (gross * discPct / 100);
  }

  onInvoiceSelect(invoiceId: number): void {
    if (!invoiceId) return;
    this.loadingInvoiceItems.set(true);
    // Step 1: Fetch invoice + returns list in parallel
    forkJoin({
      invoice: this.invoiceService.getById(invoiceId),
      returns: this.service.list(1, 200, { invoice_id: invoiceId }),
    }).pipe(
      // Step 2: Fetch detail for each non-cancelled return (list doesn't include items)
      switchMap(({ invoice, returns }) => {
        const activeReturns = returns.data.filter(
          r => r.status !== 'cancelled' && !(this.editingReturn() && r.id === this.editingReturn()!.id)
        );
        if (activeReturns.length === 0) {
          return of({ invoice, returnDetails: [] as SalesReturn[] });
        }
        return forkJoin(activeReturns.map(r => this.service.getById(r.id))).pipe(
          map(details => ({ invoice, returnDetails: details.map(d => d.data) })),
        );
      }),
    ).subscribe({
      next: ({ invoice, returnDetails }) => {
        this.selectedInvoice.set(invoice.data);
        this.items.clear();
        // Sum up already-returned quantities per invoice_item_id
        const returnedMap = new Map<number, number>();
        for (const ret of returnDetails) {
          for (const ri of ret.items || []) {
            const itemId = ri.invoice_item_id ?? 0;
            const prev = returnedMap.get(itemId) || 0;
            returnedMap.set(itemId, prev + parseFloat(ri.quantity as any));
          }
        }
        let allFullyReturned = true;
        (invoice.data.items || []).forEach((item) => {
          const originalQty = parseFloat(item.quantity);
          const alreadyReturned = returnedMap.get(item.id) || 0;
          const remaining = Math.max(0, originalQty - alreadyReturned);
          if (remaining > 0) allFullyReturned = false;
          // Show all items — fully returned ones with remaining=0
          this.items.push(
            this.fb.group({
              invoice_item_id: [item.id],
              product_id: [item.product_id],
              product_name: [item.product_name],
              unit_id: [item.unit_id],
              unit_name: [item.unit_name],
              quantity: [0, [Validators.min(0)]],
              max_quantity: [remaining],
              original_quantity: [originalQty],
              unit_price: [parseFloat(item.unit_price)],
              warehouse_id: [item.warehouse_id],
              fully_returned: [remaining <= 0],
            })
          );
        });
        this.invoiceFullyReturned.set(
          (invoice.data.items || []).length > 0 && allFullyReturned
        );
        this.loadingInvoiceItems.set(false);
      },
      error: () => this.loadingInvoiceItems.set(false),
    });
  }

  openNew(): void {
    this.editingReturn.set(null);
    this.selectedInvoice.set(null);
    this.invoiceFullyReturned.set(false);
    this.standaloneMode.set(false);
    this.returnForm.reset({ date: new Date(), reason: '', reason_ar: '', notes: '', notes_ar: '' });
    this.returnForm.get('invoice_id')?.setValidators(Validators.required);
    this.returnForm.get('invoice_id')?.updateValueAndValidity();
    this.returnForm.get('customer_id')?.clearValidators();
    this.returnForm.get('customer_id')?.updateValueAndValidity();
    this.items.clear();
    this.dialogVisible.set(true);
  }

  editReturn(ret: SalesReturn): void {
    if (ret.status !== 'draft') return;
    this.editingReturn.set(ret);
    this.selectedInvoice.set(null);

    // Detect standalone return
    const isStandalone = !ret.invoice_id;
    this.standaloneMode.set(isStandalone);

    this.returnForm.patchValue({
      invoice_id: ret.invoice_id,
      customer_id: ret.customer_id,
      date: new Date(ret.date),
      reason: ret.reason || '',
      reason_ar: ret.reason_ar || '',
      notes: ret.notes || '',
      notes_ar: ret.notes_ar || '',
    });

    // Update validators
    if (isStandalone) {
      this.returnForm.get('invoice_id')?.clearValidators();
      this.returnForm.get('customer_id')?.setValidators(Validators.required);
      // Load products for dropdowns
      this.productService.searchForDropdown('').subscribe({
        next: (res) => this.products.set(res.data || res),
        error: () => {},
      });
    } else {
      this.returnForm.get('invoice_id')?.setValidators(Validators.required);
      this.returnForm.get('customer_id')?.clearValidators();
    }
    this.returnForm.get('invoice_id')?.updateValueAndValidity();
    this.returnForm.get('customer_id')?.updateValueAndValidity();

    this.items.clear();
    (ret.items || []).forEach((item) => {
      if (isStandalone) {
        this.items.push(this.fb.group({
          product_id: [item.product_id, Validators.required],
          unit_id: [item.unit_id, Validators.required],
          warehouse_id: [item.warehouse_id],
          quantity: [parseFloat(item.quantity), [Validators.required, Validators.min(0.01)]],
          unit_price: [parseFloat(item.unit_price), [Validators.required, Validators.min(0)]],
          discount_percent: [parseFloat(item.discount_percent) || 0],
          tax_rate_id: [item.tax_rate_id],
        }));
      } else {
        this.items.push(
          this.fb.group({
            invoice_item_id: [item.invoice_item_id],
            product_id: [item.product_id],
            product_name: [item.product_name],
            unit_id: [item.unit_id],
            unit_name: [item.unit_name],
            quantity: [parseFloat(item.quantity), [Validators.min(0)]],
            max_quantity: [999],
            unit_price: [parseFloat(item.unit_price)],
            warehouse_id: [item.warehouse_id],
          })
        );
      }
    });
    this.dialogVisible.set(true);
  }

  viewReturn(ret: SalesReturn): void {
    this.revenueJe.set(null);
    this.cogsJe.set(null);
    this.service.getById(ret.id).subscribe({
      next: (res) => {
        const r = res.data;
        this.viewingReturn.set(r);
        this.viewDialogVisible.set(true);
        this.loadReturnJournalEntries(r);
      },
      error: () => {
        this.viewingReturn.set(ret);
        this.viewDialogVisible.set(true);
        this.loadReturnJournalEntries(ret);
      },
    });
  }

  private loadReturnJournalEntries(ret: SalesReturn): void {
    if (!ret.journal_entry_id && !ret.cogs_journal_entry_id) return;
    this.jeLoading.set(true);
    let pending = 0;
    const done = () => { pending--; if (pending <= 0) this.jeLoading.set(false); };
    if (ret.journal_entry_id) {
      pending++;
      this.journalEntryService.getById(ret.journal_entry_id).subscribe({
        next: (res) => { this.revenueJe.set(res.data); done(); },
        error: () => done(),
      });
    }
    if (ret.cogs_journal_entry_id) {
      pending++;
      this.journalEntryService.getById(ret.cogs_journal_entry_id).subscribe({
        next: (res) => { this.cogsJe.set(res.data); done(); },
        error: () => done(),
      });
    }
    if (pending === 0) this.jeLoading.set(false);
  }

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

  deleteReturn(ret: SalesReturn): void {
    if (ret.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(ret.id).subscribe({
          next: () => {
            this.messageService.add({
              severity: 'success',
              summary: this.translate.instant('COMMON.SUCCESS'),
              detail: this.translate.instant('SALES.RETURN_DELETED'),
            });
            this.reloadCurrentPage();
          },
          error: (err) => this.showError(err),
        });
      },
    });
  }

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

  approveReturn(ret: SalesReturn): void {
    this.service.approve(ret.id).subscribe({
      next: () => {
        this.messageService.add({
          severity: 'success',
          summary: this.translate.instant('COMMON.SUCCESS'),
          detail: this.translate.instant('SALES.APPROVE') + ' - OK',
        });
        this.reloadCurrentPage();
      },
      error: (err) => this.showError(err),
    });
  }

  rejectReturn(ret: SalesReturn): void {
    this.service.reject(ret.id).subscribe({
      next: () => {
        this.messageService.add({
          severity: 'success',
          summary: this.translate.instant('COMMON.SUCCESS'),
          detail: this.translate.instant('SALES.REJECT') + ' - OK',
        });
        this.reloadCurrentPage();
      },
      error: (err) => this.showError(err),
    });
  }

  postReturn(ret: SalesReturn): void {
    this.confirmationService.confirm({
      message: this.translate.instant('SALES.CONFIRM_POST_RETURN'),
      header: this.translate.instant('COMMON.CONFIRM'),
      icon: 'pi pi-exclamation-triangle',
      accept: () => {
        this.service.post(ret.id).subscribe({
          next: () => {
            this.messageService.add({
              severity: 'success',
              summary: this.translate.instant('COMMON.SUCCESS'),
              detail: this.translate.instant('SALES.RETURN_POSTED'),
            });
            this.reloadCurrentPage();
          },
          error: (err) => this.showError(err),
        });
      },
    });
  }

  cancelReturn(ret: SalesReturn): 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(ret.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),
        });
      },
    });
  }

  private loadReturnableInvoices(): void {
    const statuses = ['posted', 'partially_paid', 'paid', 'overdue'];
    forkJoin(statuses.map(s => this.invoiceService.list(1, 200, { status: s }))).subscribe({
      next: (results) => {
        const all = results.flatMap(r => r.data);
        // Deduplicate by id
        const map = new Map<number, SalesInvoice>();
        all.forEach(inv => map.set(inv.id, inv));
        this.invoices.set(Array.from(map.values()).sort((a, b) => b.id - a.id));
      },
      error: () => {},
    });
  }

  private buildSaveData(fv: any, validItems: any[]): any {
    const inv = this.selectedInvoice();
    const data: any = {
      date: this.formatDate(fv.date),
      reason: fv.reason || undefined,
      reason_ar: fv.reason_ar || undefined,
      notes: fv.notes || undefined,
      notes_ar: fv.notes_ar || undefined,
    };

    if (this.standaloneMode()) {
      data.return_type = 'standalone';
      data.customer_id = fv.customer_id;
      data.items = validItems.map((c: any, idx: number) => ({
        product_id: c.value.product_id,
        unit_id: c.value.unit_id,
        quantity: c.value.quantity,
        unit_price: c.value.unit_price,
        discount_percent: c.value.discount_percent || 0,
        tax_rate_id: c.value.tax_rate_id || undefined,
        warehouse_id: c.value.warehouse_id || undefined,
        sort_order: idx + 1,
      }));
    } else {
      data.customer_id = inv?.customer_id || this.editingReturn()?.customer_id;
      data.invoice_id = fv.invoice_id;
      data.items = validItems.map((c: any, idx: number) => ({
        invoice_item_id: c.value.invoice_item_id,
        product_id: c.value.product_id,
        unit_id: c.value.unit_id,
        quantity: c.value.quantity,
        unit_price: c.value.unit_price,
        warehouse_id: c.value.warehouse_id || undefined,
        sort_order: idx + 1,
      }));
    }

    return data;
  }

  private isFormValid(fv: any, validItems: any[]): boolean {
    if (this.standaloneMode()) {
      // For standalone: need customer_id, date, reason, and at least one item with product_id
      const hasValidItems = validItems.length > 0 && validItems.every(c => c.get('product_id')?.value);
      return !!(fv.customer_id && fv.date && fv.reason) && hasValidItems;
    }
    return this.returnForm.valid && validItems.length > 0;
  }

  onSave(): void {
    const validItems = this.items.controls.filter(
      (c) => (parseFloat(c.get('quantity')?.value) || 0) > 0
    );
    const fv = this.returnForm.value;

    // For standalone, validate items have product_id
    if (this.standaloneMode()) {
      const hasValidItems = validItems.length > 0 && validItems.every(c => c.get('product_id')?.value);
      if (!hasValidItems) {
        this.messageService.add({
          severity: 'warn',
          summary: this.translate.instant('COMMON.ERROR'),
          detail: this.translate.instant('SALES.NO_RETURN_ITEMS'),
        });
        return;
      }
    }

    if (this.isFormValid(fv, validItems)) {
      this.saving.set(true);
      const data = this.buildSaveData(fv, validItems);

      const obs$ = this.editingReturn()
        ? this.service.update(this.editingReturn()!.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.editingReturn() ? 'SALES.RETURN_UPDATED' : 'SALES.RETURN_CREATED'
            ),
          });
          this.reloadCurrentPage();
        },
        error: (err) => {
          this.saving.set(false);
          this.showError(err);
        },
      });
    } else {
      this.returnForm.markAllAsTouched();
      if (validItems.length === 0) {
        this.messageService.add({
          severity: 'warn',
          summary: this.translate.instant('COMMON.ERROR'),
          detail: this.translate.instant('SALES.NO_RETURN_ITEMS'),
        });
      }
    }
  }

  /** Save & Process: create -> submit -> approve -> post in one click */
  onSaveAndProcess(): void {
    const validItems = this.items.controls.filter(
      (c) => (parseFloat(c.get('quantity')?.value) || 0) > 0
    );
    const fv = this.returnForm.value;

    // For standalone, validate items have product_id
    if (this.standaloneMode()) {
      const hasValidItems = validItems.length > 0 && validItems.every(c => c.get('product_id')?.value);
      if (!hasValidItems) {
        this.messageService.add({
          severity: 'warn',
          summary: this.translate.instant('COMMON.ERROR'),
          detail: this.translate.instant('SALES.NO_RETURN_ITEMS'),
        });
        return;
      }
    }

    if (!this.isFormValid(fv, validItems)) {
      this.returnForm.markAllAsTouched();
      if (validItems.length === 0) {
        this.messageService.add({
          severity: 'warn',
          summary: this.translate.instant('COMMON.ERROR'),
          detail: this.translate.instant('SALES.NO_RETURN_ITEMS'),
        });
      }
      return;
    }

    this.saving.set(true);
    const data = this.buildSaveData(fv, validItems);

    const isEdit = !!this.editingReturn();
    const createOrUpdate$ = isEdit
      ? this.service.update(this.editingReturn()!.id, data)
      : this.service.create(data);

    createOrUpdate$.pipe(
      switchMap((res: any) => {
        const ret: SalesReturn = res?.data;
        if (!ret?.id) return of(res);
        // Auto-chain: submit -> approve -> post
        if (ret.status === 'draft') {
          return this.service.submitApproval(ret.id).pipe(
            switchMap(() => this.service.approve(ret.id)),
            switchMap(() => this.service.post(ret.id)),
          );
        }
        if (ret.status === 'pending_approval') {
          return this.service.approve(ret.id).pipe(
            switchMap(() => this.service.post(ret.id)),
          );
        }
        if (ret.status === 'approved') {
          return this.service.post(ret.id);
        }
        return of(res);
      }),
    ).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('SALES.RETURN_POSTED'),
        });
        this.reloadCurrentPage();
      },
      error: (err) => {
        this.saving.set(false);
        // If posting failed but create succeeded, still close and reload
        if (err.error?.message?.includes('MovementType')) {
          this.dialogVisible.set(false);
          this.messageService.add({
            severity: 'warn',
            summary: this.translate.instant('COMMON.SUCCESS'),
            detail: this.translate.instant('SALES.RETURN_CREATED') + ' (' + this.translate.instant('SALES.APPROVED') + ')',
          });
          this.reloadCurrentPage();
        } else {
          this.showError(err);
        }
      },
    });
  }

  /** Quick process: submit -> approve -> post for existing returns */
  quickProcess(ret: SalesReturn): void {
    this.confirmationService.confirm({
      message: this.translate.instant('SALES.CONFIRM_POST_RETURN'),
      header: this.translate.instant('COMMON.CONFIRM'),
      icon: 'pi pi-check-circle',
      accept: () => {
        let chain$;
        if (ret.status === 'draft') {
          chain$ = this.service.submitApproval(ret.id).pipe(
            switchMap(() => this.service.approve(ret.id)),
            switchMap(() => this.service.post(ret.id)),
          );
        } else if (ret.status === 'pending_approval') {
          chain$ = this.service.approve(ret.id).pipe(
            switchMap(() => this.service.post(ret.id)),
          );
        } else if (ret.status === 'approved') {
          chain$ = this.service.post(ret.id);
        } else {
          return;
        }

        chain$.subscribe({
          next: () => {
            this.messageService.add({
              severity: 'success',
              summary: this.translate.instant('COMMON.SUCCESS'),
              detail: this.translate.instant('SALES.RETURN_POSTED'),
            });
            this.reloadCurrentPage();
          },
          error: (err) => {
            // If posting fails due to backend bug, still reload to show updated status
            if (err.error?.message?.includes('MovementType')) {
              this.messageService.add({
                severity: 'warn',
                summary: this.translate.instant('COMMON.SUCCESS'),
                detail: this.translate.instant('SALES.APPROVED'),
              });
              this.reloadCurrentPage();
            } else {
              this.showError(err);
            }
          },
        });
      },
    });
  }

  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 'posted': return 'success';
      case 'cancelled': return 'danger';
      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, ' ');
  }

  toggleField(field: string): void {
    const current = this.fieldVisibility();
    this.fieldVisibility.set({ ...current, [field]: !current[field] });
  }

  isFieldVisible(field: string): boolean {
    return this.fieldVisibility()[field] !== false;
  }

  saveFieldVisibility(): void {
    const data = { setting_key: 'sales.return_visible_fields', value: JSON.stringify(this.fieldVisibility()) };
    this.settingService.update(data).subscribe({
      next: () => {
        this.fieldSettingsVisible.set(false);
        this.messageService.add({
          severity: 'success',
          summary: this.translate.instant('COMMON.SUCCESS'),
          detail: this.translate.instant('SETTINGS.SETTING_UPDATED'),
        });
      },
      error: () => {},
    });
  }

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

  printReturn(r: any): void {
    this.printService.print(RETURN_PRINT_CONFIG, r, this.companyInfo());
  }

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