"use client";

/** كشف حساب الطالب التراكمي (v8.1) — حوار تفصيلي قابل للطباعة
 *  يعرض: القسط الكلي، نسبة ومبلغ التخفيض، المسدد، المتبقي،
 *  جدول الأقساط الثمانية مع حالة كل قسط، وسجل كل دفعة بتاريخها ورقم وصل القبض. */

import { useEffect, useState } from "react";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Loader2, Printer, FileText } from "lucide-react";
import { apiFetch, formatMoney, formatDate, gradeLabel } from "@/lib/client-utils";

interface StatementData {
  student: {
    id: string; studentCode: string; nameAr: string; nameEn: string;
    grade: string; classroom: string; guardianName: string; guardianPhone: string;
    registeredAt: string; isActive: boolean;
  };
  feeSummary: {
    grossFee: number; discountPercent: number; discountAmount: number; netFee: number;
    paid: number; remaining: number; installmentsCount: number; monthlyInstallment: number;
    deadline: string; fullyPaid: boolean;
  };
  installments: { seq: number; dueDate: string; amount: number; paidAmount: number; remainingAmount: number; status: string }[];
  payments: { id: string; receiptNumber: string; amount: number; installmentType: string; method: string; paidAt: string; by: string | null }[];
}

const STATUS_STYLE: Record<string, string> = {
  PAID: "bg-emerald-100 text-emerald-800",
  PARTIAL: "bg-amber-100 text-amber-800",
  UNPAID: "bg-red-100 text-red-800",
};
const STATUS_AR: Record<string, string> = { PAID: "مسدد", PARTIAL: "جزئي", UNPAID: "غير مسدد" };

