import { Component, computed, inject, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { TranslateModule } from '@ngx-translate/core';
import { DialogModule } from 'primeng/dialog';
import { InputTextModule } from 'primeng/inputtext';
import { InputNumberModule } from 'primeng/inputnumber';
import { SelectModule } from 'primeng/select';
import { ButtonModule } from 'primeng/button';
import { input, output } from '@angular/core';
import { PosService } from '../../services/pos.service';
import {
  PosSession,
  ReturnItem,
  ReturnRequest,
  PaymentMethod,
} from '../../models/pos.model';

interface InvoiceItem {
  id: number;
  product_id: number;
  product_name: string;
  quantity: number;
  unit_price: number;
  return_qty: number;
  reason: string;
  selected: boolean;
}

@Component({
  selector: 'app-return-dialog',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    TranslateModule,
    DialogModule,
    InputTextModule,
    InputNumberModule,
    SelectModule,
    ButtonModule,
  ],
  templateUrl: './return-dialog.component.html',
  styleUrl: './return-dialog.component.scss',
})
export class ReturnDialogComponent {
  private readonly posService = inject(PosService);

  readonly session = input.required<PosSession>();
  readonly returnComplete = output<any>();
  readonly cancelled = output<void>();

  readonly invoiceSearch = signal('');
  readonly invoice = signal<any>(null);
  readonly invoiceItems = signal<InvoiceItem[]>([]);
  readonly refundMethod = signal<PaymentMethod>('cash');
  readonly loading = signal(false);
  readonly searching = signal(false);

  readonly refundMethods: { label: string; value: PaymentMethod }[] = [
    { label: 'POS.METHOD_CASH', value: 'cash' },
    { label: 'POS.METHOD_CARD', value: 'credit_card' },
    { label: 'POS.METHOD_TRANSFER', value: 'bank_transfer' },
  ];

  readonly selectedItems = computed(() =>
    this.invoiceItems().filter((item) => item.selected && item.return_qty > 0)
  );

  readonly refundTotal = computed(() =>
    this.selectedItems().reduce(
      (sum, item) => sum + item.return_qty * item.unit_price,
      0
    )
  );

  searchInvoice(): void {
    const query = this.invoiceSearch();
    if (!query) return;

    this.searching.set(true);
    this.posService.searchInvoice(query).subscribe({
      next: (res) => {
        this.searching.set(false);
        const invoices = res.data || [];
        if (invoices.length > 0) {
          const inv = invoices[0];
          this.invoice.set(inv);
          this.invoiceItems.set(
            (inv.items || []).map((item: any) => ({
              id: item.id,
              product_id: item.product_id,
              product_name: item.product?.name || item.description || '',
              quantity: item.quantity,
              unit_price: parseFloat(item.unit_price || '0'),
              return_qty: 0,
              reason: '',
              selected: false,
            }))
          );
        } else {
          this.invoice.set(null);
          this.invoiceItems.set([]);
        }
      },
      error: () => this.searching.set(false),
    });
  }

  toggleItem(index: number): void {
    const items = [...this.invoiceItems()];
    items[index] = {
      ...items[index],
      selected: !items[index].selected,
      return_qty: !items[index].selected ? items[index].quantity : 0,
    };
    this.invoiceItems.set(items);
  }

  updateReturnQty(index: number, qty: number): void {
    const items = [...this.invoiceItems()];
    items[index] = { ...items[index], return_qty: qty };
    this.invoiceItems.set(items);
  }

  updateReason(index: number, reason: string): void {
    const items = [...this.invoiceItems()];
    items[index] = { ...items[index], reason };
    this.invoiceItems.set(items);
  }

  processReturn(): void {
    const inv = this.invoice();
    if (!inv || this.selectedItems().length === 0) return;

    this.loading.set(true);
    const request: ReturnRequest = {
      invoice_id: inv.id,
      items: this.selectedItems().map((item) => ({
        invoice_item_id: item.id,
        product_id: item.product_id,
        return_qty: item.return_qty,
        reason: item.reason,
      })),
      refund_method: this.refundMethod(),
      session_id: this.session().id,
    };

    this.posService.createReturn(request).subscribe({
      next: (res) => {
        this.loading.set(false);
        this.returnComplete.emit(res.data);
      },
      error: () => this.loading.set(false),
    });
  }
}
