"use client";

/** سلف المنتسبين (v8.1) — منح سلفة لموظف وتسديدها تدريجياً
 *  كل سلفة تُسجّل مصروفاً تلقائياً برقم وصل صرف، وكل تسديد يُسجّل إيراداً ببند "تسديد سلف منتسبين". */

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 { useToast } from "@/hooks/use-toast";
import { apiFetch, formatMoney, formatDateTime, toLocalDateInput } from "@/lib/client-utils";
import { Loader2, Plus, HandCoins, Wallet } from "lucide-react";

interface LoanRow {
  id: string;
  employeeId: string;
  employeeName: string;
  employeeRole: string;
  employeeType: string;
  amount: number;
  reason: string;
  loanedAt: string;
  notes?: string | null;
  voucherNumber?: string | null;
  repaid: number;
  remaining: number;
  fullyRepaid: boolean;
  repayments: { id: string; amount: number; paidAt: string; notes?: string | null }[];
}

interface EmployeeOption {
  id: string;
  name: string;
  role: string;
}

export function StaffLoansView({
  currency,
  refreshKey,
  onChanged,
}: {
  currency: string;
  refreshKey: number;
  onChanged: () => void;
}) {
  const { toast } = useToast();
  const [loans, setLoans] = useState<LoanRow[]>([]);
  const [employees, setEmployees] = useState<EmployeeOption[]>([]);
  const [loading, setLoading] = useState(true);

  // نموذج منح سلفة
  const [loanDialogOpen, setLoanDialogOpen] = useState(false);
  const [loanEmployee, setLoanEmployee] = useState("");
  const [loanAmount, setLoanAmount] = useState("");
  const [loanReason, setLoanReason] = useState("");
  const [loanDate, setLoanDate] = useState("");
  const [loanVoucher, setLoanVoucher] = useState("");
  const [loanNotes, setLoanNotes] = useState("");
  const [savingLoan, setSavingLoan] = useState(false);

  // نموذج تسديد
  const [repayLoan, setRepayLoan] = useState<LoanRow | null>(null);
  const [repayAmount, setRepayAmount] = useState("");
  const [repayDate, setRepayDate] = useState("");
  const [repayNotes, setRepayNotes] = useState("");
  const [savingRepay, setSavingRepay] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const [loanData, empData] = await Promise.all([
        apiFetch<{ loans: LoanRow[] }>("/api/employee-loans"),
        apiFetch<{ employees: EmployeeOption[] }>("/api/employees"),
      ]);
      setLoans(loanData.loans);
      setEmployees(empData.employees);
    } catch (err) {
      toast({ title: "تعذر تحميل سلف المنتسبين", description: err instanceof Error ? err.message : "", variant: "destructive" });
    } finally {
      setLoading(false);
    }
  }, [toast]);

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

  async function giveLoan(e: React.FormEvent) {
    e.preventDefault();
    const amt = Number(loanAmount);
    if (!loanEmployee) {
      toast({ title: "اختر الموظف", variant: "destructive" });
      return;
    }
    if (!amt || amt <= 0) {
      toast({ title: "مبلغ السلفة غير صالح", variant: "destructive" });
      return;
    }
    if (loanReason.trim().length < 2) {
      toast({ title: "سبب السلفة مطلوب", variant: "destructive" });
      return;
    }
    setSavingLoan(true);
    try {
      await apiFetch("/api/employee-loans", {
        method: "POST",
        body: JSON.stringify({
          employeeId: loanEmployee,
          amount: amt,
          reason: loanReason.trim(),
          loanedAt: loanDate ? new Date(loanDate).toISOString() : undefined,
          voucherNumber: loanVoucher.trim() || undefined,
          notes: loanNotes.trim() || null,
        }),
      });
      toast({
        title: "تم منح السلفة",
        description: `قُيدت مصروفاً (سلف منتسبين)${loanVoucher.trim() ? "" : " مع رقم وصل صرف تلقائي"}`,
      });
      setLoanDialogOpen(false);
      setLoanAmount("");
      setLoanReason("");
      setLoanVoucher("");
      setLoanNotes("");
      onChanged();
      load();
    } catch (err) {
      toast({ title: "فشل منح السلفة", description: err instanceof Error ? err.message : "", variant: "destructive" });
    } finally {
      setSavingLoan(false);
    }
  }

  function openRepay(loan: LoanRow) {
    setRepayLoan(loan);
    setRepayAmount(String(loan.remaining));
    setRepayDate(toLocalDateInput(new Date()));
    setRepayNotes("");
  }

  async function saveRepay(e: React.FormEvent) {
    e.preventDefault();
    if (!repayLoan) return;
    const amt = Number(repayAmount);
    if (!amt || amt <= 0) {
      toast({ title: "مبلغ التسديد غير صالح", variant: "destructive" });
      return;
    }
    if (amt > repayLoan.remaining + 0.001) {
      toast({ title: "المبلغ يتجاوز المتبقي", description: `المتبقي ${formatMoney(repayLoan.remaining, currency)}`, variant: "destructive" });
      return;
    }
    setSavingRepay(true);
    try {
      await apiFetch(`/api/employee-loans/${repayLoan.id}/repayments`, {
        method: "POST",
        body: JSON.stringify({
          amount: amt,
          paidAt: repayDate ? new Date(repayDate).toISOString() : undefined,
          notes: repayNotes.trim() || null,
        }),
      });
      toast({ title: "تم تسجيل التسديد", description: "قُيد إيراداً ببند «تسديد سلف منتسبين» تلقائياً" });
      setRepayLoan(null);
      onChanged();
      load();
    } catch (err) {
      toast({ title: "فشل تسجيل التسديد", description: err instanceof Error ? err.message : "", variant: "destructive" });
    } finally {
      setSavingRepay(false);
    }
  }

  const totalGiven = loans.reduce((s, l) => s + l.amount, 0);
  const totalRepaid = loans.reduce((s, l) => s + l.repaid, 0);
  const totalRemaining = loans.reduce((s, l) => s + l.remaining, 0);

  return (
    <div className="space-y-4">
      <div className="grid gap-3 sm:grid-cols-3">
        <Card className="border-r-4 border-r-red-400">
          <CardContent className="pt-5 pb-4">
            <p className="text-sm text-muted-foreground">إجمالي السلف الممنوحة</p>
            <p className="text-2xl font-extrabold text-red-600 mt-1">{formatMoney(totalGiven, currency)}</p>
          </CardContent>
        </Card>
        <Card className="border-r-4 border-r-emerald-500">
          <CardContent className="pt-5 pb-4">
            <p className="text-sm text-muted-foreground">إجمالي المسدد</p>
            <p className="text-2xl font-extrabold text-emerald-700 mt-1">{formatMoney(totalRepaid, currency)}</p>
          </CardContent>
        </Card>
        <Card className="border-r-4 border-r-amber-500">
          <CardContent className="pt-5 pb-4">
            <p className="text-sm text-muted-foreground">المتبقي (ذمم الموظفين)</p>
            <p className="text-2xl font-extrabold text-amber-600 mt-1">{formatMoney(totalRemaining, currency)}</p>
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardHeader className="pb-3 flex-row items-start justify-between space-y-0">
          <div className="space-y-1.5">
            <CardTitle className="text-base flex items-center gap-2">
              <HandCoins className="w-5 h-5 text-amber-600" />
              سلف الموظفين (المنتسبين)
            </CardTitle>
            <CardDescription>
              تُقيَّد السلفة مصروفاً تلقائياً برقم وصل صرف، وتسديدها يُقيَّد إيراداً ببند "تسديد سلف منتسبين"
            </CardDescription>
          </div>
          <Button
            size="sm"
            onClick={() => {
              setLoanDate(toLocalDateInput(new Date()));
              setLoanDialogOpen(true);
            }}
            className="shrink-0"
            disabled={employees.length === 0}
          >
            <Plus className="w-4 h-4 ml-1" />
            منح سلفة
          </Button>
        </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>
          ) : loans.length === 0 ? (
            <p className="text-sm text-muted-foreground text-center py-8">لا توجد سلف مسجلة — اضغط "منح سلفة"</p>
          ) : (
            <div className="space-y-2 max-h-[480px] overflow-y-auto">
              {loans.map((l) => (
                <div key={l.id} className="rounded-xl border p-3 space-y-2">
                  <div className="flex items-center justify-between gap-2 flex-wrap">
                    <div className="flex items-center gap-2 flex-wrap min-w-0">
                      <span className="font-medium text-sm">{l.employeeName}</span>
                      {l.voucherNumber && (
                        <Badge variant="outline" dir="ltr" className="text-[10px] bg-amber-50">وصل: {l.voucherNumber}</Badge>
                      )}
                      <Badge variant={l.fullyRepaid ? "secondary" : "destructive"} className="text-[10px]">
                        {l.fullyRepaid ? "مسددة بالكامل" : `متبقي ${formatMoney(l.remaining, currency)}`}
                      </Badge>
                    </div>
                    <div className="flex items-center gap-2">
                      <span className="font-bold text-red-600">-{formatMoney(l.amount, currency)}</span>
                      {!l.fullyRepaid && (
                        <Button size="sm" variant="outline" className="h-8" onClick={() => openRepay(l)}>
                          <Wallet className="w-3.5 h-3.5 ml-1" />
                          تسديد
                        </Button>
                      )}
                    </div>
                  </div>
                  <p className="text-[11px] text-muted-foreground">
                    {l.reason} · {formatDateTime(l.loanedAt)} · المسدد {formatMoney(l.repaid, currency)}
                    {l.notes ? ` · ${l.notes}` : ""}
                  </p>
                  {l.repayments.length > 0 && (
                    <div className="rounded-lg bg-muted/40 p-2 space-y-1">
                      {l.repayments.map((r) => (
                        <p key={r.id} className="text-[11px] text-muted-foreground">
                          <span className="text-emerald-700 font-bold">+{formatMoney(r.amount, currency)}</span> — تسديد بتاريخ {formatDateTime(r.paidAt)}
                        </p>
                      ))}
                    </div>
                  )}
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      {/* حوار منح سلفة */}
      <Dialog open={loanDialogOpen} onOpenChange={setLoanDialogOpen}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2 text-primary">
              <HandCoins className="w-5 h-5" />
              منح سلفة لموظف
            </DialogTitle>
            <DialogDescription>
              سيُسجل المصروف تلقائياً ببند "سلف منتسبين" — يمكنك إدخال رقم وصل الصرف الورقي أو تركه فارغاً للتوليد التلقائي
            </DialogDescription>
          </DialogHeader>
          <form onSubmit={giveLoan} className="grid gap-3">
            <div className="space-y-2">
              <Label>الموظف *</Label>
              <Select value={loanEmployee} onValueChange={setLoanEmployee}>
                <SelectTrigger><SelectValue placeholder="اختر الموظف" /></SelectTrigger>
                <SelectContent>
                  {employees.map((e) => (
                    <SelectItem key={e.id} value={e.id}>{e.name}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-2">
                <Label htmlFor="el-amount">المبلغ ({currency}) *</Label>
                <Input id="el-amount" type="number" min={0} step="any" value={loanAmount} onChange={(e) => setLoanAmount(e.target.value)} className="font-bold" required />
              </div>
              <div className="space-y-2">
                <Label htmlFor="el-date">التاريخ *</Label>
                <Input id="el-date" type="date" value={loanDate} onChange={(e) => setLoanDate(e.target.value)} required />
              </div>
            </div>
            <div className="space-y-2">
              <Label htmlFor="el-reason">سبب السلفة *</Label>
              <Input id="el-reason" value={loanReason} onChange={(e) => setLoanReason(e.target.value)} placeholder="مثال: سلفة عائلية، ظرف طارئ" required />
            </div>
            <div className="space-y-2">
              <Label htmlFor="el-voucher">رقم وصل الصرف</Label>
              <Input id="el-voucher" value={loanVoucher} onChange={(e) => setLoanVoucher(e.target.value)} placeholder="اختياري — يُولد تلقائياً إذا تُرك فارغاً" />
            </div>
            <div className="space-y-2">
              <Label htmlFor="el-notes">ملاحظات</Label>
              <Input id="el-notes" value={loanNotes} onChange={(e) => setLoanNotes(e.target.value)} placeholder="اختياري — مثال: يسدد بمقدار 100 شهرياً" />
            </div>
            <div className="flex gap-2 pt-1">
              <Button type="submit" className="flex-1 font-bold" disabled={savingLoan}>
                {savingLoan && <Loader2 className="w-4 h-4 ml-2 animate-spin" />}
                منح السلفة
              </Button>
              <Button type="button" variant="outline" onClick={() => setLoanDialogOpen(false)}>إلغاء</Button>
            </div>
          </form>
        </DialogContent>
      </Dialog>

      {/* حوار تسديد سلفة */}
      <Dialog open={!!repayLoan} onOpenChange={(o) => !o && setRepayLoan(null)}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle className="text-primary">تسديد سلفة — {repayLoan?.employeeName}</DialogTitle>
            <DialogDescription>
              المتبقي {repayLoan ? formatMoney(repayLoan.remaining, currency) : ""} — سيُسجل التسديد إيراداً ببند "تسديد سلف منتسبين" تلقائياً
            </DialogDescription>
          </DialogHeader>
          <form onSubmit={saveRepay} className="grid gap-3">
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-2">
                <Label htmlFor="elr-amount">مبلغ التسديد ({currency}) *</Label>
                <Input id="elr-amount" type="number" min={0} step="any" value={repayAmount} onChange={(e) => setRepayAmount(e.target.value)} className="font-bold" required />
              </div>
              <div className="space-y-2">
                <Label htmlFor="elr-date">التاريخ *</Label>
                <Input id="elr-date" type="date" value={repayDate} onChange={(e) => setRepayDate(e.target.value)} required />
              </div>
            </div>
            <div className="space-y-2">
              <Label htmlFor="elr-notes">ملاحظات</Label>
              <Input id="elr-notes" value={repayNotes} onChange={(e) => setRepayNotes(e.target.value)} placeholder="اختياري" />
            </div>
            <div className="flex gap-2 pt-1">
              <Button type="submit" className="flex-1 font-bold" disabled={savingRepay}>
                {savingRepay && <Loader2 className="w-4 h-4 ml-2 animate-spin" />}
                تسجيل التسديد
              </Button>
              <Button type="button" variant="outline" onClick={() => setRepayLoan(null)}>إلغاء</Button>
            </div>
          </form>
        </DialogContent>
      </Dialog>
    </div>
  );
}