export function StudentStatementDialog({
  studentId,
  open,
  onOpenChange,
  gradeLabels,
}: {
  studentId: string | null;
  open: boolean;
  onOpenChange: (o: boolean) => void;
  gradeLabels?: Record<string, string>;
}) {
  const [data, setData] = useState<StatementData | null>(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (!open || !studentId) return;
    setLoading(true);
    setData(null);
    apiFetch<StatementData>(`/api/students/${studentId}/statement`)
      .then(setData)
      .catch(() => setData(null))
      .finally(() => setLoading(false));
  }, [open, studentId]);

  const printStatement = () => {
    window.print();
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-3xl max-h-[90vh] overflow-y-auto statement-print-area">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <FileText className="w-5 h-5 text-primary" />
            كشف الحساب التراكمي للطالب
          </DialogTitle>
          <DialogDescription>
            سجل مالي شامل: القسط الكلي، التخفيض، الأقساط الثمانية، وكل دفعة برقم وصلها
          </DialogDescription>
        </DialogHeader>

        {loading ? (
          <div className="flex justify-center py-12">
            <Loader2 className="w-8 h-8 animate-spin text-primary" />
          </div>
        ) : !data ? (
          <p className="text-center text-muted-foreground py-8">تعذر جلب الكشف — حاول مجدداً</p>
        ) : (
          <div id="student-statement" className="space-y-4">
            {/* رأس الكشف */}
            <div className="rounded-xl border bg-muted/30 p-4">
              <div className="grid grid-cols-2 sm:grid-cols-3 gap-3 text-sm">
                <div>
                  <p className="text-[11px] text-muted-foreground">اسم الطالب</p>
                  <p className="font-bold">{data.student.nameAr}</p>
                  <p className="text-[11px] text-muted-foreground" dir="ltr">{data.student.nameEn}</p>
                </div>
                <div>
                  <p className="text-[11px] text-muted-foreground">كود الطالب</p>
                  <p className="font-bold" dir="ltr">{data.student.studentCode}</p>
                </div>
                <div>
                  <p className="text-[11px] text-muted-foreground">الصف / الشعبة</p>
                  <p className="font-bold">
                    {gradeLabel(data.student.grade, gradeLabels)} / {data.student.classroom}
                  </p>
                </div>
                <div>
                  <p className="text-[11px] text-muted-foreground">ولي الأمر</p>
                  <p className="font-semibold">{data.student.guardianName}</p>
                </div>
                <div>
                  <p className="text-[11px] text-muted-foreground">هاتف ولي الأمر</p>
                  <p className="font-semibold" dir="ltr">{data.student.guardianPhone}</p>
                </div>
                <div>
                  <p className="text-[11px] text-muted-foreground">تاريخ التسجيل</p>
                  <p className="font-semibold">{formatDate(data.student.registeredAt)}</p>
                </div>
              </div>
            </div>

            {/* ملخص الرسوم */}
            <div className="grid grid-cols-2 sm:grid-cols-5 gap-2 text-center">
              <div className="rounded-lg border p-2">
                <p className="text-[10px] text-muted-foreground">القسط الكلي</p>
                <p className="font-bold text-sm">{formatMoney(data.feeSummary.grossFee)}</p>
              </div>
              <div className="rounded-lg bg-emerald-50 p-2">
                <p className="text-[10px] text-muted-foreground">نسبة التخفيض</p>
                <p className="font-bold text-sm text-emerald-700">{data.feeSummary.discountPercent}%</p>
                <p className="text-[10px] text-emerald-700">({formatMoney(data.feeSummary.discountAmount)})</p>
              </div>
              <div className="rounded-lg bg-primary/10 p-2">
                <p className="text-[10px] text-muted-foreground">الصافي المستحق</p>
                <p className="font-bold text-sm text-primary">{formatMoney(data.feeSummary.netFee)}</p>
              </div>
              <div className="rounded-lg bg-primary/5 p-2">
                <p className="text-[10px] text-muted-foreground">المسدد</p>
                <p className="font-bold text-sm text-primary">{formatMoney(data.feeSummary.paid)}</p>
              </div>
              <div className="rounded-lg bg-destructive/10 p-2">
                <p className="text-[10px] text-muted-foreground">المتبقي</p>
                <p className="font-bold text-sm text-destructive">{formatMoney(data.feeSummary.remaining)}</p>
              </div>
            </div>

            {/* جدول الأقساط الثمانية */}
            <div>
              <p className="text-sm font-semibold mb-2">
                جدول الأقساط ({data.feeSummary.installmentsCount} أقساط شهرية — القسط الشهري {formatMoney(data.feeSummary.monthlyInstallment)})
              </p>
              <div className="rounded-lg border overflow-x-auto">
                <table className="w-full text-xs">
                  <thead className="bg-muted/60">
                    <tr>
                      <th className="p-2 text-right">القسط</th>
                      <th className="p-2 text-right">تاريخ الاستحقاق</th>
                      <th className="p-2 text-right">المبلغ</th>
                      <th className="p-2 text-right">المسدد</th>
                      <th className="p-2 text-right">المتبقي</th>
                      <th className="p-2 text-right">الحالة</th>
                    </tr>
                  </thead>
                  <tbody>
                    {data.installments.map((inst) => (
                      <tr key={inst.seq} className="border-t">
                        <td className="p-2 font-semibold">قسط {inst.seq}</td>
                        <td className="p-2">{formatDate(inst.dueDate)}</td>
                        <td className="p-2">{formatMoney(inst.amount)}</td>
                        <td className="p-2 text-primary font-semibold">{formatMoney(inst.paidAmount)}</td>
                        <td className="p-2 text-destructive">{formatMoney(inst.remainingAmount)}</td>
                        <td className="p-2">
                          <span className={`px-2 py-0.5 rounded-full text-[10px] font-bold ${STATUS_STYLE[inst.status] ?? ""}`}>
                            {STATUS_AR[inst.status] ?? inst.status}
                          </span>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>

            {/* سجل الدفعات */}
            <div>
              <p className="text-sm font-semibold mb-2">سجل الدفعات ({data.payments.length}) — تاريخ كل دفعة ورقم وصل القبض</p>
              {data.payments.length === 0 ? (
                <p className="text-xs text-muted-foreground py-3 text-center border rounded-lg">لا توجد دفعات مسجلة بعد</p>
              ) : (
                <div className="rounded-lg border overflow-x-auto">
                  <table className="w-full text-xs">
                    <thead className="bg-muted/60">
                      <tr>
                        <th className="p-2 text-right">#</th>
                        <th className="p-2 text-right">رقم وصل القبض</th>
                        <th className="p-2 text-right">تاريخ الدفع</th>
                        <th className="p-2 text-right">نوع القسط</th>
                        <th className="p-2 text-right">الطريقة</th>
                        <th className="p-2 text-right">المبلغ</th>
                      </tr>
                    </thead>
                    <tbody>
                      {data.payments.map((p, idx) => (
                        <tr key={p.id} className="border-t">
                          <td className="p-2">{idx + 1}</td>
                          <td className="p-2 font-bold" dir="ltr">{p.receiptNumber}</td>
                          <td className="p-2">{formatDate(p.paidAt)}</td>
                          <td className="p-2">{p.installmentType}</td>
                          <td className="p-2">{p.method === "CASH" ? "نقدي" : "إلكتروني"}</td>
                          <td className="p-2 text-primary font-bold">{formatMoney(p.amount)}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </div>
          </div>
        )}

        <div className="flex gap-2 print:hidden">
          <Button variant="outline" className="flex-1" onClick={printStatement} disabled={!data}>
            <Printer className="w-4 h-4 ml-2" />
            طباعة الكشف
          </Button>
          <Button className="flex-1" onClick={() => onOpenChange(false)}>
            إغلاق
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}
