'use client';

import { useEffect, useState } from 'react';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { format } from 'date-fns';
import { PlusCircle, Trash2, Eye, Check } from 'lucide-react';
import type { PurchaseCreditNote, PurchaseOrder, Supplier } from '@/lib/types';
import { useToast } from '@/hooks/use-toast';

interface PurchaseCreditNotesClientProps {
  creditNotes: PurchaseCreditNote[];
  invoices: PurchaseOrder[];
  suppliers: Supplier[];
  t: Record<string, any>;
  currencySymbol: string;
  showCreateButton?: boolean;
  autoOpenCreateDialog?: boolean;
  redirectPathAfterCreate?: string;
}

export function PurchaseCreditNotesClient({
  creditNotes,
  invoices,
  suppliers,
  t,
  currencySymbol,
  showCreateButton = true,
  autoOpenCreateDialog = false,
  redirectPathAfterCreate,
}: PurchaseCreditNotesClientProps) {
  const { toast } = useToast();
  const SUPPLIER_SCOPE_ID = '__supplier_balance__';
  const [creditMode, setCreditMode] = useState<'items' | 'invoice-total' | 'supplier-total'>('items');
  const [createDialogOpen, setCreateDialogOpen] = useState(false);
  const [selectedInvoiceId, setSelectedInvoiceId] = useState('');
  const [selectedSupplierId, setSelectedSupplierId] = 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 [selectedNote, setSelectedNote] = useState<PurchaseCreditNote | null>(null);
  const [viewDialogOpen, setViewDialogOpen] = useState(false);
  const [cancelDialogOpen, setCancelDialogOpen] = useState(false);
  const [cancelReason, setCancelReason] = useState('');
  const [isProcessing, setIsProcessing] = useState(false);

  const getStatusBadge = (status: PurchaseCreditNote['status']) => {
    switch (status) {
      case 'draft':
        return <Badge variant="outline">{t.statusDraft ?? 'مسودة'}</Badge>;
      case 'posted':
        return <Badge variant="default" className="bg-green-600">{t.statusPosted ?? 'مرحل'}</Badge>;
      case 'cancelled':
        return <Badge variant="destructive">{t.statusCancelled ?? 'ملغي'}</Badge>;
      default:
        return <Badge>{status}</Badge>;
    }
  };

  const getReasonDisplay = (reason: string) => {
    const reasonMap: Record<string, string> = {
      'return': t.returnReason ?? 'مردود بضاعة',
      'price-adjustment': t.priceAdjustmentReason ?? 'تعديل سعر',
      'damage': t.damageReason ?? 'تلف البضاعة',
      'invoice-error': t.invoiceErrorReason ?? 'خطأ في الفاتورة',
      'other': t.otherReason ?? 'أسباب أخرى',
    };
    return reasonMap[reason] || reason;
  };

  const getReasonImpactHint = (reason?: PurchaseCreditNote['reason']) => {
    if (!reason) return null;

    if (reason === 'return') {
      return {
        accounting: t.reasonHintReturnAccounting ?? 'محاسبيًا: يتم تخفيض ذمة المورد (مدين 2100) مقابل مردودات مشتريات (دائن 5150).',
        inventory: t.reasonHintReturnInventory ?? 'مخزنيًا: لا يتم تحديث المخزون تلقائيًا حاليًا من إشعار الدائن وحده.',
      };
    }

    if (reason === 'price-adjustment' || reason === 'invoice-error') {
      return {
        accounting: t.reasonHintAdjustmentAccounting ?? 'محاسبيًا: يتم تخفيض ذمة المورد (مدين 2100) مقابل خصم مشتريات (دائن 5140).',
        inventory: t.reasonHintAdjustmentInventory ?? 'مخزنيًا: لا يوجد تأثير مخزني لأن هذه تسوية قيمة فقط.',
      };
    }

    if (reason === 'damage') {
      return {
        accounting: t.reasonHintDamageAccounting ?? 'محاسبيًا: يتم تخفيض ذمة المورد وفق قيد الإشعار (حاليًا مقابل 5150).',
        inventory: t.reasonHintDamageInventory ?? 'مخزنيًا: لا يتم خصم/إضافة مخزون تلقائيًا من هذا النموذج.',
      };
    }

    return {
      accounting: t.reasonHintOtherAccounting ?? 'محاسبيًا: يطبّق قيد إشعار دائن قياسي لتخفيض ذمة المورد.',
      inventory: t.reasonHintOtherInventory ?? 'مخزنيًا: لا يوجد تأثير تلقائي ما لم يتم تنفيذ حركة مخزون مستقلة.',
    };
  };

  const selectedInvoice = invoices.find(inv => inv.id === selectedInvoiceId);
  const selectedSupplier = suppliers.find(s => s.id === selectedSupplierId);

  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 openCreateDialog = () => {
    setCreditMode('items');
    setSelectedInvoiceId('');
    setSelectedSupplierId('');
    setManualAmount('0');
    setSelectedReason(undefined);
    setCreditNoteDate(format(new Date(), 'yyyy-MM-dd'));
    setCreateNotes('');
    setDraftItems([]);
    setLockedSupplierId('');
    setLockedByUser('');
    setCreateDialogOpen(true);
  };

  const handleChangeMode = (mode: 'items' | 'invoice-total' | 'supplier-total') => {
    setCreditMode(mode);
    setSelectedInvoiceId('');
    setSelectedSupplierId('');
    setManualAmount('0');
    setDraftItems([]);
  };

  const handleSelectInvoice = (invoiceId: string) => {
    setSelectedInvoiceId(invoiceId);
    const invoice = invoices.find(inv => inv.id === invoiceId);
    if (!invoice) {
      setDraftItems([]);
      return;
    }

    if (lockedSupplierId && lockedSupplierId !== invoice.supplierId) {
      void releaseCreditLock(lockedSupplierId);
      setLockedSupplierId('');
    }
    void 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 = (supplierId: string) => {
    setSelectedSupplierId(supplierId);
    if (lockedSupplierId && lockedSupplierId !== supplierId) {
      void releaseCreditLock(lockedSupplierId);
      setLockedSupplierId('');
    }
    void 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) {
        void releaseCreditLock(lockedSupplierId);
      }
      setCreateDialogOpen(false);
      if (redirectPathAfterCreate) {
        window.location.assign(redirectPathAfterCreate);
      } else {
        window.location.reload();
      }
    } catch (error) {
      toast({
        title: t.error ?? 'خطأ',
        description: error instanceof Error ? error.message : (t.operationFailed ?? 'فشلت العملية'),
        variant: 'destructive',
      });
    } finally {
      setIsCreating(false);
    }
  };

  useEffect(() => {
    if (!createDialogOpen || !lockedSupplierId) return;
    const timer = setInterval(() => {
      void acquireCreditLock(lockedSupplierId);
    }, 60000);
    return () => clearInterval(timer);
  }, [createDialogOpen, lockedSupplierId]);

  useEffect(() => {
    return () => {
      if (lockedSupplierId) {
        void releaseCreditLock(lockedSupplierId);
      }
    };
  }, [lockedSupplierId]);

  useEffect(() => {
    if (createDialogOpen) return;
    if (!lockedSupplierId) return;
    void releaseCreditLock(lockedSupplierId);
    setLockedSupplierId('');
    setLockedByUser('');
  }, [createDialogOpen, lockedSupplierId]);

  useEffect(() => {
    if (!autoOpenCreateDialog) return;
    openCreateDialog();
    // Open once on mount for dedicated create page.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleViewClick = (note: PurchaseCreditNote) => {
    setSelectedNote(note);
    setViewDialogOpen(true);
  };

  const handlePostClick = async (noteId: string) => {
    setIsProcessing(true);
    try {
      const response = await fetch('/api/admin/purchases/credit-notes/post', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ creditNoteId: noteId }),
      });

      const data = await response.json();
      if (!response.ok) {
        throw new Error(data.error || 'Failed to post credit note');
      }

      toast({
        title: t.success ?? 'نجاح',
        description: t.creditNotePostedSuccess ?? 'تم ترحيل إشعار الدائن بنجاح',
      });
      window.location.reload();
    } catch (error) {
      toast({
        title: t.error ?? 'خطأ',
        description: error instanceof Error ? error.message : t.operationFailed ?? 'فشلت العملية',
        variant: 'destructive',
      });
    } finally {
      setIsProcessing(false);
    }
  };

  const handleCancelClick = (note: PurchaseCreditNote) => {
    setSelectedNote(note);
    setCancelReason('');
    setCancelDialogOpen(true);
  };

  const handleConfirmCancel = async () => {
    if (!selectedNote) return;

    setIsProcessing(true);
    try {
      const response = await fetch('/api/admin/purchases/credit-notes/cancel', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          creditNoteId: selectedNote.id,
          reason: cancelReason.trim() || 'No reason provided',
        }),
      });

      const data = await response.json();
      if (!response.ok) {
        throw new Error(data.error || 'Failed to cancel credit note');
      }

      toast({
        title: t.success ?? 'نجاح',
        description: t.creditNoteCancelledSuccess ?? 'تم إلغاء إشعار الدائن بنجاح',
      });
      setCancelDialogOpen(false);
      window.location.reload();
    } catch (error) {
      toast({
        title: t.error ?? 'خطأ',
        description: error instanceof Error ? error.message : t.operationFailed ?? 'فشلت العملية',
        variant: 'destructive',
      });
    } finally {
      setIsProcessing(false);
    }
  };

  const getInvoiceNumber = (invoiceId: string) => {
    if (!invoiceId || invoiceId === SUPPLIER_SCOPE_ID) {
      return t.generalSupplierDiscount ?? 'خصم عام على رصيد المورد';
    }
    const invoice = invoices.find(inv => inv.id === invoiceId);
    return invoice?.orderNumber || invoiceId;
  };

  const reasonImpactHint = getReasonImpactHint(selectedReason);

  const formatAmount = (amount: number) => `${currencySymbol}${amount.toFixed(2)}`;

  return (
    <>
      {showCreateButton ? (
        <div className="flex items-center justify-end">
          <Button type="button" onClick={openCreateDialog}>
            <PlusCircle className="me-2 h-4 w-4" />
            {t.createCreditNote ?? 'إنشاء إشعار دائن'}
          </Button>
        </div>
      ) : null}

      <div className="rounded-md border">
        <div className="relative w-full overflow-auto">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>{t.creditNoteNumber ?? 'رقم الإشعار'}</TableHead>
                <TableHead>{t.linkedInvoice ?? 'الفاتورة الأصلية'}</TableHead>
                <TableHead>{t.supplierName ?? 'اسم المورد'}</TableHead>
                <TableHead>{t.creditNoteDateLabel ?? 'تاريخ الإشعار'}</TableHead>
                <TableHead className="text-right">{t.creditNoteTotal ?? 'الإجمالي'}</TableHead>
                <TableHead>{t.reasonLabel ?? 'السبب'}</TableHead>
                <TableHead>{t.status ?? 'الحالة'}</TableHead>
                <TableHead>{t.actions ?? 'الإجراءات'}</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {creditNotes.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={8} className="text-center text-muted-foreground py-8">
                    {t.noCreditNotes ?? 'لا توجد إشعارات دائن'}
                  </TableCell>
                </TableRow>
              ) : (
                creditNotes.map((note) => (
                  <TableRow key={note.id}>
                    <TableCell className="font-medium">{note.creditNoteNumber}</TableCell>
                    <TableCell>{getInvoiceNumber(note.invoiceId)}</TableCell>
                    <TableCell>{note.supplierName}</TableCell>
                    <TableCell>{format(new Date(note.date), 'yyyy-MM-dd')}</TableCell>
                    <TableCell className="text-right">{formatAmount(note.grandTotal)}</TableCell>
                    <TableCell>{getReasonDisplay(note.reason)}</TableCell>
                    <TableCell>{getStatusBadge(note.status)}</TableCell>
                    <TableCell>
                      <div className="flex gap-2">
                        <Button
                          size="sm"
                          variant="outline"
                          title={t.view ?? 'عرض'}
                          onClick={() => handleViewClick(note)}
                        >
                          <Eye className="h-4 w-4" />
                        </Button>
                        {note.status === 'draft' && (
                          <Button
                            size="sm"
                            variant="outline"
                            title={t.postCreditNote ?? 'ترحيل الإشعار'}
                            onClick={() => handlePostClick(note.id)}
                            disabled={isProcessing}
                          >
                            <Check className="h-4 w-4" />
                          </Button>
                        )}
                        {note.status !== 'cancelled' && (
                          <Button
                            size="sm"
                            variant="outline"
                            className="text-destructive"
                            title={t.cancelCreditNote ?? 'إلغاء الإشعار'}
                            onClick={() => handleCancelClick(note)}
                            disabled={isProcessing}
                          >
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        )}
                      </div>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </div>
      </div>

      <Dialog open={createDialogOpen} onOpenChange={setCreateDialogOpen}>
        <DialogContent className="max-w-3xl">
          <DialogHeader>
            <DialogTitle>{t.createCreditNote ?? 'إنشاء إشعار دائن'}</DialogTitle>
            <DialogDescription>
              {t.createCreditNoteDescription ?? 'إصدار إشعار دائن يقلل من ذمة المورد.'}
            </DialogDescription>
          </DialogHeader>

          <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) => 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={handleSelectSupplierForGeneralCredit}>
                  <SelectTrigger>
                    <SelectValue placeholder={t.selectSupplier ?? 'اختر المورد'} />
                  </SelectTrigger>
                  <SelectContent>
                    {suppliers.map((supplier) => (
                      <SelectItem key={supplier.id} value={supplier.id}>
                        {supplier.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                {lockedByUser && (
                  <p className="text-xs text-destructive">
                    {t.creditNoteLockedBy ?? 'يوجد مستخدم آخر يعمل على إشعار دائن لهذا المورد'}: {lockedByUser}
                  </p>
                )}
              </div>
            ) : (
            <div className="space-y-2">
              <Label>{t.selectInvoice ?? 'اختر الفاتورة الأصلية'}</Label>
              <Select value={selectedInvoiceId} onValueChange={handleSelectInvoice}>
                <SelectTrigger>
                  <SelectValue placeholder={t.selectInvoice ?? 'اختر الفاتورة الأصلية'} />
                </SelectTrigger>
                <SelectContent>
                  {invoices.map((invoice) => (
                    <SelectItem key={invoice.id} value={invoice.id}>
                      {invoice.orderNumber} - {invoice.supplierName}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              {lockedByUser && (
                <p className="text-xs text-destructive">
                  {t.creditNoteLockedBy ?? 'يوجد مستخدم آخر يعمل على إشعار دائن لهذا المورد'}: {lockedByUser}
                </p>
              )}
            </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>
              {reasonImpactHint && (
                <div className="rounded-md border border-dashed p-3 text-xs text-muted-foreground space-y-1">
                  <p>{reasonImpactHint.accounting}</p>
                  <p>{reasonImpactHint.inventory}</p>
                </div>
              )}
            </div>
          </div>

          {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)}
                          />
                          <div className="text-xs text-muted-foreground mt-1">max: {item.maxQty}</div>
                        </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)}
              onFocus={(e) => {
                // Make it ready for quick overwrite when entering a new amount.
                if ((e.currentTarget.value || '').trim() === '0') {
                  setManualAmount('');
                }
                e.currentTarget.select();
              }}
              placeholder="0.00"
            />
            <p className="text-xs text-muted-foreground">
              {creditMode === 'invoice-total'
                ? (t.invoiceLevelCreditHint ?? 'سيتم تسجيل خصم إجمالي على الفاتورة المرتبطة دون توزيع على الأصناف.')
                : (t.supplierLevelCreditHint ?? 'سيتم تسجيل خصم عام على ذمة المورد دون ربطه بفاتورة محددة.')}
            </p>
          </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>

          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => setCreateDialogOpen(false)} disabled={isCreating}>
              {t.cancel ?? 'إلغاء'}
            </Button>
            <Button type="button" onClick={submitCreateCreditNote} disabled={isCreating || isLockBusy || Boolean(lockedByUser)}>
              {isCreating ? (t.processing ?? 'جاري...') : (t.createCreditNote ?? 'إنشاء إشعار دائن')}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* View Dialog */}
      <Dialog open={viewDialogOpen} onOpenChange={setViewDialogOpen}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>{t.creditNoteViewTitle ?? 'تفاصيل إشعار الدائن'}</DialogTitle>
            <DialogDescription>
              {t.creditNoteViewDescription ?? 'عرض تفاصيل إشعار الدائن بما في ذلك المورد، الفاتورة المرتبطة، وعناصر الإشعار.'}
            </DialogDescription>
          </DialogHeader>
          {selectedNote && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <p className="text-sm text-muted-foreground">{t.creditNoteNumber ?? 'رقم الإشعار'}</p>
                  <p className="font-medium">{selectedNote.creditNoteNumber}</p>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">{t.creditNoteDateLabel ?? 'التاريخ'}</p>
                  <p className="font-medium">{format(new Date(selectedNote.date), 'yyyy-MM-dd')}</p>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">{t.supplierName ?? 'المورد'}</p>
                  <p className="font-medium">{selectedNote.supplierName}</p>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">{t.linkedInvoice ?? 'الفاتورة'}</p>
                  <p className="font-medium">{getInvoiceNumber(selectedNote.invoiceId || '')}</p>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">{t.reasonLabel ?? 'السبب'}</p>
                  <p className="font-medium">{getReasonDisplay(selectedNote.reason)}</p>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">{t.status ?? 'الحالة'}</p>
                  {getStatusBadge(selectedNote.status)}
                </div>
              </div>

              {selectedNote.items.length > 0 && (
              <div className="border-t pt-4">
                <p className="text-sm font-medium mb-2">{t.creditNoteItems ?? 'الأصناف'}</p>
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>{t.item ?? 'الصنف'}</TableHead>
                      <TableHead>{t.quantity ?? 'الكمية'}</TableHead>
                      <TableHead className="text-right">{t.price ?? 'السعر'}</TableHead>
                      <TableHead className="text-right">{t.total ?? 'الإجمالي'}</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {selectedNote.items.map((item, idx) => (
                      <TableRow key={idx}>
                        <TableCell>{item.name}</TableCell>
                        <TableCell>{item.quantity}</TableCell>
                        <TableCell className="text-right">{formatAmount(item.unitPrice)}</TableCell>
                        <TableCell className="text-right">{formatAmount(item.total)}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
              )}

              <div className="border-t pt-4 space-y-2">
                <div className="flex justify-between">
                  <p>{t.creditNoteSubtotal ?? 'المجموع الفرعي'}</p>
                  <p>{formatAmount(selectedNote.subTotal)}</p>
                </div>
                {selectedNote.totalDiscount > 0 && (
                  <div className="flex justify-between">
                    <p>{t.creditNoteDiscount ?? 'الخصم'}</p>
                    <p>-{formatAmount(selectedNote.totalDiscount)}</p>
                  </div>
                )}
                {selectedNote.taxAmount > 0 && (
                  <div className="flex justify-between">
                    <p>{t.creditNoteTax ?? 'الضريبة'}</p>
                    <p>{formatAmount(selectedNote.taxAmount)}</p>
                  </div>
                )}
                <div className="flex justify-between font-bold border-t pt-2">
                  <p>{t.creditNoteTotal ?? 'الإجمالي'}</p>
                  <p>{formatAmount(selectedNote.grandTotal)}</p>
                </div>
              </div>

              {selectedNote.notes && (
                <div className="border-t pt-4">
                  <p className="text-sm text-muted-foreground">{t.notes ?? 'ملاحظات'}</p>
                  <p>{selectedNote.notes}</p>
                </div>
              )}
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* Cancel Dialog */}
      <Dialog open={cancelDialogOpen} onOpenChange={setCancelDialogOpen}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>{t.creditNoteCancelDialog ?? 'إلغاء إشعار الدائن'}</DialogTitle>
            <DialogDescription>
              {t.creditNoteCancelDescription ?? 'سيتم عكس تأثير الإشعار المحاسبي'}
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            <div className="rounded-md bg-muted p-3">
              <p className="text-sm font-medium">{selectedNote?.creditNoteNumber}</p>
            </div>
            <textarea
              placeholder={t.cancelReasonPlaceholder ?? 'اسباب الالغاء...'}
              value={cancelReason}
              onChange={(e) => setCancelReason(e.target.value)}
              className="min-h-24 rounded-md border px-3 py-2 text-sm"
            />
          </div>

          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setCancelDialogOpen(false)}
              disabled={isProcessing}
            >
              {t.cancel ?? 'إلغاء'}
            </Button>
            <Button
              variant="destructive"
              onClick={handleConfirmCancel}
              disabled={isProcessing}
            >
              {isProcessing ? (t.processing ?? 'جاري...') : (t.confirmCancel ?? 'تأكيد الإلغاء')}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}
