"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 { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useToast } from "@/hooks/use-toast";
import { apiFetch, formatMoney, formatDateTime, toLocalDateInput } from "@/lib/client-utils";
import { LectureWagesView } from "@/components/lecture-wages-view";
import { StaffLoansView } from "@/components/staff-loans-view";
import {
  Loader2, Plus, Pencil, Trash2, Pause, Play, HandCoins, Users, Wallet, CalendarClock, ReceiptText, GraduationCap,
} from "lucide-react";

interface EmployeeRow {
  id: string;
  name: string;
  role: string;
  monthlySalary: number;
  startDate: string;
  isActive: boolean;
  /** v8.1: نوع الكادر — TEACHER (تدريسي) | ADMIN (إداري) */
  employeeType?: string;
  /** v8.1: سعر المحاضرة للمعلمين */
  lecturePrice?: number;
  months: number;
  totalDue: number;
  totalPaid: number;
  remaining: number;
}

interface PaymentRow {
  id: string;
  employeeId: string;
  amount: number;
  /** v8.1: المبلغ الاسمي + الخصومات + المكافآت + رقم وصل الصرف */
  baseAmount?: number;
  deductions?: number;
  bonuses?: number;
  voucherNumber?: string | null;
  paidAt: string;
  notes?: string | null;
  employee: { name: string; role: string };
  creator?: { fullName: string } | null;
}

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

