'use client';

import { useEffect, useMemo, useState } from 'react';
import { useRouter } from 'next/navigation';
import { format } from 'date-fns';
import { Check, ChevronsUpDown } from 'lucide-react';

import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Textarea } from '@/components/ui/textarea';

import { useToast } from '@/hooks/use-toast';
import { cn } from '@/lib/utils';
import type { PurchaseCreditNote, PurchaseOrder, Supplier } from '@/lib/types';

interface PurchaseCreditNoteCreatePageClientProps {
  creditNotes: PurchaseCreditNote[];
  invoices: PurchaseOrder[];
  suppliers: Supplier[];
  t: Record<string, any>;
  currencySymbol: string;
}

export default function PurchaseCreditNoteCreatePageClient({
  creditNotes,
  invoices,
  suppliers,
  t,
  currencySymbol,
}: PurchaseCreditNoteCreatePageClientProps) {
  const router = useRouter();
  const { toast } = useToast();
  const SUPPLIER_SCOPE_ID = '__supplier_balance__';

  const [creditMode, setCreditMode] = useState<'items' | 'invoice-total' | 'supplier-total'>('items');
  const [selectedInvoiceId, setSelectedInvoiceId] = useState('');
  const [selectedSupplierId, setSelectedSupplierId] = useState('');
  const [invoicePickerOpen, setInvoicePickerOpen] = useState(false);
  const [invoiceSearchTerm, setInvoiceSearchTerm] = useState('');

  const [lockedSupplierId, setLockedSupplierId] = useState('');
  const [lockedByUser, setLockedByUser] = useState('');
  const [isLockBusy, setIsLockBusy] = useState(false);

  const [manualAmount, setManualAmount] = useState('0');
  const [selectedReason, setSelectedReason] = useState<PurchaseCreditNote['reason'] | undefined>(undefined);
  const [creditNoteDate, setCreditNoteDate] = useState(format(new Date(), 'yyyy-MM-dd'));
  const [createNotes, setCreateNotes] = useState('');
  const [isCreating, setIsCreating] = useState(false);
  const [draftItems, setDraftItems] = useState<Array<{ materialId: string; name: string; maxQty: number; quantity: number; unitPrice: number }>>([]);

  const selectedInvoice = invoices.find((inv) => inv.id === selectedInvoiceId);
  const selectedSupplier = suppliers.find((s) => s.id === selectedSupplierId);
  const previousCreditNotesForInvoice = useMemo(() => {
    if (!selectedInvoice) return [] as PurchaseCreditNote[];
    return creditNotes.filter(
      (note) => note.invoiceId === selectedInvoice.id && note.status !== 'cancelled'
    );
  }, [creditNotes, selectedInvoice]);
  const previousCreditsTotal = useMemo(
    () => previousCreditNotesForInvoice.reduce((sum, note) => sum + Number(note.grandTotal || 0), 0),
    [previousCreditNotesForInvoice]
  );
  const invoiceNetAfterCredits = useMemo(() => {
    if (!selectedInvoice) return 0;
    return Number(selectedInvoice.grandTotal || 0) - previousCreditsTotal;
  }, [selectedInvoice, previousCreditsTotal]);

  const filteredInvoices = useMemo(() => {
    const q = invoiceSearchTerm.trim().toLowerCase();
    if (!q) return invoices;
    return invoices.filter((invoice) => {
      const haystack = `${invoice.orderNumber} ${invoice.supplierName} ${invoice.supplierInvoiceNumber || ''}`.toLowerCase();
      return haystack.includes(q);
    });
  }, [invoices, invoiceSearchTerm]);

  const formatAmount = (amount: number) => `${currencySymbol}${Number(amount || 0).toFixed(2)}`;

  const releaseCreditLock = async (supplierId: string) => {
    if (!supplierId) return;
    try {
      await fetch('/api/admin/purchases/credit-notes/lock', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'release', supplierId }),
      });
    } catch {
      // Ignore lock release errors on UI side.
    }
  };

  const acquireCreditLock = async (supplierId: string) => {
    if (!supplierId) return false;
    setIsLockBusy(true);
    try {
      const response = await fetch('/api/admin/purchases/credit-notes/lock', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'acquire', supplierId }),
      });
      const data = await response.json().catch(() => ({}));

      if (!response.ok || !data?.success) {
        const by = String(data?.lockedBy || t.lockedByAnotherUser || 'مستخدم آخر');
        setLockedByUser(by);
        toast({
          title: t.warning ?? 'تنبيه',
          description: `${t.creditNoteLockedBy ?? 'يوجد مستخدم آخر يعمل على إشعار دائن لهذا المورد'}: ${by}`,
          variant: 'destructive',
        });
        return false;
      }

      setLockedSupplierId(supplierId);
      setLockedByUser('');
      return true;
    } catch {
      return false;
    } finally {
      setIsLockBusy(false);
    }
  };

  const handleChangeMode = async (mode: 'items' | 'invoice-total' | 'supplier-total') => {
    if (lockedSupplierId) {
      await releaseCreditLock(lockedSupplierId);
      setLockedSupplierId('');
    }
    setCreditMode(mode);
    setSelectedInvoiceId('');
    setSelectedSupplierId('');
    setManualAmount('0');
    setDraftItems([]);
  };

  const handleSelectInvoice = async (invoiceId: string) => {
    setSelectedInvoiceId(invoiceId);
    setInvoicePickerOpen(false);
    setInvoiceSearchTerm('');

    const invoice = invoices.find((inv) => inv.id === invoiceId);
    if (!invoice) {
      setDraftItems([]);
      return;
    }

    if (lockedSupplierId && lockedSupplierId !== invoice.supplierId) {
      await releaseCreditLock(lockedSupplierId);
      setLockedSupplierId('');
    }
    await acquireCreditLock(invoice.supplierId);

    const mapped = invoice.items.map((item) => ({
      materialId: item.materialId,
      name: item.name,
      maxQty: Number(item.quantity || 0),
      quantity: 0,
      unitPrice: Number(item.unitPrice || 0),
    }));
    setDraftItems(mapped);
  };

  const handleSelectSupplierForGeneralCredit = async (supplierId: string) => {
    setSelectedSupplierId(supplierId);
    if (lockedSupplierId && lockedSupplierId !== supplierId) {
      await releaseCreditLock(lockedSupplierId);
      setLockedSupplierId('');
    }
    await acquireCreditLock(supplierId);
  };

  const updateDraftQty = (index: number, value: string) => {
    const parsed = Number(value || 0);
    setDraftItems((prev) =>
      prev.map((it, i) => {
        if (i !== index) return it;
        const normalized = Number.isFinite(parsed) ? Math.max(0, Math.min(parsed, it.maxQty)) : 0;
        return { ...it, quantity: normalized };
      })
    );
  };

  const submitCreateCreditNote = async () => {
    if (lockedByUser) {
      toast({
        title: t.warning ?? 'تنبيه',
        description: `${t.creditNoteLockedBy ?? 'يوجد مستخدم آخر يعمل على إشعار دائن لهذا المورد'}: ${lockedByUser}`,
        variant: 'destructive',
      });
      return;
    }

    if (!selectedReason) {
      toast({
        title: t.error ?? 'خطأ',
        description: t.selectReasonRequired ?? 'يرجى اختيار سبب التخفيض من القائمة',
        variant: 'destructive',
      });
      return;
    }

    const requiresInvoice = creditMode === 'items' || creditMode === 'invoice-total';
    if (requiresInvoice && !selectedInvoice) {
      toast({
        title: t.error ?? 'خطأ',
        description: t.selectInvoice ?? 'اختر الفاتورة الأصلية',
        variant: 'destructive',
      });
      return;
    }

    if (creditMode === 'supplier-total' && !selectedSupplier) {
      toast({
        title: t.error ?? 'خطأ',
        description: t.selectSupplier ?? 'اختر المورد',
        variant: 'destructive',
      });
      return;
    }

    const activeItems = draftItems.filter((it) => it.quantity > 0);
    if (creditMode === 'items' && activeItems.length === 0) {
      toast({
        title: t.error ?? 'خطأ',
        description: t.creditNoteEmptyItems ?? 'يجب إضافة أصنافًا واحدًا على الأقل',
        variant: 'destructive',
      });
      return;
    }

    const payloadItems = activeItems.map((item, idx) => {
      const total = Number((item.quantity * item.unitPrice).toFixed(2));
      return {
        id: `tmp-${idx + 1}`,
        creditNoteId: '',
        materialId: item.materialId,
        name: item.name,
        quantity: item.quantity,
        unitPrice: item.unitPrice,
        total,
      };
    });

    const itemsTotal = Number(payloadItems.reduce((sum, it) => sum + it.total, 0).toFixed(2));
    const enteredAmount = Number(manualAmount || 0);
    const subTotal = creditMode === 'items' ? itemsTotal : Number(enteredAmount.toFixed(2));

    if (!Number.isFinite(subTotal) || subTotal <= 0) {
      toast({
        title: t.error ?? 'خطأ',
        description: t.creditNoteAmountRequired ?? 'قيمة الإشعار مطلوبة',
        variant: 'destructive',
      });
      return;
    }

    const effectiveSupplierId = creditMode === 'supplier-total' ? selectedSupplier!.id : selectedInvoice!.supplierId;
    const effectiveSupplierName = creditMode === 'supplier-total' ? selectedSupplier!.name : selectedInvoice!.supplierName;
    const effectiveInvoiceId = creditMode === 'supplier-total' ? SUPPLIER_SCOPE_ID : selectedInvoice!.id;
    const effectiveCurrency = creditMode === 'supplier-total' ? undefined : selectedInvoice!.currencyCode;
    const effectiveBaseCurrency = creditMode === 'supplier-total' ? undefined : selectedInvoice!.baseCurrencyCode;
    const effectiveExchangeRate = creditMode === 'supplier-total' ? undefined : selectedInvoice!.exchangeRate;
    const effectiveWarehouseId = creditMode === 'supplier-total' ? undefined : selectedInvoice!.warehouseId;
    const grandTotalBase = effectiveExchangeRate ? Number((subTotal * effectiveExchangeRate).toFixed(2)) : subTotal;

    setIsCreating(true);
    try {
      const response = await fetch('/api/admin/purchases/credit-notes', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          creditScope: creditMode,
          invoiceId: effectiveInvoiceId,
          supplierId: effectiveSupplierId,
          supplierName: effectiveSupplierName,
          date: creditNoteDate,
          currencyCode: effectiveCurrency,
          baseCurrencyCode: effectiveBaseCurrency,
          exchangeRate: effectiveExchangeRate,
          warehouseId: effectiveWarehouseId,
          items: creditMode === 'items' ? payloadItems : [],
          subTotal,
          totalDiscount: 0,
          taxAmount: 0,
          grandTotal: subTotal,
          grandTotalBase,
          reason: selectedReason,
          notes: createNotes.trim() || undefined,
        }),
      });

      const data = await response.json().catch(() => ({}));
      if (!response.ok) {
        throw new Error(data?.error || t.operationFailed || 'Failed to create credit note');
      }

      toast({
        title: t.success ?? 'نجاح',
        description: t.creditNoteCreatedSuccess ?? 'تم إنشاء إشعار الدائن بنجاح',
      });

      if (lockedSupplierId) {
        await releaseCreditLock(lockedSupplierId);
      }

      router.push('/admin/purchases/credit-notes');
      router.refresh();
    } catch (error) {
      toast({
        title: t.error ?? 'خطأ',
        description: error instanceof Error ? error.message : (t.operationFailed ?? 'فشلت العملية'),
        variant: 'destructive',
      });
    } finally {
      setIsCreating(false);
    }
  };

  useEffect(() => {
    if (!lockedSupplierId) return;
    const timer = setInterval(() => {
      void acquireCreditLock(lockedSupplierId);
    }, 60000);
    return () => clearInterval(timer);
  }, [lockedSupplierId]);

  useEffect(() => {
    return () => {
      if (lockedSupplierId) {
        void releaseCreditLock(lockedSupplierId);
      }
    };
  }, [lockedSupplierId]);

  return (
    <Card>
      <CardHeader>
        <CardTitle>{t.newCreditNoteTab ?? 'إنشاء إشعار جديد'}</CardTitle>
        <CardDescription>{t.createCreditNoteDescription ?? 'إصدار إشعار دائن يقلل من ذمة المورد.'}</CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div className="space-y-2 md:col-span-2">
            <Label>{t.creditNoteScope ?? 'نوع إشعار الدائن'}</Label>
            <Select value={creditMode} onValueChange={(v) => void handleChangeMode(v as 'items' | 'invoice-total' | 'supplier-total')}>
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="items">{t.creditScopeItems ?? 'على مستوى الأصناف'}</SelectItem>
                <SelectItem value="invoice-total">{t.creditScopeInvoiceTotal ?? 'خصم إجمالي على الفاتورة'}</SelectItem>
                <SelectItem value="supplier-total">{t.creditScopeSupplierTotal ?? 'خصم عام على رصيد المورد'}</SelectItem>
              </SelectContent>
            </Select>
          </div>

          {creditMode === 'supplier-total' ? (
            <div className="space-y-2">
              <Label>{t.selectSupplier ?? 'اختر المورد'}</Label>
              <Select value={selectedSupplierId} onValueChange={(v) => void handleSelectSupplierForGeneralCredit(v)}>
                <SelectTrigger>
                  <SelectValue placeholder={t.selectSupplier ?? 'اختر المورد'} />
                </SelectTrigger>
                <SelectContent>
                  {suppliers.map((supplier) => (
                    <SelectItem key={supplier.id} value={supplier.id}>
                      {supplier.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          ) : (
            <div className="space-y-2">
              <Label>{t.selectInvoice ?? 'اختر الفاتورة الأصلية'}</Label>
              <Popover open={invoicePickerOpen} onOpenChange={setInvoicePickerOpen}>
                <PopoverTrigger asChild>
                  <Button
                    type="button"
                    variant="outline"
                    role="combobox"
                    className={cn('w-full justify-between', !selectedInvoice && 'text-muted-foreground')}
                  >
                    {selectedInvoice
                      ? `${selectedInvoice.orderNumber} - ${selectedInvoice.supplierName}`
                      : (t.selectInvoice ?? 'اختر الفاتورة الأصلية')}
                    <ChevronsUpDown className="ms-2 h-4 w-4 shrink-0 opacity-50" />
                  </Button>
                </PopoverTrigger>
                <PopoverContent className="w-[--radix-popover-trigger-width] p-0">
                  <div className="p-2 border-b">
                    <Input
                      placeholder={t.searchInvoicePlaceholder ?? 'ابحث برقم الفاتورة أو اسم المورد...'}
                      value={invoiceSearchTerm}
                      onChange={(e) => setInvoiceSearchTerm(e.target.value)}
                      autoFocus
                    />
                  </div>
                  <div className="max-h-60 overflow-y-auto">
                    {filteredInvoices.length > 0 ? (
                      filteredInvoices.map((invoice) => (
                        <button
                          key={invoice.id}
                          type="button"
                          onClick={() => void handleSelectInvoice(invoice.id)}
                          className={cn(
                            'w-full flex items-center gap-2 text-start px-2 py-1.5 text-sm hover:bg-accent',
                            invoice.id === selectedInvoiceId && 'bg-accent'
                          )}
                        >
                          <Check className={cn('h-4 w-4', invoice.id === selectedInvoiceId ? 'opacity-100' : 'opacity-0')} />
                          <span className="flex-1">{invoice.orderNumber} - {invoice.supplierName}</span>
                          <span className="text-xs text-muted-foreground">{formatAmount(invoice.grandTotal)}</span>
                        </button>
                      ))
                    ) : (
                      <div className="px-3 py-4 text-center text-sm text-muted-foreground">
                        {t.noInvoicesFound ?? 'لا توجد نتائج'}
                      </div>
                    )}
                  </div>
                </PopoverContent>
              </Popover>
            </div>
          )}

          <div className="space-y-2">
            <Label>{t.creditNoteDateLabel ?? 'تاريخ الإشعار'}</Label>
            <Input type="date" value={creditNoteDate} onChange={(e) => setCreditNoteDate(e.target.value)} />
          </div>

          <div className="space-y-2 md:col-span-2">
            <Label>{t.reasonLabel ?? 'سبب التخفيض'}</Label>
            <Select value={selectedReason} onValueChange={(v) => setSelectedReason(v as PurchaseCreditNote['reason'])}>
              <SelectTrigger>
                <SelectValue placeholder={t.selectReason ?? 'اختر سبب التخفيض'} />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="return">{t.returnReason ?? 'مردود بضاعة'}</SelectItem>
                <SelectItem value="price-adjustment">{t.priceAdjustmentReason ?? 'تعديل سعر'}</SelectItem>
                <SelectItem value="damage">{t.damageReason ?? 'تلف البضاعة'}</SelectItem>
                <SelectItem value="invoice-error">{t.invoiceErrorReason ?? 'خطأ في الفاتورة'}</SelectItem>
                <SelectItem value="other">{t.otherReason ?? 'أسباب أخرى'}</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </div>

        {selectedInvoice && creditMode !== 'supplier-total' && (
          <div className="rounded-md border p-3 text-sm space-y-2">
            <p className="font-medium">{t.invoiceInfoTitle ?? 'معلومات الفاتورة'}</p>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 text-muted-foreground">
              <p>{t.invoiceNumber ?? 'رقم الفاتورة'}: <span className="text-foreground">{selectedInvoice.orderNumber}</span></p>
              <p>{t.supplierName ?? 'المورد'}: <span className="text-foreground">{selectedInvoice.supplierName}</span></p>
              <p>{t.invoiceDateLabel ?? 'تاريخ الفاتورة'}: <span className="text-foreground">{format(new Date(selectedInvoice.date), 'yyyy-MM-dd')}</span></p>
              <p>{t.invoiceTotalLabel ?? 'إجمالي الفاتورة'}: <span className="text-foreground">{formatAmount(selectedInvoice.grandTotal)}</span></p>
              <p>{t.previousCreditNotesCount ?? 'عدد الإشعارات السابقة'}: <span className="text-foreground">{previousCreditNotesForInvoice.length}</span></p>
              <p>{t.previousCreditNotesTotal ?? 'مجموع الإشعارات السابقة'}: <span className="text-foreground">{formatAmount(previousCreditsTotal)}</span></p>
              <p className="sm:col-span-2 font-medium">{t.invoiceNetAfterCredits ?? 'صافي الفاتورة بعد الإشعارات'}: <span className="text-foreground">{formatAmount(invoiceNetAfterCredits)}</span></p>
            </div>
          </div>
        )}

        {lockedByUser && (
          <p className="text-xs text-destructive">
            {t.creditNoteLockedBy ?? 'يوجد مستخدم آخر يعمل على إشعار دائن لهذا المورد'}: {lockedByUser}
          </p>
        )}

        {creditMode === 'items' ? (
          <div className="space-y-2">
            <Label>{t.creditNoteItems ?? 'أصناف الإشعار'}</Label>
            <div className="max-h-64 overflow-auto rounded-md border">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>{t.item ?? 'الصنف'}</TableHead>
                    <TableHead>{t.quantity ?? 'الكمية المرتجعة'}</TableHead>
                    <TableHead>{t.price ?? 'السعر'}</TableHead>
                    <TableHead>{t.total ?? 'الإجمالي'}</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {draftItems.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={4} className="text-center text-muted-foreground">
                        {t.creditNoteCalculatedFromInvoice ?? 'تم نسخ البيانات من الفاتورة الأصلية'}
                      </TableCell>
                    </TableRow>
                  ) : (
                    draftItems.map((item, idx) => (
                      <TableRow key={`${item.materialId}-${idx}`}>
                        <TableCell>{item.name}</TableCell>
                        <TableCell>
                          <Input
                            type="number"
                            min="0"
                            max={item.maxQty}
                            step="0.01"
                            value={item.quantity}
                            onChange={(e) => updateDraftQty(idx, e.target.value)}
                          />
                        </TableCell>
                        <TableCell>{formatAmount(item.unitPrice)}</TableCell>
                        <TableCell>{formatAmount(item.quantity * item.unitPrice)}</TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </div>
          </div>
        ) : (
          <div className="space-y-2">
            <Label>{t.creditNoteTotal ?? 'إجمالي الإشعار'}</Label>
            <Input
              type="number"
              min="0"
              step="0.01"
              value={manualAmount}
              onChange={(e) => setManualAmount(e.target.value)}
              placeholder="0.00"
            />
          </div>
        )}

        <div className="space-y-2">
          <Label>{t.notes ?? 'ملاحظات'}</Label>
          <Textarea
            value={createNotes}
            onChange={(e) => setCreateNotes(e.target.value)}
            placeholder={t.notesPlaceholder ?? 'أدخل ملاحظات...'}
            rows={3}
          />
        </div>

        <div className="flex items-center justify-end gap-2">
          <Button type="button" variant="outline" onClick={() => router.push('/admin/purchases/credit-notes')}>
            {t.cancel ?? 'إلغاء'}
          </Button>
          <Button type="button" onClick={submitCreateCreditNote} disabled={isCreating || isLockBusy || Boolean(lockedByUser)}>
            {isCreating ? (t.processing ?? 'جاري...') : (t.createCreditNote ?? 'إنشاء إشعار دائن')}
          </Button>
        </div>
      </CardContent>
    </Card>
  );
}
