"use client";

import { useCallback, useEffect, useState } from "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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { useToast } from "@/hooks/use-toast";
import { apiFetch, formatMoney, formatDateTime, toLocalDateInput } from "@/lib/client-utils";
import {
  Loader2, Plus, Pencil, Trash2, Building2, FileText, HandCoins, Phone, ChevronDown,
} from "lucide-react";

interface InvoiceRow {
  id: string;
  description: string;
  amount: number;
  invoiceDate: string;
}

interface SupplierPayRow {
  id: string;
  amount: number;
  paidAt: string;
  notes?: string | null;
  invoiceId?: string | null;
  invoice?: { description: string } | null;
}

interface SupplierRow {
  id: string;
  name: string;
  phone?: string | null;
  notes?: string | null;
  invoices: InvoiceRow[];
  payments: SupplierPayRow[];
  totalInvoices: number;
  totalPaid: number;
  debt: number;
}

interface SuppliersViewProps {
  currency: string;
  isAdmin: boolean;
  refreshKey: number;
  onFinanceChanged: () => void;
}

export default function SuppliersView({ currency, isAdmin, refreshKey, onFinanceChanged }: SuppliersViewProps) {
  const { toast } = useToast();

  const [suppliers, setSuppliers] = useState<SupplierRow[]>([]);
  const [selectedId, setSelectedId] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);

  // نموذج شركة
  const [coDialog, setCoDialog] = useState<null | { mode: "add" } | { mode: "edit"; co: SupplierRow }>(null);
  const [coName, setCoName] = useState("");
  const [coPhone, setCoPhone] = useState("");
  const [coNotes, setCoNotes] = useState("");
  const [savingCo, setSavingCo] = useState(false);

  // نموذج فاتورة
  const [invDialog, setInvDialog] = useState<null | { mode: "add"; co: SupplierRow } | { mode: "edit"; co: SupplierRow; inv: InvoiceRow }>(null);
  const [invDesc, setInvDesc] = useState("");
  const [invAmount, setInvAmount] = useState("");
  const [invDate, setInvDate] = useState("");
  const [savingInv, setSavingInv] = useState(false);

  // نموذج دفعة
  const [payDialog, setPayDialog] = useState<null | { mode: "add"; co: SupplierRow } | { mode: "edit"; co: SupplierRow; pay: SupplierPayRow }>(null);
  const [payAmount, setPayAmount] = useState("");
  const [payDate, setPayDate] = useState("");
  const [payInvoiceId, setPayInvoiceId] = useState<string>("none");
  const [payNotes, setPayNotes] = useState("");
  const [savingPay, setSavingPay] = useState(false);

  // تأكيدات الحذف
  const [deleteCo, setDeleteCo] = useState<SupplierRow | null>(null);
  const [deleteInv, setDeleteInv] = useState<{ co: SupplierRow; inv: InvoiceRow } | null>(null);
  const [deletePay, setDeletePay] = useState<{ co: SupplierRow; pay: SupplierPayRow } | null>(null);
  const [deleting, setDeleting] = useState(false);

  const loadData = useCallback(async () => {
    setLoading(true);
    try {
      const data = await apiFetch<{ suppliers: SupplierRow[] }>("/api/suppliers");
      setSuppliers(data.suppliers);
      setSelectedId((prev) => (prev && data.suppliers.some((s) => s.id === prev) ? prev : null));
    } catch (err) {
      toast({ title: "تعذر تحميل بيانات الشركات", description: err instanceof Error ? err.message : "", variant: "destructive" });
    } finally {
      setLoading(false);
    }
  }, [toast]);

  useEffect(() => {
    loadData();
  }, [loadData, refreshKey]);

  const selected = suppliers.find((s) => s.id === selectedId) ?? null;

  // ========== شركة ==========
  function openAddCo() {
    setCoName("");
    setCoPhone("");
    setCoNotes("");
    setCoDialog({ mode: "add" });
  }

  function openEditCo(co: SupplierRow) {
    setCoName(co.name);
    setCoPhone(co.phone ?? "");
    setCoNotes(co.notes ?? "");
    setCoDialog({ mode: "edit", co });
  }

  async function saveCompany(e: React.FormEvent) {
    e.preventDefault();
    if (coName.trim().length < 2) {
      toast({ title: "اسم الشركة مطلوب", variant: "destructive" });
      return;
    }
    setSavingCo(true);
    const isEdit = coDialog?.mode === "edit";
    try {
      await apiFetch(isEdit ? `/api/suppliers/${(coDialog as { co: SupplierRow }).co.id}` : "/api/suppliers", {
        method: isEdit ? "PATCH" : "POST",
        body: JSON.stringify({ name: coName.trim(), phone: coPhone, notes: coNotes }),
      });
      toast({ title: isEdit ? "تم تعديل بيانات الشركة" : "تمت إضافة الشركة" });
      setCoDialog(null);
      onFinanceChanged();
    } catch (err) {
      toast({ title: isEdit ? "فشل التعديل" : "فشل الإضافة", description: err instanceof Error ? err.message : "", variant: "destructive" });
    } finally {
      setSavingCo(false);
    }
  }

  async function confirmDeleteCo() {
    if (!deleteCo) return;
    setDeleting(true);
    try {
      await apiFetch(`/api/suppliers/${deleteCo.id}`, { method: "DELETE" });
      toast({ title: "تم حذف الشركة", description: "تبقت فواتيرها ودفعاتها محفوظة في السجل" });
      setDeleteCo(null);
      if (selectedId === deleteCo.id) setSelectedId(null);
      onFinanceChanged();
    } catch (err) {
      toast({ title: "فشل الحذف", description: err instanceof Error ? err.message : "", variant: "destructive" });
    } finally {
      setDeleting(false);
    }
  }

  // ========== فاتورة ==========
  function openAddInv(co: SupplierRow) {
    setInvDesc("");
    setInvAmount("");
    setInvDate(toLocalDateInput(new Date()));
    setInvDialog({ mode: "add", co });
  }

  function openEditInv(co: SupplierRow, inv: InvoiceRow) {
    setInvDesc(inv.description);
    setInvAmount(String(inv.amount));
    setInvDate(toLocalDateInput(new Date(inv.invoiceDate)));
    setInvDialog({ mode: "edit", co, inv });
  }

  async function saveInvoice(e: React.FormEvent) {
    e.preventDefault();
    if (invDesc.trim().length < 2) {
      toast({ title: "وصف الفاتورة مطلوب", variant: "destructive" });
      return;
    }
    const amt = Number(invAmount);
    if (!amt || amt <= 0) {
      toast({ title: "مبلغ الفاتورة غير صالح", variant: "destructive" });
      return;
    }
    if (!invDialog) return;
    setSavingInv(true);
    const isEdit = invDialog.mode === "edit";
    const co = invDialog.co;
    try {
      await apiFetch(
        isEdit ? `/api/suppliers/invoices/${(invDialog as { inv: InvoiceRow }).inv.id}` : "/api/suppliers/invoices",
        {
          method: isEdit ? "PATCH" : "POST",
          body: JSON.stringify(
            isEdit
              ? { description: invDesc.trim(), amount: amt, invoiceDate: invDate }
              : { supplierId: co.id, description: invDesc.trim(), amount: amt, invoiceDate: invDate }
          ),
        }
      );
      toast({ title: isEdit ? "تم تعديل الفاتورة" : `تم تسجيل فاتورة لشركة ${co.name}` });
      setInvDialog(null);
      onFinanceChanged();
    } catch (err) {
      toast({ title: isEdit ? "فشل التعديل" : "فشل تسجيل الفاتورة", description: err instanceof Error ? err.message : "", variant: "destructive" });
    } finally {
      setSavingInv(false);
    }
  }

  async function confirmDeleteInv() {
    if (!deleteInv) return;
    setDeleting(true);
    try {
      await apiFetch(`/api/suppliers/invoices/${deleteInv.inv.id}`, { method: "DELETE" });
      toast({ title: "تم حذف الفاتورة" });
      setDeleteInv(null);
      onFinanceChanged();
    } catch (err) {
      toast({ title: "فشل الحذف", description: err instanceof Error ? err.message : "", variant: "destructive" });
    } finally {
      setDeleting(false);
    }
  }

  // ========== دفعة ==========
  function openAddPay(co: SupplierRow) {
    setPayAmount("");
    setPayDate(toLocalDateInput(new Date()));
    setPayInvoiceId("none");
    setPayNotes("");
    setPayDialog({ mode: "add", co });
  }

  function openEditPay(co: SupplierRow, pay: SupplierPayRow) {
    setPayAmount(String(pay.amount));
    setPayDate(toLocalDateInput(new Date(pay.paidAt)));
    setPayInvoiceId(pay.invoiceId ?? "none");
    setPayNotes(pay.notes ?? "");
    setPayDialog({ mode: "edit", co, pay });
  }

  async function savePayment(e: React.FormEvent) {
    e.preventDefault();
    const amt = Number(payAmount);
    if (!amt || amt <= 0) {
      toast({ title: "مبلغ الدفعة غير صالح", variant: "destructive" });
      return;
    }
    if (!payDialog) return;
    setSavingPay(true);
    try {
      const isEdit = payDialog.mode === "edit";
      const co = payDialog.co;
      if (isEdit) {
        const pay = (payDialog as { pay: SupplierPayRow }).pay;
        await apiFetch(`/api/suppliers/payments/${pay.id}`, {
          method: "PATCH",
          body: JSON.stringify({ amount: amt, paidAt: payDate, notes: payNotes, invoiceId: payInvoiceId === "none" ? null : payInvoiceId }),
        });
        toast({ title: "تم تعديل الدفعة", description: "زُامن المصروف المرتبط تلقائياً" });
      } else {
        await apiFetch("/api/suppliers/payments", {
          method: "POST",
          body: JSON.stringify({
            supplierId: co.id,
            amount: amt,
            paidAt: payDate,
            notes: payNotes,
            invoiceId: payInvoiceId === "none" ? undefined : payInvoiceId,
          }),
        });
        toast({ title: `تم تسجيل دفعة لشركة ${co.name}`, description: `${formatMoney(amt, currency)} — سُجلت كمصروف تلقائياً` });
      }
      setPayDialog(null);
      onFinanceChanged();
    } catch (err) {
      toast({ title: "فشل تسجيل الدفعة", description: err instanceof Error ? err.message : "", variant: "destructive" });
    } finally {
      setSavingPay(false);
    }
  }

  async function confirmDeletePay() {
    if (!deletePay) return;
    setDeleting(true);
    try {
      await apiFetch(`/api/suppliers/payments/${deletePay.pay.id}`, { method: "DELETE" });
      toast({ title: "تم حذف الدفعة", description: "حُذف المصروف المرتبط وعاد الرصيد" });
      setDeletePay(null);
      onFinanceChanged();
    } catch (err) {
      toast({ title: "فشل الحذف", description: err instanceof Error ? err.message : "", variant: "destructive" });
    } finally {
      setDeleting(false);
    }
  }

  const thC = "text-right font-bold whitespace-nowrap";

  return (
    <div className="space-y-4">
      {/* بطاقات الشركات */}
      <Card>
        <CardHeader className="pb-3">
          <div className="flex items-center justify-between gap-2 flex-wrap">
            <div>
              <CardTitle className="text-lg flex items-center gap-2">
                <Building2 className="w-5 h-5 text-primary" />
                الشركات والموردين
              </CardTitle>
              <CardDescription>سجل فواتير الشركات الآجلة والدفعات المسددة — المتبقي = الفواتير − الدفعات</CardDescription>
            </div>
            <Button onClick={openAddCo} className="h-10 font-bold">
              <Plus className="w-4 h-4 ml-2" />
              إضافة شركة
            </Button>
          </div>
        </CardHeader>
        <CardContent>
          {loading ? (
            <div className="flex justify-center py-8"><Loader2 className="w-7 h-7 animate-spin text-primary" /></div>
          ) : suppliers.length === 0 ? (
            <p className="text-sm text-muted-foreground text-center py-8">
              لا توجد شركات بعد — أضف شركة لتسجل فواتيرها الآجلة ودفعاتها
            </p>
          ) : (
            <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
              {suppliers.map((co) => (
                <div
                  key={co.id}
                  className={`rounded-xl border p-4 space-y-3 transition-colors ${selectedId === co.id ? "border-primary bg-primary/5" : "hover:bg-muted/40"}`}
                >
                  <button type="button" className="w-full text-right" onClick={() => setSelectedId(selectedId === co.id ? null : co.id)}>
                    <div className="flex items-start justify-between gap-2">
                      <div className="min-w-0">
                        <p className="font-bold truncate">{co.name}</p>
                        {co.phone && (
                          <p className="text-xs text-muted-foreground flex items-center gap-1 mt-0.5">
                            <Phone className="w-3 h-3" />
                            <span dir="ltr">{co.phone}</span>
                          </p>
                        )}
                      </div>
                      <ChevronDown className={`w-4 h-4 text-muted-foreground transition-transform ${selectedId === co.id ? "rotate-180" : ""}`} />
                    </div>
                  </button>
                  <div className="grid grid-cols-3 gap-2 text-center">
                    <div className="rounded-lg bg-muted/60 p-2">
                      <p className="text-[10px] text-muted-foreground">الفواتير</p>
                      <p className="text-sm font-bold">{formatMoney(co.totalInvoices, currency)}</p>
                    </div>
                    <div className="rounded-lg bg-emerald-50 p-2">
                      <p className="text-[10px] text-muted-foreground">المسدد</p>
                      <p className="text-sm font-bold text-emerald-700">{formatMoney(co.totalPaid, currency)}</p>
                    </div>
                    <div className={`rounded-lg p-2 ${co.debt > 0 ? "bg-red-50" : "bg-emerald-50"}`}>
                      <p className="text-[10px] text-muted-foreground">المتبقي لها</p>
                      <p className={`text-sm font-extrabold ${co.debt > 0 ? "text-red-600" : "text-emerald-700"}`}>
                        {formatMoney(co.debt, currency)}
                      </p>
                    </div>
                  </div>
                  <div className="flex items-center gap-1 flex-wrap">
                    <Button variant="outline" size="sm" className="h-8 text-xs" onClick={() => openAddInv(co)}>
                      <FileText className="w-3.5 h-3.5 ml-1" />
                      فاتورة
                    </Button>
                    <Button variant="outline" size="sm" className="h-8 text-xs" onClick={() => openAddPay(co)}>
                      <HandCoins className="w-3.5 h-3.5 ml-1" />
                      دفعة
                    </Button>
                    <span className="grow" />
                    <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => openEditCo(co)} aria-label={`تعديل ${co.name}`}>
                      <Pencil className="w-4 h-4" />
                    </Button>
                    {isAdmin && (
                      <Button variant="ghost" size="icon" className="h-8 w-8 text-destructive" onClick={() => setDeleteCo(co)} aria-label={`حذف ${co.name}`}>
                        <Trash2 className="w-4 h-4" />
                      </Button>
                    )}
                  </div>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      {/* تفاصيل الشركة المحددة */}
      {selected && (
        <div className="space-y-4">
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-base">فواتير شركة {selected.name} ({selected.invoices.length})</CardTitle>
              <CardDescription>اضغط «فاتورة» على أي بطاقة شركة لتسجيل فاتورة جديدة</CardDescription>
            </CardHeader>
            <CardContent>
              {selected.invoices.length === 0 ? (
                <p className="text-sm text-muted-foreground text-center py-6">لا توجد فواتير لهذه الشركة بعد</p>
              ) : (
                <div className="overflow-x-auto max-h-72 overflow-y-auto">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead className={thC}>الوصف</TableHead>
                        <TableHead className={thC}>المبلغ</TableHead>
                        <TableHead className={thC}>التاريخ</TableHead>
                        <TableHead className="text-center font-bold">إجراءات</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {selected.invoices.map((inv) => (
                        <TableRow key={inv.id}>
                          <TableCell className="font-medium">{inv.description}</TableCell>
                          <TableCell className="font-bold whitespace-nowrap">{formatMoney(inv.amount, currency)}</TableCell>
                          <TableCell className="text-xs text-muted-foreground whitespace-nowrap">{formatDateTime(inv.invoiceDate)}</TableCell>
                          <TableCell>
                            <div className="flex items-center justify-center gap-1">
                              <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => openEditInv(selected, inv)} aria-label="تعديل الفاتورة">
                                <Pencil className="w-4 h-4" />
                              </Button>
                              {isAdmin && (
                                <Button variant="ghost" size="icon" className="h-8 w-8 text-destructive" onClick={() => setDeleteInv({ co: selected, inv })} aria-label="حذف الفاتورة">
                                  <Trash2 className="w-4 h-4" />
                                </Button>
                              )}
                            </div>
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </div>
              )}
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-base">دفعات شركة {selected.name} ({selected.payments.length})</CardTitle>
              <CardDescription>كل دفعة تُسجل تلقائياً كمصروف بفئة «فواتير الشركات»</CardDescription>
            </CardHeader>
            <CardContent>
              {selected.payments.length === 0 ? (
                <p className="text-sm text-muted-foreground text-center py-6">لا توجد دفعات لهذه الشركة بعد</p>
              ) : (
                <div className="overflow-x-auto max-h-72 overflow-y-auto">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead className={thC}>المبلغ</TableHead>
                        <TableHead className={thC}>التاريخ</TableHead>
                        <TableHead className={thC}>على فاتورة</TableHead>
                        <TableHead className={thC}>ملاحظات</TableHead>
                        <TableHead className="text-center font-bold">إجراءات</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {selected.payments.map((p) => (
                        <TableRow key={p.id}>
                          <TableCell className="font-bold text-emerald-700 whitespace-nowrap">{formatMoney(p.amount, currency)}</TableCell>
                          <TableCell className="text-xs text-muted-foreground whitespace-nowrap">{formatDateTime(p.paidAt)}</TableCell>
                          <TableCell className="text-xs max-w-40 truncate">{p.invoice?.description ?? <Badge variant="outline">بدون ربط</Badge>}</TableCell>
                          <TableCell className="text-xs text-muted-foreground max-w-40 truncate">{p.notes || "-"}</TableCell>
                          <TableCell>
                            <div className="flex items-center justify-center gap-1">
                              <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => openEditPay(selected, p)} aria-label="تعديل الدفعة">
                                <Pencil className="w-4 h-4" />
                              </Button>
                              {isAdmin && (
                                <Button variant="ghost" size="icon" className="h-8 w-8 text-destructive" onClick={() => setDeletePay({ co: selected, pay: p })} aria-label="حذف الدفعة">
                                  <Trash2 className="w-4 h-4" />
                                </Button>
                              )}
                            </div>
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </div>
              )}
            </CardContent>
          </Card>
        </div>
      )}

      {/* حوار إضافة / تعديل شركة */}
      <Dialog open={!!coDialog} onOpenChange={(o) => !o && setCoDialog(null)}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle className="text-primary">{coDialog?.mode === "edit" ? "تعديل بيانات الشركة" : "إضافة شركة"}</DialogTitle>
            <DialogDescription>{coDialog?.mode === "edit" ? "عدّل البيانات ثم اضغط حفظ التعديل" : "سجل شركة / مورداً تتعامل معه المدرسة"}</DialogDescription>
          </DialogHeader>
          <form onSubmit={saveCompany} className="grid gap-3">
            <div className="space-y-2">
              <Label htmlFor="co-name">اسم الشركة</Label>
              <Input id="co-name" value={coName} onChange={(e) => setCoName(e.target.value)} placeholder="مثال: شركة النور للمطبوعات" required />
            </div>
            <div className="space-y-2">
              <Label htmlFor="co-phone">رقم الهاتف (اختياري)</Label>
              <Input id="co-phone" value={coPhone} onChange={(e) => setCoPhone(e.target.value)} dir="ltr" placeholder="07XX XXX XXXX" />
            </div>
            <div className="space-y-2">
              <Label htmlFor="co-notes">ملاحظات (اختياري)</Label>
              <Input id="co-notes" value={coNotes} onChange={(e) => setCoNotes(e.target.value)} placeholder="مثال: مورد الكراسات والقرطاسية" />
            </div>
            <div className="flex gap-2 pt-1">
              <Button type="submit" className="flex-1 font-bold" disabled={savingCo}>
                {savingCo && <Loader2 className="w-4 h-4 ml-2 animate-spin" />}
                {coDialog?.mode === "edit" ? "حفظ التعديل" : "إضافة الشركة"}
              </Button>
              <Button type="button" variant="outline" onClick={() => setCoDialog(null)}>إلغاء</Button>
            </div>
          </form>
        </DialogContent>
      </Dialog>

      {/* حوار إضافة / تعديل فاتورة */}
      <Dialog open={!!invDialog} onOpenChange={(o) => !o && setInvDialog(null)}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle className="text-primary">
              {invDialog?.mode === "edit" ? "تعديل الفاتورة" : `فاتورة جديدة — ${invDialog?.co?.name ?? ""}`}
            </DialogTitle>
            <DialogDescription>الفاتورة تُضاف إلى ديون الشركة وتظهر في المتبقي</DialogDescription>
          </DialogHeader>
          <form onSubmit={saveInvoice} className="grid gap-3">
            <div className="space-y-2">
              <Label htmlFor="inv-desc">وصف الفاتورة</Label>
              <Input id="inv-desc" value={invDesc} onChange={(e) => setInvDesc(e.target.value)} placeholder="مثال: توريد 200 كراسة" required />
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-2">
                <Label htmlFor="inv-amount">المبلغ ({currency})</Label>
                <Input id="inv-amount" type="number" min={0} value={invAmount} onChange={(e) => setInvAmount(e.target.value)} className="font-bold" required />
              </div>
              <div className="space-y-2">
                <Label htmlFor="inv-date">تاريخ الفاتورة</Label>
                <Input id="inv-date" type="date" value={invDate} onChange={(e) => setInvDate(e.target.value)} required />
              </div>
            </div>
            <div className="flex gap-2 pt-1">
              <Button type="submit" className="flex-1 font-bold" disabled={savingInv}>
                {savingInv && <Loader2 className="w-4 h-4 ml-2 animate-spin" />}
                {invDialog?.mode === "edit" ? "حفظ التعديل" : "تسجيل الفاتورة"}
              </Button>
              <Button type="button" variant="outline" onClick={() => setInvDialog(null)}>إلغاء</Button>
            </div>
          </form>
        </DialogContent>
      </Dialog>

      {/* حوار إضافة / تعديل دفعة لشركة */}
      <Dialog open={!!payDialog} onOpenChange={(o) => !o && setPayDialog(null)}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle className="text-primary">
              {payDialog?.mode === "edit" ? "تعديل الدفعة" : `دفعة لشركة ${payDialog?.co?.name ?? ""}`}
            </DialogTitle>
            <DialogDescription>
              {payDialog?.mode === "edit"
                ? "عند تعديل المبلغ أو التاريخ يُزامن المصروف المرتبط تلقائياً"
                : `المتبقي على الشركة حالياً: ${payDialog ? formatMoney(payDialog.co.debt, currency) : ""}`}
            </DialogDescription>
          </DialogHeader>
          <form onSubmit={savePayment} className="grid gap-3">
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-2">
                <Label htmlFor="spay-amount">المبلغ ({currency})</Label>
                <Input id="spay-amount" type="number" min={0} value={payAmount} onChange={(e) => setPayAmount(e.target.value)} className="font-bold" required />
              </div>
              <div className="space-y-2">
                <Label htmlFor="spay-date">تاريخ الدفع</Label>
                <Input id="spay-date" type="date" value={payDate} onChange={(e) => setPayDate(e.target.value)} required />
              </div>
            </div>
            <div className="space-y-2">
              <Label>على فاتورة (اختياري)</Label>
              <Select value={payInvoiceId} onValueChange={setPayInvoiceId}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="none">بدون ربط بفاتورة</SelectItem>
                  {(payDialog?.co?.invoices ?? []).map((inv) => (
                    <SelectItem key={inv.id} value={inv.id}>
                      {inv.description} — {formatMoney(inv.amount, currency)}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label htmlFor="spay-notes">ملاحظات (اختياري)</Label>
              <Input id="spay-notes" value={payNotes} onChange={(e) => setPayNotes(e.target.value)} placeholder="مثال: دفعة نقدية" />
            </div>
            <div className="flex gap-2 pt-1">
              <Button type="submit" className="flex-1 font-bold" disabled={savingPay}>
                {savingPay && <Loader2 className="w-4 h-4 ml-2 animate-spin" />}
                {payDialog?.mode === "edit" ? "حفظ التعديل" : "تسجيل الدفعة"}
              </Button>
              <Button type="button" variant="outline" onClick={() => setPayDialog(null)}>إلغاء</Button>
            </div>
          </form>
        </DialogContent>
      </Dialog>

      {/* تأكيد حذف شركة */}
      <AlertDialog open={!!deleteCo} onOpenChange={(o) => !o && setDeleteCo(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>حذف شركة {deleteCo?.name}؟</AlertDialogTitle>
            <AlertDialogDescription>
              ستُحذف الشركة من القائمة. فواتيرها ودفعاتها السابقة تبقى محفوظة في السجل والمصروفات لحفظ صحة الميزانية.
              هل أنت متأكد من الحذف؟
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>إلغاء</AlertDialogCancel>
            <AlertDialogAction
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
              onClick={(e) => { e.preventDefault(); confirmDeleteCo(); }}
              disabled={deleting}
            >
              {deleting ? <Loader2 className="w-4 h-4 ml-2 animate-spin" /> : null}
              نعم، حذف الشركة
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* تأكيد حذف فاتورة */}
      <AlertDialog open={!!deleteInv} onOpenChange={(o) => !o && setDeleteInv(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>حذف الفاتورة؟</AlertDialogTitle>
            <AlertDialogDescription>
              سيتم حذف فاتورة «{deleteInv?.inv.description}» بمبلغ {deleteInv ? formatMoney(deleteInv.inv.amount, currency) : ""}.
              لا يمكن الحذف إذا كانت الفاتورة مرتبطة بدفعات مسددة.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>إلغاء</AlertDialogCancel>
            <AlertDialogAction
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
              onClick={(e) => { e.preventDefault(); confirmDeleteInv(); }}
              disabled={deleting}
            >
              {deleting ? <Loader2 className="w-4 h-4 ml-2 animate-spin" /> : null}
              نعم، حذف الفاتورة
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* تأكيد حذف دفعة شركة */}
      <AlertDialog open={!!deletePay} onOpenChange={(o) => !o && setDeletePay(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>حذف الدفعة؟</AlertDialogTitle>
            <AlertDialogDescription>
              سيتم حذف دفعة بمبلغ {deletePay ? formatMoney(deletePay.pay.amount, currency) : ""} لصالح شركة {deletePay?.co.name}،
              ويُحذف المصروف المرتبط بها تلقائياً فيعود الرصيد الصحيح. هل أنت متأكد؟
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>إلغاء</AlertDialogCancel>
            <AlertDialogAction
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
              onClick={(e) => { e.preventDefault(); confirmDeletePay(); }}
              disabled={deleting}
            >
              {deleting ? <Loader2 className="w-4 h-4 ml-2 animate-spin" /> : null}
              نعم، حذف الدفعة
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