const ROLES = ["معلم", "إداري", "محاسب", "أخرى"];

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

  const [employees, setEmployees] = useState<EmployeeRow[]>([]);
  const [payments, setPayments] = useState<PaymentRow[]>([]);
  const [loading, setLoading] = useState(true);

  // نموذج موظف (إضافة / تعديل)
  const [empDialog, setEmpDialog] = useState<null | { mode: "add" } | { mode: "edit"; emp: EmployeeRow }>(null);
  const [empName, setEmpName] = useState("");
  const [empRole, setEmpRole] = useState(ROLES[0]);
  const [empSalary, setEmpSalary] = useState("");
  const [empStart, setEmpStart] = useState("");
  // v8.1: نوع الكادر + سعر المحاضرة
  const [empType, setEmpType] = useState("ADMIN");
  const [empLecturePrice, setEmpLecturePrice] = useState("");
  const [savingEmp, setSavingEmp] = useState(false);

  // دفعة راتب (تسجيل / تعديل)
  const [payDialog, setPayDialog] = useState<null | { mode: "add"; emp: EmployeeRow } | { mode: "edit"; pay: PaymentRow }>(null);
  const [payAmount, setPayAmount] = useState("");
  const [payDate, setPayDate] = useState("");
  const [payNotes, setPayNotes] = useState("");
  // v8.1: بيانات كشف الرواتب التفصيلية
  const [payBase, setPayBase] = useState("");
  const [payDeductions, setPayDeductions] = useState("");
  const [payBonuses, setPayBonuses] = useState("");
  const [payVoucher, setPayVoucher] = useState("");
  const [savingPay, setSavingPay] = useState(false);

  // تأكيدات الحذف
  const [deleteEmp, setDeleteEmp] = useState<EmployeeRow | null>(null);
  const [deletePay, setDeletePay] = useState<PaymentRow | null>(null);
  const [deleting, setDeleting] = useState(false);

  const loadData = useCallback(async () => {
    setLoading(true);
    try {
      const [empData, payData] = await Promise.all([
        apiFetch<{ employees: EmployeeRow[] }>("/api/employees"),
        apiFetch<{ payments: PaymentRow[] }>("/api/employee-payments"),
      ]);
      setEmployees(empData.employees);
      setPayments(payData.payments);
    } catch (err) {
      toast({ title: "تعذر تحميل بيانات الرواتب", description: err instanceof Error ? err.message : "", variant: "destructive" });
    } finally {
      setLoading(false);
    }
  }, [toast]);

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

  function resetEmpForm() {
    setEmpName("");
    setEmpRole(ROLES[0]);
    setEmpSalary("");
    setEmpStart(toLocalDateInput(new Date()));
    setEmpType("ADMIN");
    setEmpLecturePrice("");
  }

  function openAdd() {
    resetEmpForm();
    setEmpDialog({ mode: "add" });
  }

  function openEdit(emp: EmployeeRow) {
    setEmpName(emp.name);
    setEmpRole(ROLES.includes(emp.role) ? emp.role : "أخرى");
    setEmpSalary(String(emp.monthlySalary));
    setEmpStart(toLocalDateInput(new Date(emp.startDate)));
    setEmpType(emp.employeeType === "TEACHER" ? "TEACHER" : "ADMIN");
    setEmpLecturePrice(emp.lecturePrice ? String(emp.lecturePrice) : "");
    setEmpDialog({ mode: "edit", emp });
  }

  async function saveEmployee(e: React.FormEvent) {
    e.preventDefault();
    if (empName.trim().length < 2) {
      toast({ title: "اسم الموظف مطلوب", variant: "destructive" });
      return;
    }
    const salary = Number(empSalary);
    // المعلم التدريسي قد يعمل بنظام أجور المحاضرات فقط (راتب شهري صفر)
    if (isNaN(salary) || salary < 0 || (salary === 0 && empType !== "TEACHER")) {
      toast({ title: "الراتب الشهري غير صالح", variant: "destructive" });
      return;
    }
    if (!empStart) {
      toast({ title: "تاريخ المباشر مطلوب", variant: "destructive" });
      return;
    }
    setSavingEmp(true);
    const isEdit = empDialog?.mode === "edit";
    try {
      await apiFetch(isEdit ? `/api/employees/${(empDialog as { emp: EmployeeRow }).emp.id}` : "/api/employees", {
        method: isEdit ? "PATCH" : "POST",
        body: JSON.stringify({
          name: empName.trim(),
          role: empRole,
          monthlySalary: salary,
          startDate: empStart,
          employeeType: empType,
          lecturePrice: empType === "TEACHER" ? Number(empLecturePrice || 0) : undefined,
        }),
      });
      toast({
        title: isEdit ? "تم تعديل بيانات الموظف" : "تمت إضافة الموظف",
        description:
          `${empName.trim()} — ${empType === "TEACHER" ? "كادر تدريسي" : "كادر إداري"}` +
          (salary > 0 ? ` — ${formatMoney(salary, currency)} شهرياً` : ""),
      });
      setEmpDialog(null);
      onFinanceChanged();
    } catch (err) {
      toast({ title: isEdit ? "فشل التعديل" : "فشل الإضافة", description: err instanceof Error ? err.message : "", variant: "destructive" });
    } finally {
      setSavingEmp(false);
    }
  }

  async function toggleActive(emp: EmployeeRow) {
    try {
      await apiFetch(`/api/employees/${emp.id}`, {
        method: "PATCH",
        body: JSON.stringify({ isActive: !emp.isActive }),
      });
      toast({ title: emp.isActive ? `تم إيقاف ${emp.name} مؤقتاً` : `تم تفعيل ${emp.name}` });
      onFinanceChanged();
    } catch (err) {
      toast({ title: "فشل تغيير الحالة", description: err instanceof Error ? err.message : "", variant: "destructive" });
    }
  }

  function openPay(emp: EmployeeRow) {
    setPayAmount(emp.monthlySalary > 0 ? String(emp.monthlySalary) : "");
    setPayBase(emp.monthlySalary > 0 ? String(emp.monthlySalary) : "");
    setPayDeductions("");
    setPayBonuses("");
    setPayVoucher("");
    setPayDate(toLocalDateInput(new Date()));
    setPayNotes("");
    setPayDialog({ mode: "add", emp });
  }

  function openEditPayment(pay: PaymentRow) {
    setPayAmount(String(pay.amount));
    setPayBase(pay.baseAmount ? String(pay.baseAmount) : "");
    setPayDeductions(pay.deductions ? String(pay.deductions) : "");
    setPayBonuses(pay.bonuses ? String(pay.bonuses) : "");
    setPayVoucher(pay.voucherNumber ?? "");
    setPayDate(toLocalDateInput(new Date(pay.paidAt)));
    setPayNotes(pay.notes ?? "");
    setPayDialog({ mode: "edit", pay });
  }

  async function savePayment(e: React.FormEvent) {
    e.preventDefault();
    const amt = Number(payAmount);
    if (!amt || amt <= 0) {
      toast({ title: "مبلغ الدفعة غير صالح", variant: "destructive" });
      return;
    }
    if (!payDate) {
      toast({ title: "تاريخ الدفع مطلوب", variant: "destructive" });
      return;
    }
    setSavingPay(true);
    try {
      const isEdit = payDialog?.mode === "edit";
      if (isEdit) {
        const pay = (payDialog as { pay: PaymentRow }).pay;
        await apiFetch(`/api/employee-payments/${pay.id}`, {
          method: "PATCH",
          body: JSON.stringify({ amount: amt, paidAt: payDate, notes: payNotes }),
        });
        toast({ title: "تم تعديل الدفعة", description: "زُامن المصروف المرتبط تلقائياً" });
      } else {
        const emp = (payDialog as { emp: EmployeeRow }).emp;
        const base = Number(payBase || 0);
        const ded = Number(payDeductions || 0);
        const bon = Number(payBonuses || 0);
        await apiFetch("/api/employee-payments", {
          method: "POST",
          body: JSON.stringify({
            employeeId: emp.id,
            amount: amt,
            baseAmount: base || undefined,
            deductions: ded || undefined,
            bonuses: bon || undefined,
            voucherNumber: payVoucher.trim() || undefined,
            paidAt: payDate,
            notes: payNotes,
          }),
        });
        toast({
          title: `تم تسجيل دفعة راتب لـ ${emp.name}`,
          description:
            `${formatMoney(amt, currency)} — سُجلت كمصروف تلقائياً` +
            (payVoucher.trim() ? ` — وصل صرف: ${payVoucher.trim()}` : " مع رقم وصل تلقائي"),
        });
      }
      setPayDialog(null);
      onFinanceChanged();
    } catch (err) {
      toast({ title: "فشل تسجيل الدفعة", description: err instanceof Error ? err.message : "", variant: "destructive" });
    } finally {
      setSavingPay(false);
    }
  }

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

  async function confirmDeletePayment() {
    if (!deletePay) return;
    setDeleting(true);
    try {
      await apiFetch(`/api/employee-payments/${deletePay.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 activeCount = employees.filter((e) => e.isActive).length;
  const totalMonthly = employees.filter((e) => e.isActive).reduce((s, e) => s + e.monthlySalary, 0);
  const totalPaidAll = employees.reduce((s, e) => s + e.totalPaid, 0);
  const totalRemaining = employees.reduce((s, e) => s + e.remaining, 0);

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

  return (
    <Tabs defaultValue="salaries" className="space-y-4">
      <TabsList className="grid w-full grid-cols-3">
        <TabsTrigger value="salaries">الرواتب والكادر</TabsTrigger>
        <TabsTrigger value="lectures">أجور المحاضرات</TabsTrigger>
        <TabsTrigger value="staff-loans">سلف المنتسبين</TabsTrigger>
      </TabsList>

      {/* تبويب الرواتب والكادر */}
      <TabsContent value="salaries" className="space-y-4 mt-4">
      {/* ملخص سريع */}
      <div className="grid gap-3 grid-cols-2 lg:grid-cols-4">
        <Card className="border-r-4 border-r-sky-600">
          <CardContent className="pt-4 flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">الموظفون النشطون</p>
              <p className="text-xl font-extrabold text-sky-700 mt-1">{activeCount} / {employees.length}</p>
            </div>
            <Users className="w-7 h-7 text-sky-600" />
          </CardContent>
        </Card>
        <Card className="border-r-4 border-r-indigo-600">
          <CardContent className="pt-4 flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">إجمالي الرواتب الشهرية (النشطون)</p>
              <p className="text-lg font-extrabold text-indigo-700 mt-1">{formatMoney(totalMonthly, currency)}</p>
            </div>
            <Wallet className="w-7 h-7 text-indigo-600" />
          </CardContent>
        </Card>
        <Card className="border-r-4 border-r-emerald-600">
          <CardContent className="pt-4 flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">إجمالي المدفوع</p>
              <p className="text-lg font-extrabold text-emerald-700 mt-1">{formatMoney(totalPaidAll, currency)}</p>
            </div>
            <ReceiptText className="w-7 h-7 text-emerald-600" />
          </CardContent>
        </Card>
        <Card className="border-r-4 border-r-amber-500">
          <CardContent className="pt-4 flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">إجمالي ما بقي له</p>
              <p className="text-lg font-extrabold text-amber-700 mt-1">{formatMoney(totalRemaining, currency)}</p>
            </div>
            <CalendarClock className="w-7 h-7 text-amber-600" />
          </CardContent>
        </Card>
      </div>

      {/* جدول الموظفين */}
      <Card>
        <CardHeader className="pb-3">
          <div className="flex items-center justify-between gap-2 flex-wrap">
            <div>
              <CardTitle className="text-lg">رواتب الموظفين</CardTitle>
              <CardDescription>المستحق يُحسب تلقائياً من تاريخ المباشر (راتب × أشهر) ويُخصم منه المدفوع</CardDescription>
            </div>
            <Button onClick={openAdd} 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>
          ) : employees.length === 0 ? (
            <p className="text-sm text-muted-foreground text-center py-8">
              لا يوجد موظفون بعد — أضف أول موظف لتتابع رواتبه واستحقاقاته
            </p>
          ) : (
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className={thC}>الموظف</TableHead>
                    <TableHead className={thC}>الصفة</TableHead>
                    <TableHead className={thC}>الراتب الشهري</TableHead>
                    <TableHead className={thC}>تاريخ المباشر</TableHead>
                    <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>
                  {employees.map((emp) => (
                    <TableRow key={emp.id} className={!emp.isActive ? "opacity-60" : ""}>
                      <TableCell className="font-bold whitespace-nowrap">{emp.name}</TableCell>
                      <TableCell>
                        <div className="flex items-center gap-1 flex-wrap">
                          <Badge variant="outline">{emp.role}</Badge>
                          {emp.employeeType === "TEACHER" && (
                            <Badge className="bg-sky-100 text-sky-800 hover:bg-sky-100 text-[10px]">
                              <GraduationCap className="w-3 h-3 ml-0.5" />
                              تدريسي
                            </Badge>
                          )}
                        </div>
                      </TableCell>
                      <TableCell className="whitespace-nowrap">{formatMoney(emp.monthlySalary, currency)}</TableCell>
                      <TableCell className="text-xs text-muted-foreground whitespace-nowrap">{formatDateTime(emp.startDate)}</TableCell>
                      <TableCell className="whitespace-nowrap">
                        {formatMoney(emp.totalDue, currency)}
                        <span className="text-[10px] text-muted-foreground block">({emp.months} شهر)</span>
                      </TableCell>
                      <TableCell className="text-emerald-700 font-medium whitespace-nowrap">{formatMoney(emp.totalPaid, currency)}</TableCell>
                      <TableCell className={`font-extrabold whitespace-nowrap ${emp.remaining > 0 ? "text-amber-700" : "text-emerald-700"}`}>
                        {formatMoney(emp.remaining, currency)}
                      </TableCell>
                      <TableCell>
                        {emp.isActive ? (
                          <Badge className="bg-emerald-100 text-emerald-800 hover:bg-emerald-100">نشط</Badge>
                        ) : (
                          <Badge variant="secondary">موقوف مؤقتاً</Badge>
                        )}
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center justify-center gap-1">
                          <Button variant="outline" size="sm" className="h-8 text-xs" onClick={() => openPay(emp)} aria-label={`تسجيل دفعة لـ ${emp.name}`}>
                            <HandCoins className="w-3.5 h-3.5 ml-1" />
                            دفع
                          </Button>
                          <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => openEdit(emp)} aria-label={`تعديل بيانات ${emp.name}`}>
                            <Pencil className="w-4 h-4" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="icon"
                            className={`h-8 w-8 ${emp.isActive ? "text-amber-600" : "text-emerald-600"}`}
                            onClick={() => toggleActive(emp)}
                            aria-label={emp.isActive ? `إيقاف ${emp.name}` : `تفعيل ${emp.name}`}
                          >
                            {emp.isActive ? <Pause className="w-4 h-4" /> : <Play className="w-4 h-4" />}
                          </Button>
                          {isAdmin && (
                            <Button variant="ghost" size="icon" className="h-8 w-8 text-destructive" onClick={() => setDeleteEmp(emp)} aria-label={`حذف ${emp.name}`}>
                              <Trash2 className="w-4 h-4" />
                            </Button>
                          )}
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          )}
        </CardContent>
      </Card>

      {/* سجل دفعات الرواتب */}
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="text-base flex items-center gap-2">
            <ReceiptText className="w-5 h-5 text-primary" />
            كشف الرواتب التفصيلي ({payments.length})
          </CardTitle>
          <CardDescription>كل دفعة تُسجل تلقائياً كمصروف ببند «رواتب الموظفين» مع رقم وصل صرف — التعديل والحذف يُزامنان المصروف المرتبط</CardDescription>
        </CardHeader>
        <CardContent>
          {loading ? (
            <div className="flex justify-center py-8"><Loader2 className="w-7 h-7 animate-spin text-primary" /></div>
          ) : payments.length === 0 ? (
            <p className="text-sm text-muted-foreground text-center py-8">لا توجد دفعات رواتب بعد</p>
          ) : (
            <div className="overflow-x-auto max-h-96 overflow-y-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className={thC}>الموظف</TableHead>
                    <TableHead className={thC}>الاسمي</TableHead>
                    <TableHead className={thC}>خصومات</TableHead>
                    <TableHead className={thC}>مكافآت</TableHead>
                    <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>
                  {payments.map((p) => (
                    <TableRow key={p.id}>
                      <TableCell className="font-medium whitespace-nowrap">{p.employee?.name ?? "-"}</TableCell>
                      <TableCell className="whitespace-nowrap">{p.baseAmount ? formatMoney(p.baseAmount, currency) : "—"}</TableCell>
                      <TableCell className="text-red-600 whitespace-nowrap">{p.deductions ? `-${formatMoney(p.deductions, currency)}` : "—"}</TableCell>
                      <TableCell className="text-emerald-700 whitespace-nowrap">{p.bonuses ? `+${formatMoney(p.bonuses, currency)}` : "—"}</TableCell>
                      <TableCell className="font-bold whitespace-nowrap">{formatMoney(p.amount, currency)}</TableCell>
                      <TableCell dir="ltr" className="text-xs whitespace-nowrap">{p.voucherNumber ?? "—"}</TableCell>
                      <TableCell className="text-xs text-muted-foreground whitespace-nowrap">{formatDateTime(p.paidAt)}</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={() => openEditPayment(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(p)} aria-label="حذف الدفعة">
                              <Trash2 className="w-4 h-4" />
                            </Button>
                          )}
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          )}
        </CardContent>
      </Card>
      </TabsContent>

      {/* تبويب أجور المحاضرات (v8.1) */}
      <TabsContent value="lectures" className="mt-4">
        <LectureWagesView currency={currency} refreshKey={refreshKey} onChanged={onFinanceChanged} />
      </TabsContent>

      {/* تبويب سلف المنتسبين (v8.1) */}
      <TabsContent value="staff-loans" className="mt-4">
        <StaffLoansView currency={currency} refreshKey={refreshKey} onChanged={onFinanceChanged} />
      </TabsContent>

      {/* حوار إضافة / تعديل موظف */}
      <Dialog open={!!empDialog} onOpenChange={(o) => !o && setEmpDialog(null)}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle className="text-primary">
              {empDialog?.mode === "edit" ? "تعديل بيانات الموظف" : "إضافة موظف / معلم"}
            </DialogTitle>
            <DialogDescription>
              {empDialog?.mode === "edit" ? "عدّل البيانات ثم اضغط حفظ التعديل" : "سجل موظفاً جديداً لمتابعة رواته واستحقاقاته الشهرية"}
            </DialogDescription>
          </DialogHeader>
          <form onSubmit={saveEmployee} className="grid gap-3">
            <div className="space-y-2">
              <Label htmlFor="emp-name">اسم الموظف</Label>
              <Input id="emp-name" value={empName} onChange={(e) => setEmpName(e.target.value)} placeholder="مثال: أحمد محمد" required />
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-2">
                <Label>الصفة</Label>
                <Select value={empRole} onValueChange={setEmpRole}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    {ROLES.map((r) => (
                      <SelectItem key={r} value={r}>{r}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>نوع الكادر</Label>
                <Select value={empType} onValueChange={setEmpType}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="ADMIN">إداري</SelectItem>
                    <SelectItem value="TEACHER">تدريسي (معلم)</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-2">
                <Label htmlFor="emp-salary">الراتب الشهري ({currency})</Label>
                <Input id="emp-salary" type="number" min={0} value={empSalary} onChange={(e) => setEmpSalary(e.target.value)} className="font-bold" required />
                {empType === "TEACHER" && (
                  <p className="text-[11px] text-muted-foreground">المعلم بأجر المحاضرات فقط يمكن وضع الراتب صفر</p>
                )}
              </div>
              {empType === "TEACHER" && (
                <div className="space-y-2">
                  <Label htmlFor="emp-lecture-price">سعر المحاضرة ({currency})</Label>
                  <Input id="emp-lecture-price" type="number" min={0} step="any" value={empLecturePrice} onChange={(e) => setEmpLecturePrice(e.target.value)} placeholder="0" />
                </div>
              )}
            </div>
            <div className="space-y-2">
              <Label htmlFor="emp-start">تاريخ المباشر</Label>
              <Input id="emp-start" type="date" value={empStart} onChange={(e) => setEmpStart(e.target.value)} required />
            </div>
            <div className="flex gap-2 pt-1">
              <Button type="submit" className="flex-1 font-bold" disabled={savingEmp}>
                {savingEmp && <Loader2 className="w-4 h-4 ml-2 animate-spin" />}
                {empDialog?.mode === "edit" ? "حفظ التعديل" : "إضافة الموظف"}
              </Button>
              <Button type="button" variant="outline" onClick={() => setEmpDialog(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 as { emp?: EmployeeRow })?.emp?.name ?? ""}`}
            </DialogTitle>
            <DialogDescription>
              {payDialog?.mode === "edit"
                ? "عند تعديل المبلغ أو التاريخ يُزامن المصروف المرتبط تلقائياً"
                : `مستحقاته حتى الآن: ${payDialog ? formatMoney((payDialog as { emp: EmployeeRow }).emp.totalDue, currency) : ""} — ما بقي له: ${payDialog ? formatMoney((payDialog as { emp: EmployeeRow }).emp.remaining, currency) : ""}`}
            </DialogDescription>
          </DialogHeader>
          <form onSubmit={savePayment} className="grid gap-3">
            {payDialog?.mode === "add" && (
              <>
                <div className="grid grid-cols-2 gap-3">
                  <div className="space-y-2">
                    <Label htmlFor="pay-base">المبلغ الاسمي ({currency})</Label>
                    <Input
                      id="pay-base"
                      type="number"
                      min={0}
                      value={payBase}
                      onChange={(e) => {
                        setPayBase(e.target.value);
                        // احتساب الصافي تلقائياً = الاسمي + المكافآت - الخصومات
                        const b = Number(e.target.value || 0);
                        const d = Number(payDeductions || 0);
                        const bo = Number(payBonuses || 0);
                        if (b > 0) setPayAmount(String(b + bo - d));
                      }}
                      className="font-bold"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="pay-date">تاريخ الصرف</Label>
                    <Input id="pay-date" type="date" value={payDate} onChange={(e) => setPayDate(e.target.value)} required />
                  </div>
                </div>
                <div className="grid grid-cols-2 gap-3">
                  <div className="space-y-2">
                    <Label htmlFor="pay-deductions">الخصومات والاستقطاعات ({currency})</Label>
                    <Input
                      id="pay-deductions"
                      type="number"
                      min={0}
                      value={payDeductions}
                      onChange={(e) => {
                        setPayDeductions(e.target.value);
                        const b = Number(payBase || 0);
                        const d = Number(e.target.value || 0);
                        const bo = Number(payBonuses || 0);
                        if (b > 0) setPayAmount(String(Math.max(0, b + bo - d)));
                      }}
                      placeholder="0"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="pay-bonuses">المكافآت والزيادات ({currency})</Label>
                    <Input
                      id="pay-bonuses"
                      type="number"
                      min={0}
                      value={payBonuses}
                      onChange={(e) => {
                        setPayBonuses(e.target.value);
                        const b = Number(payBase || 0);
                        const d = Number(payDeductions || 0);
                        const bo = Number(e.target.value || 0);
                        if (b > 0) setPayAmount(String(b + bo - d));
                      }}
                      placeholder="0"
                    />
                  </div>
                </div>
              </>
            )}
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-2">
                <Label htmlFor="pay-amount">الصافي المصروف ({currency}) *</Label>
                <Input id="pay-amount" type="number" min={0} value={payAmount} onChange={(e) => setPayAmount(e.target.value)} className="font-bold text-primary" required />
                {payDialog?.mode === "add" && (
                  <p className="text-[11px] text-muted-foreground">يُحسب تلقائياً: الاسمي + المكافآت − الخصومات، ويمكن تعديله يدوياً</p>
                )}
              </div>
              {payDialog?.mode === "add" && (
                <div className="space-y-2">
                  <Label htmlFor="pay-voucher">رقم وصل الصرف</Label>
                  <Input id="pay-voucher" value={payVoucher} onChange={(e) => setPayVoucher(e.target.value)} placeholder="اختياري — يُولد تلقائياً SO-XXXX" />
                </div>
              )}
            </div>
            <div className="space-y-2">
              <Label htmlFor="pay-notes">ملاحظات (اختياري)</Label>
              <Input id="pay-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={!!deleteEmp} onOpenChange={(o) => !o && setDeleteEmp(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>حذف الموظف {deleteEmp?.name}؟</AlertDialogTitle>
            <AlertDialogDescription>
              سيُحذف الموظف من القائمة ولا يمكن التراجع من الواجهة. دفعات رواتبه السابقة تبقى محفوظة في السجل
              وتظهر في المصروفات لحفظ صحة الميزانية. هل أنت متأكد من الحذف؟
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>إلغاء</AlertDialogCancel>
            <AlertDialogAction
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
              onClick={(e) => { e.preventDefault(); confirmDeleteEmployee(); }}
              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?.employee?.name} بمبلغ {deletePay ? formatMoney(deletePay.amount, currency) : ""}،
              ويُحذف المصروف المرتبط بها تلقائياً فيعود الرصيد الصحيح. هل أنت متأكد؟
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>إلغاء</AlertDialogCancel>
            <AlertDialogAction
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
              onClick={(e) => { e.preventDefault(); confirmDeletePayment(); }}
              disabled={deleting}
            >
              {deleting ? <Loader2 className="w-4 h-4 ml-2 animate-spin" /> : null}
              نعم، حذف الدفعة
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </Tabs>
  );
}
