"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Calendar } from "@/components/ui/calendar";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { useToast } from "@/hooks/use-toast";
import { apiFetch, formatMoney, formatDateTime, formatDate, toLocalDateInput, startOfLocalDay, gradeLabel } from "@/lib/client-utils";
import { ReportData, SchoolSettingsDTO, StudentsStatusReport, StudentStatusRow } from "@/lib/types";
import { useStructure } from "@/lib/structure-context";
import { INSTALLMENT_MONTHS, PAYMENT_STATUS_AR } from "@/lib/fee-schedule";
import { cn } from "@/lib/utils";
import { AccountingReportsView } from "@/components/accounting-reports-view";
import {
  BarChart3, Loader2, CalendarIcon, FileSpreadsheet, Printer,
  TrendingUp, TrendingDown, Scale, Sun, CalendarDays, CalendarRange, CalendarCheck,
  Users, AlertTriangle, CheckCircle2, Clock3, RefreshCw, Database, FileUp,
} from "lucide-react";

interface ReportsViewProps {
  settings: SchoolSettingsDTO | null;
  userRole: string;
}

interface LegacyImportSummary {
  total: number;
  ready: number;
  duplicates: number;
  unmatched: number;
  errors: number;
  readyAmount: number;
}

interface LegacyPreviewRow {
  receiptNumber: string;
  studentCode: string;
  amount: number;
  installmentType: string;
  method: string;
  paidAt: string;
  status: "ready" | "duplicate" | "unmatched" | "error";
  reason: string;
}

interface LegacyImportResponse {
  summary: LegacyImportSummary;
  rows?: LegacyPreviewRow[];
  imported?: number;
}

type ReportType = "daily" | "weekly" | "monthly" | "custom";

const REPORT_TYPES: { key: ReportType; label: string; icon: React.ComponentType<{ className?: string }> }[] = [
  { key: "daily", label: "تقرير يومي", icon: Sun },
  { key: "weekly", label: "تقرير أسبوعي", icon: CalendarDays },
  { key: "monthly", label: "تقرير شهري", icon: CalendarRange },
  { key: "custom", label: "تقرير مخصص", icon: CalendarCheck },
];

type StatusFilter = "ALL" | "DUE" | "REMAINING" | "PAID";

const STATUS_FILTERS: { key: StatusFilter; label: string; icon: React.ComponentType<{ className?: string }>; activeClass: string }[] = [
  { key: "ALL", label: "جميع الطلبة", icon: Users, activeClass: "border-primary bg-primary/5 text-primary" },
  { key: "DUE", label: "مستحق", icon: AlertTriangle, activeClass: "border-red-500 bg-red-50 text-red-700" },
  { key: "REMAINING", label: "متبقي", icon: Clock3, activeClass: "border-amber-500 bg-amber-50 text-amber-700" },
  { key: "PAID", label: "مسدد", icon: CheckCircle2, activeClass: "border-emerald-600 bg-emerald-50 text-emerald-700" },
];

/** حساب نطاق التقرير بتوقيت الجهاز المحلي بالكامل — يمنع انزياح اليوم بسبب فرق التوقيت (بغداد +3) */
function buildLocalRange(t: ReportType, f?: Date, to2?: Date): { from: string; to: string; label: string } {
  const now = new Date();
  let fromD: Date;
  let toD: Date;
  if (t === "custom") {
    fromD = new Date((f ?? now).getFullYear(), (f ?? now).getMonth(), (f ?? now).getDate());
    toD = new Date((to2 ?? now).getFullYear(), (to2 ?? now).getMonth(), (to2 ?? now).getDate(), 23, 59, 59, 999);
  } else if (t === "weekly") {
    const diff = (now.getDay() + 6) % 7; // الأسبوع يبدأ الاثنين
    fromD = new Date(now.getFullYear(), now.getMonth(), now.getDate() - diff);
    toD = new Date(fromD.getFullYear(), fromD.getMonth(), fromD.getDate() + 6, 23, 59, 59, 999);
  } else if (t === "monthly") {
    fromD = new Date(now.getFullYear(), now.getMonth(), 1);
    toD = new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59, 999);
  } else {
    fromD = startOfLocalDay(now);
    toD = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59, 999);
  }
  const fromStr = toLocalDateInput(fromD);
  const toStr = toLocalDateInput(toD);
  const label =
    t === "daily" ? `التقرير اليومي - ${fromStr}`
    : t === "weekly" ? `التقرير الأسبوعي (${fromStr} - ${toStr})`
    : t === "monthly" ? `التقرير الشهري - ${fromStr.slice(0, 7)}`
    : `تقرير مخصص (${fromStr} - ${toStr})`;
  return { from: fromD.toISOString(), to: toD.toISOString(), label };
}

export default function ReportsView({ settings, userRole }: ReportsViewProps) {
  const { toast } = useToast();
  const currency = settings?.currency || "د.ع";

  const [type, setType] = useState<ReportType>("daily");
  const [from, setFrom] = useState<Date | undefined>(new Date());
  const [to, setTo] = useState<Date | undefined>(new Date());
  const [fromOpen, setFromOpen] = useState(false);
  const [toOpen, setToOpen] = useState(false);
  const [data, setData] = useState<ReportData | null>(null);
  const [loading, setLoading] = useState(false);

  // تقرير مستحقات الطلبة (مسدد | مستحق | متبقي)
  const { customLabels } = useStructure();
  const [statusData, setStatusData] = useState<StudentsStatusReport | null>(null);
  const [statusLoading, setStatusLoading] = useState(true);
  const [statusFilter, setStatusFilter] = useState<StatusFilter>("ALL");
  const [printTarget, setPrintTarget] = useState<"financial" | "students">("financial");
  const [legacyFile, setLegacyFile] = useState<File | null>(null);
  const [legacyPreview, setLegacyPreview] = useState<LegacyImportResponse | null>(null);
  const [legacyBusy, setLegacyBusy] = useState(false);
  const canImportLegacy = userRole === "ADMIN" || userRole === "SUPER_ADMIN";

  const loadReport = useCallback(async (t: ReportType, f?: Date, to2?: Date) => {
    setLoading(true);
    try {
      if (t === "custom" && (!f || !to2)) {
        toast({ title: "حدد الفترة", description: "اختر تاريخ البداية والنهاية من التقويم", variant: "destructive" });
        setLoading(false);
        return;
      }
      const range = buildLocalRange(t, f, to2);
      const params = new URLSearchParams({ type: t, from: range.from, to: range.to, label: range.label });
      const d = await apiFetch<ReportData>(`/api/reports?${params.toString()}`);
      setData(d);
    } catch (err) {
      toast({ title: "تعذر جلب التقرير", description: err instanceof Error ? err.message : "", variant: "destructive" });
    } finally {
      setLoading(false);
    }
  }, [toast]);

  useEffect(() => {
    loadReport("daily");
  }, []);

  const loadStatusReport = useCallback(async (log = false) => {
    setStatusLoading(true);
    try {
      const d = await apiFetch<StudentsStatusReport>(`/api/reports/students-status${log ? "?log=1" : ""}`);
      setStatusData(d);
    } catch (err) {
      toast({ title: "تعذر جلب تقرير المستحقات", description: err instanceof Error ? err.message : "", variant: "destructive" });
    } finally {
      setStatusLoading(false);
    }
  }, [toast]);

  useEffect(() => {
    loadStatusReport();
  }, [loadStatusReport]);

  const filteredStudents = useMemo<StudentStatusRow[]>(() => {
    if (!statusData) return [];
    if (statusFilter === "ALL") return statusData.students;
    return statusData.students.filter((s) => s.status === statusFilter);
  }, [statusData, statusFilter]);

  async function exportExcel() {
    if (!data) return;
    try {
      const XLSX = await import("xlsx");
      const rows = data.rows.map((r) => ({
        "التاريخ": formatDateTime(r.date),
        "النوع": r.type === "income" ? "إيراد (قسط)" : "مصروف",
        "المرجع": r.reference,
        "الطالب": r.studentName || "",
        "كود الطالب": r.studentCode || "",
        "الفئة": r.category || "",
        "البيان": r.description,
        "المبلغ": r.amount,
        "المستخدم": r.by,
      }));
      const ws = XLSX.utils.json_to_sheet(rows);
      ws["!cols"] = [{ wch: 18 }, { wch: 12 }, { wch: 14 }, { wch: 22 }, { wch: 16 }, { wch: 14 }, { wch: 32 }, { wch: 12 }, { wch: 14 }];
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, "التقرير المالي");
      // صف الإجماليات
      XLSX.utils.book_append_sheet(
        wb,
        XLSX.utils.json_to_sheet([
          { "البند": "إجمالي الإيرادات", "المبلغ": data.totals.income },
          { "البند": "إجمالي المصروفات", "المبلغ": data.totals.expenses },
          { "البند": "الصافي", "المبلغ": data.totals.net },
          { "البند": "عدد عمليات الإيراد", "المبلغ": data.totals.incomeCount },
          { "البند": "عدد عمليات المصروف", "المبلغ": data.totals.expenseCount },
        ]),
        "الإجماليات"
      );
      const fileName = `تقرير-${data.periodLabel.replace(/[^\u0600-\u06FF\w-]/g, "_").slice(0, 40)}.xlsx`;
      XLSX.writeFile(wb, fileName);
      toast({ title: "تم تصدير التقرير Excel", description: "فحص ملف التنزيلات لديك" });
    } catch (err) {
      toast({ title: "فشل التصدير", description: err instanceof Error ? err.message : "", variant: "destructive" });
    }
  }

  function exportPDF() {
    if (!data) return;
    setPrintTarget("financial");
    setTimeout(() => window.print(), 50);
  }

  const statusCount = (k: StatusFilter): number => {
    if (!statusData) return 0;
    const s = statusData.summary;
    return k === "ALL" ? s.totalCount : k === "DUE" ? s.dueCount : k === "REMAINING" ? s.remainingCount : s.paidCount;
  };

  async function exportStudentsExcel() {
    if (!statusData || filteredStudents.length === 0) return;
    try {
      const XLSX = await import("xlsx");
      const rows = filteredStudents.map((s) => ({
        "كود الطالب": s.studentCode,
        "اسم الطالب": s.nameAr,
        "الصف": gradeLabel(s.grade, customLabels),
        "الشعبة": s.classroom,
        "تاريخ التسجيل": formatDate(s.registeredAt || s.createdAt),
        "القسط الصافي": s.netFee,
        "المسدد": s.paid,
        "المطلوب حتى الآن": s.expectedToDate,
        "المستحق الآن": s.dueNow,
        "المتبقي": s.remaining,
        "الحالة": PAYMENT_STATUS_AR[s.status],
        "متأخر عن الموعد النهائي": s.pastDeadline ? "نعم" : "",
      }));
      const ws = XLSX.utils.json_to_sheet(rows);
      ws["!cols"] = [{ wch: 14 }, { wch: 26 }, { wch: 18 }, { wch: 10 }, { wch: 13 }, { wch: 13 }, { wch: 12 }, { wch: 14 }, { wch: 13 }, { wch: 12 }, { wch: 10 }, { wch: 18 }];
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, "حالة السداد");
      const s = statusData.summary;
      XLSX.utils.book_append_sheet(
        wb,
        XLSX.utils.json_to_sheet([
          { "البند": "عدد الطلبة", "القيمة": s.totalCount },
          { "البند": "طلبة مسددون", "القيمة": s.paidCount },
          { "البند": "طلبة مستحق", "القيمة": s.dueCount },
          { "البند": "طلبة متبقٍ (لم يستحق بعد)", "القيمة": s.remainingCount },
          { "البند": "طلبة تجاوزوا الموعد النهائي", "القيمة": s.lateCount },
          { "البند": "إجمالي المسدد", "القيمة": s.totalPaid },
          { "البند": "إجمالي المستحق الآن", "القيمة": s.totalDueNow },
          { "البند": "إجمالي المتبقي", "القيمة": s.totalRemaining },
        ]),
        "الإجماليات"
      );
      const filterName = statusFilter === "ALL" ? "الكل" : PAYMENT_STATUS_AR[statusFilter];
      XLSX.writeFile(wb, `مستحقات-الطلبة-${filterName}.xlsx`);
      apiFetch("/api/reports/students-status?log=1").catch(() => undefined);
      toast({ title: "تم تصدير تقرير المستحقات Excel", description: "فحص ملف التنزيلات لديك" });
    } catch (err) {
      toast({ title: "فشل التصدير", description: err instanceof Error ? err.message : "", variant: "destructive" });
    }
  }

  function exportStudentsPDF() {
    if (!statusData || filteredStudents.length === 0) return;
    setPrintTarget("students");
    setTimeout(() => window.print(), 100);
  }

  async function processLegacyImport(mode: "preview" | "commit") {
    if (!legacyFile) {
      toast({ title: "اختر قاعدة البيانات", description: "حدد ملف custom.db من البرنامج السابق", variant: "destructive" });
      return;
    }
    if (mode === "commit") {
      const count = legacyPreview?.summary.ready ?? 0;
      if (!window.confirm(`سيتم إضافة ${count} دفعة بتاريخها ورقم وصلها الأصليين إلى المدرسة المحددة. ستظهر هذه المبالغ في التقارير المالية حسب تواريخها القديمة. هل تريد المتابعة؟`)) return;
    }

    setLegacyBusy(true);
    try {
      const body = new FormData();
      body.set("file", legacyFile);
      body.set("mode", mode);
      const result = await apiFetch<LegacyImportResponse>("/api/reports/import-legacy-payments", {
        method: "POST",
        headers: {},
        body,
      });
      if (mode === "preview") {
        setLegacyPreview(result);
        toast({ title: "اكتملت المعاينة", description: `وجدنا ${result.summary.ready} دفعة جاهزة للاستيراد` });
      } else {
        toast({ title: "اكتمل استيراد الدفعات", description: `تمت إضافة ${result.imported ?? 0} دفعة إلى المدرسة المحددة` });
        setLegacyPreview(null);
        setLegacyFile(null);
        const input = document.getElementById("legacy-payments-db") as HTMLInputElement | null;
        if (input) input.value = "";
        await Promise.all([
          loadStatusReport(),
          type === "custom" ? loadReport("custom", from, to) : loadReport(type),
        ]);
      }
    } catch (err) {
      toast({ title: mode === "preview" ? "تعذرت معاينة قاعدة البيانات" : "تعذر استيراد الدفعات", description: err instanceof Error ? err.message : "", variant: "destructive" });
    } finally {
      setLegacyBusy(false);
    }
  }

  return (
    <div className="space-y-5">
      {canImportLegacy && (
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-lg flex items-center gap-2">
              <Database className="w-5 h-5 text-primary" />
              استيراد دفعات البرنامج السابق
            </CardTitle>
            <CardDescription>
              ارفع نسخة قاعدة البيانات القديمة custom.db لنقل الدفعات بتواريخها وأرقام وصولها، مع مطابقة الطلبة بكود الطالب.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="rounded-xl border border-primary/20 bg-primary/5 p-3 text-sm leading-6">
              أوقف البرنامج السابق قبل اختيار قاعدة البيانات لضمان حفظ آخر التغييرات. تُقرأ القاعدة دون تعديل، وتُحذف النسخة المؤقتة بعد المعالجة. اختر المدرسة الصحيحة من القائمة العلوية قبل المعاينة.
              <br />
              ستظهر الدفعات المستوردة في التقارير المالية حسب تواريخها الأصلية، ولن تُسجّل كإيراد بتاريخ الاستيراد.
            </div>
            <div className="flex flex-col gap-3 sm:flex-row sm:items-end">
              <label className="flex-1 space-y-2 text-sm font-medium">
                ملف قاعدة بيانات البرنامج السابق
                <input
                  id="legacy-payments-db"
                  type="file"
                  accept=".db,.sqlite,.sqlite3,application/octet-stream"
                  disabled={legacyBusy}
                  onChange={(event) => {
                    setLegacyFile(event.target.files?.[0] ?? null);
                    setLegacyPreview(null);
                  }}
                  className="block w-full rounded-lg border bg-background p-2 text-sm file:ml-3 file:rounded-md file:border-0 file:bg-primary/10 file:px-3 file:py-1.5 file:font-medium file:text-primary"
                />
              </label>
              <Button variant="outline" onClick={() => processLegacyImport("preview")} disabled={!legacyFile || legacyBusy}>
                {legacyBusy ? <Loader2 className="w-4 h-4 ml-2 animate-spin" /> : <FileUp className="w-4 h-4 ml-2" />}
                معاينة الدفعات
              </Button>
              <Button onClick={() => processLegacyImport("commit")} disabled={!legacyFile || legacyBusy || !legacyPreview?.summary.ready}>
                {legacyBusy ? <Loader2 className="w-4 h-4 ml-2 animate-spin" /> : <Database className="w-4 h-4 ml-2" />}
                استيراد الجاهز
              </Button>
            </div>
            {legacyPreview && (
              <div className="space-y-3 rounded-xl border p-4">
                <p className="font-semibold">نتيجة المعاينة</p>
                <div className="grid grid-cols-2 gap-2 text-sm sm:grid-cols-5">
                  <div className="rounded-lg bg-muted p-3">إجمالي السجلات: <b>{legacyPreview.summary.total}</b></div>
                  <div className="rounded-lg bg-emerald-50 p-3 text-emerald-800">جاهزة: <b>{legacyPreview.summary.ready}</b></div>
                  <div className="rounded-lg bg-amber-50 p-3 text-amber-800">موجودة مسبقاً: <b>{legacyPreview.summary.duplicates}</b></div>
                  <div className="rounded-lg bg-orange-50 p-3 text-orange-800">طالب غير مطابق: <b>{legacyPreview.summary.unmatched}</b></div>
                  <div className="rounded-lg bg-red-50 p-3 text-red-800">تحتاج مراجعة: <b>{legacyPreview.summary.errors}</b></div>
                </div>
                <p className="text-sm text-muted-foreground">إجمالي المبالغ الجاهزة: <b className="text-foreground">{formatMoney(legacyPreview.summary.readyAmount, currency)}</b></p>
                {!!legacyPreview.rows?.length && (
                  <div className="max-h-64 overflow-auto rounded-lg border">
                    <table className="w-full min-w-[720px] text-xs">
                      <thead className="sticky top-0 bg-muted">
                        <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>
                        {legacyPreview.rows.slice(0, 20).map((row, index) => (
                          <tr key={`${row.receiptNumber}-${index}`} className="border-t">
                            <td className="p-2" dir="ltr">{row.receiptNumber || "—"}</td>
                            <td className="p-2" dir="ltr">{row.studentCode || "—"}</td>
                            <td className="p-2">{row.installmentType}</td>
                            <td className="p-2 whitespace-nowrap">{formatMoney(row.amount, currency)}</td>
                            <td className="p-2 whitespace-nowrap">{row.paidAt ? formatDateTime(row.paidAt) : "—"}</td>
                            <td className="p-2">{row.status === "ready" ? "جاهز" : row.reason}</td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                    {legacyPreview.summary.total > 20 && <p className="p-2 text-center text-muted-foreground">تظهر أول 20 حركة فقط في المعاينة</p>}
                  </div>
                )}
              </div>
            )}
          </CardContent>
        </Card>
      )}

      {/* التقارير المحاسبية الشاملة (v8.1): كشف الأقساط التراكمي + المصروفات المصنفة + الميزانية الشهرية */}
      <AccountingReportsView currency={settings?.currency || "د.ع"} />

      {/* تقرير مستحقات الطلبة — حالة السداد */}
      <Card>
        <CardHeader className="pb-3">
          <div className="flex items-start justify-between gap-2 flex-wrap">
            <div>
              <CardTitle className="text-lg flex items-center gap-2">
                <Users className="w-5 h-5 text-primary" />
                تقرير مستحقات الطلبة
              </CardTitle>
              <CardDescription>
                فرز الطلبة حسب حالة السداد — القسط مقسم على {INSTALLMENT_MONTHS} أشهر من تاريخ التسجيل، وكامل المبلغ يستحق قبل نهاية شهر نيسان (الشهر الرابع) من السنة الجديدة
              </CardDescription>
            </div>
            <div className="flex items-center gap-2 shrink-0">
              <Button
                variant="outline"
                size="sm"
                onClick={exportStudentsPDF}
                disabled={statusLoading || filteredStudents.length === 0}
                className="border-primary/40 text-primary hover:bg-primary/5"
                title="طباعة تقرير مستحقات الطلبة"
              >
                <Printer className="w-4 h-4" />
                طباعة التقرير
              </Button>
              <Button variant="outline" size="sm" onClick={() => loadStatusReport()} disabled={statusLoading}>
                {statusLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : <RefreshCw className="w-4 h-4" />}
                تحديث
              </Button>
            </div>
          </div>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* فلاتر الحالة */}
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
            {STATUS_FILTERS.map((sf) => {
              const Icon = sf.icon;
              const count = statusCount(sf.key);
              return (
                <button
                  key={sf.key}
                  onClick={() => setStatusFilter(sf.key)}
                  className={cn(
                    "flex items-center justify-center gap-2 rounded-xl border p-3 text-sm font-medium transition-colors",
                    statusFilter === sf.key ? sf.activeClass : "hover:bg-accent"
                  )}
                >
                  <Icon className="w-4 h-4" />
                  {sf.label}
                  <span className={cn("rounded-full px-2 py-0.5 text-[11px] font-bold", statusFilter === sf.key ? "bg-white/70" : "bg-muted")}>
                    {statusLoading ? "…" : count}
                  </span>
                </button>
              );
            })}
          </div>

          {/* تحذير الطلبة المستحقين — بالأحمر لتنبيه المدير والمحاسب */}
          {statusData && statusData.summary.dueCount > 0 && (
            <div className="rounded-xl border-2 border-red-500 bg-red-100/70 p-3 flex items-center gap-2">
              <AlertTriangle className="w-5 h-5 text-red-600 shrink-0" />
              <p className="text-sm text-red-800 font-bold">
                تنبيه: يوجد {statusData.summary.dueCount} طالب مستحق حالياً بمبلغ {formatMoney(statusData.summary.totalDueNow, currency)} — أقساط هذه الأشهر لم تسدد بعد، يرجى المتابعة مع أولياء الأمور
              </p>
            </div>
          )}

          {/* تحذير المتأخرين عن الموعد النهائي */}
          {statusData && statusData.summary.lateCount > 0 && (
            <div className="rounded-xl border-2 border-red-400 bg-red-50 p-3 flex items-center gap-2">
              <AlertTriangle className="w-5 h-5 text-red-600 shrink-0" />
              <p className="text-sm text-red-700 font-medium">
                يوجد {statusData.summary.lateCount} طالب تجاوز الموعد النهائي لسداد كامل القسط (نهاية شهر نيسان من السنة الجديدة) — كامل المتبقي عليهم أصبح مستحقاً
              </p>
            </div>
          )}

          {/* ملخصات المبالغ */}
          <div className="grid gap-3 sm:grid-cols-3">
            <div className="rounded-xl border-r-4 border-r-red-500 bg-red-50/50 p-3">
              <p className="text-xs text-muted-foreground">إجمالي المستحق الآن ({statusData?.summary.dueCount ?? 0} طالب)</p>
              <p className="text-xl font-extrabold text-red-600 mt-1">{formatMoney(statusData?.summary.totalDueNow ?? 0, currency)}</p>
            </div>
            <div className="rounded-xl border-r-4 border-r-amber-500 bg-amber-50/50 p-3">
              <p className="text-xs text-muted-foreground">إجمالي المتبقي (لم يستحق بعد) ({statusData?.summary.remainingCount ?? 0} طالب)</p>
              <p className="text-xl font-extrabold text-amber-600 mt-1">{formatMoney(statusData?.summary.totalRemaining ?? 0, currency)}</p>
            </div>
            <div className="rounded-xl border-r-4 border-r-emerald-600 bg-emerald-50/50 p-3">
              <p className="text-xs text-muted-foreground">إجمالي المسدد ({statusData?.summary.paidCount ?? 0} طالب)</p>
              <p className="text-xl font-extrabold text-emerald-700 mt-1">{formatMoney(statusData?.summary.totalPaid ?? 0, currency)}</p>
            </div>
          </div>

          {/* أزرار التصدير */}
          <div className="flex flex-col sm:flex-row gap-2">
            <Button variant="outline" className="h-10 flex-1" onClick={exportStudentsExcel} disabled={statusLoading || filteredStudents.length === 0}>
              <FileSpreadsheet className="w-4 h-4 ml-2" />
              تصدير Excel
            </Button>
            <Button variant="outline" className="h-10 flex-1" onClick={exportStudentsPDF} disabled={statusLoading || filteredStudents.length === 0}>
              <Printer className="w-4 h-4 ml-2" />
              تصدير PDF / طباعة
            </Button>
          </div>

          {/* جدول الطلبة */}
          {statusLoading && !statusData ? (
            <div className="flex items-center justify-center gap-2 py-8 text-muted-foreground">
              <Loader2 className="w-5 h-5 animate-spin" />
              <span className="text-sm">جارٍ جلب بيانات المستحقات...</span>
            </div>
          ) : filteredStudents.length === 0 ? (
            <p className="text-sm text-muted-foreground text-center py-8">لا يوجد طلبة ضمن هذه الحالة</p>
          ) : (
            <div className="rounded-xl border overflow-x-auto">
              <table className="w-full text-sm min-w-[900px]">
                <thead className="bg-muted/60">
                  <tr>
                    <th className="text-right p-3 font-semibold">كود الطالب</th>
                    <th className="text-right p-3 font-semibold">الاسم</th>
                    <th className="text-right p-3 font-semibold">الصف / الشعبة</th>
                    <th className="text-right p-3 font-semibold">تاريخ التسجيل</th>
                    <th className="text-right p-3 font-semibold">القسط الصافي</th>
                    <th className="text-right p-3 font-semibold">المسدد</th>
                    <th className="text-right p-3 font-semibold">المستحق الآن</th>
                    <th className="text-right p-3 font-semibold">المتبقي</th>
                    <th className="text-right p-3 font-semibold">الحالة</th>
                  </tr>
                </thead>
                <tbody>
                  {filteredStudents.map((s) => (
                    <tr key={s.id} className={cn("border-t hover:bg-accent/40", s.pastDeadline && "bg-red-50/50")}>
                      <td className="p-3 whitespace-nowrap"><span dir="ltr" className="text-xs font-medium">{s.studentCode}</span></td>
                      <td className="p-3 text-xs font-semibold">{s.nameAr}</td>
                      <td className="p-3 text-xs whitespace-nowrap">{gradeLabel(s.grade, customLabels)} / {s.classroom}</td>
                      <td className="p-3 text-xs whitespace-nowrap">{formatDate(s.registeredAt || s.createdAt)}</td>
                      <td className="p-3 text-xs whitespace-nowrap">{formatMoney(s.netFee, currency)}</td>
                      <td className="p-3 text-xs whitespace-nowrap text-emerald-700 font-medium">{formatMoney(s.paid, currency)}</td>
                      <td className={cn("p-3 text-xs whitespace-nowrap font-bold", s.dueNow > 0 ? "text-red-600" : "text-muted-foreground")}>
                        {s.dueNow > 0 ? formatMoney(s.dueNow, currency) : "—"}
                      </td>
                      <td className={cn("p-3 text-xs whitespace-nowrap", s.remaining > 0 ? "text-amber-700 font-medium" : "text-emerald-700")}>
                        {formatMoney(s.remaining, currency)}
                      </td>
                      <td className="p-3">
                        <div className="flex items-center gap-1 flex-wrap">
                          <Badge
                            className={cn(
                              "text-[11px] border-transparent",
                              s.status === "PAID" && "bg-emerald-100 text-emerald-800",
                              s.status === "DUE" && "bg-red-100 text-red-700",
                              s.status === "REMAINING" && "bg-amber-100 text-amber-800"
                            )}
                          >
                            {PAYMENT_STATUS_AR[s.status]}
                          </Badge>
                          {s.pastDeadline && (
                            <Badge variant="destructive" className="text-[11px]">متأخر عن الموعد النهائي</Badge>
                          )}
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </CardContent>
      </Card>

      {/* اختيار نوع التقرير والفترة */}
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="text-lg flex items-center gap-2">
            <BarChart3 className="w-5 h-5 text-primary" />
            التقارير المالية
          </CardTitle>
          <CardDescription>اختر نوع التقرير والفترة الزمنية من التقويم ثم اعرض النتائج وقم بتصديرها</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
            {REPORT_TYPES.map((rt) => {
              const Icon = rt.icon;
              return (
                <button
                  key={rt.key}
                  onClick={() => setType(rt.key)}
                  className={cn(
                    "flex items-center justify-center gap-2 rounded-xl border p-3 text-sm font-medium transition-colors",
                    type === rt.key ? "border-primary bg-primary/5 text-primary" : "hover:bg-accent"
                  )}
                >
                  <Icon className="w-4 h-4" />
                  {rt.label}
                </button>
              );
            })}
          </div>

          {type === "custom" && (
            <div className="grid gap-3 sm:grid-cols-2">
              <div className="space-y-1">
                <p className="text-xs text-muted-foreground">من تاريخ</p>
                <Popover open={fromOpen} onOpenChange={setFromOpen}>
                  <PopoverTrigger asChild>
                    <Button variant="outline" className={cn("w-full justify-between", !from && "text-muted-foreground")}>
                      {from ? new Intl.DateTimeFormat("ar-IQ-u-nu-latn", { dateStyle: "medium" }).format(from) : "اختر التاريخ"}
                      <CalendarIcon className="w-4 h-4" />
                    </Button>
                  </PopoverTrigger>
                  <PopoverContent className="w-auto p-0" align="start">
                    <Calendar mode="single" selected={from} onSelect={(d) => { setFrom(d); setFromOpen(false); }} initialFocus />
                  </PopoverContent>
                </Popover>
              </div>
              <div className="space-y-1">
                <p className="text-xs text-muted-foreground">إلى تاريخ</p>
                <Popover open={toOpen} onOpenChange={setToOpen}>
                  <PopoverTrigger asChild>
                    <Button variant="outline" className={cn("w-full justify-between", !to && "text-muted-foreground")}>
                      {to ? new Intl.DateTimeFormat("ar-IQ-u-nu-latn", { dateStyle: "medium" }).format(to) : "اختر التاريخ"}
                      <CalendarIcon className="w-4 h-4" />
                    </Button>
                  </PopoverTrigger>
                  <PopoverContent className="w-auto p-0" align="start">
                    <Calendar mode="single" selected={to} onSelect={(d) => { setTo(d); setToOpen(false); }} initialFocus />
                  </PopoverContent>
                </Popover>
              </div>
            </div>
          )}

          <div className="flex flex-col sm:flex-row gap-2">
            <Button
              className="flex-1 h-11 font-bold"
              onClick={() => loadReport(type, from, to)}
              disabled={loading}
            >
              {loading ? <Loader2 className="w-4 h-4 ml-2 animate-spin" /> : <BarChart3 className="w-4 h-4 ml-2" />}
              عرض التقرير
            </Button>
            <Button variant="outline" className="h-11" onClick={exportExcel} disabled={!data || loading}>
              <FileSpreadsheet className="w-4 h-4 ml-2" />
              تصدير Excel
            </Button>
            <Button variant="outline" className="h-11" onClick={exportPDF} disabled={!data || loading}>
              <Printer className="w-4 h-4 ml-2" />
              تصدير PDF / طباعة
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* نتائج التقرير */}
      {data && (
        <>
          <div className="grid gap-3 sm:grid-cols-3">
            <Card className="border-r-4 border-r-emerald-600">
              <CardContent className="pt-5 flex items-center justify-between">
                <div>
                  <p className="text-sm text-muted-foreground">إيرادات الفترة ({data.totals.incomeCount} عملية)</p>
                  <p className="text-2xl font-extrabold text-emerald-700 mt-1">{formatMoney(data.totals.income, currency)}</p>
                </div>
                <TrendingUp className="w-8 h-8 text-emerald-600" />
              </CardContent>
            </Card>
            <Card className="border-r-4 border-r-red-500">
              <CardContent className="pt-5 flex items-center justify-between">
                <div>
                  <p className="text-sm text-muted-foreground">مصروفات الفترة ({data.totals.expenseCount} عملية)</p>
                  <p className="text-2xl font-extrabold text-red-600 mt-1">{formatMoney(data.totals.expenses, currency)}</p>
                </div>
                <TrendingDown className="w-8 h-8 text-red-500" />
              </CardContent>
            </Card>
            <Card className="border-r-4 border-r-amber-500">
              <CardContent className="pt-5 flex items-center justify-between">
                <div>
                  <p className="text-sm text-muted-foreground">صافي الفترة</p>
                  <p className={cn("text-2xl font-extrabold mt-1", data.totals.net >= 0 ? "text-emerald-700" : "text-red-600")}>
                    {formatMoney(data.totals.net, currency)}
                  </p>
                </div>
                <Scale className="w-8 h-8 text-amber-500" />
              </CardContent>
            </Card>
          </div>

          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-base">{data.periodLabel}</CardTitle>
              <CardDescription>جميع الحركات المالية خلال الفترة المحددة مرتبة زمنياً</CardDescription>
            </CardHeader>
            <CardContent>
              {data.rows.length === 0 ? (
                <p className="text-sm text-muted-foreground text-center py-8">لا توجد حركات مالية خلال هذه الفترة</p>
              ) : (
                <div className="rounded-xl border overflow-x-auto">
                  <table className="w-full text-sm min-w-[640px]">
                    <thead className="bg-muted/60">
                      <tr>
                        <th className="text-right p-3 font-semibold">التاريخ والوقت</th>
                        <th className="text-right p-3 font-semibold">النوع</th>
                        <th className="text-right p-3 font-semibold">المرجع / الطالب</th>
                        <th className="text-right p-3 font-semibold">البيان</th>
                        <th className="text-right p-3 font-semibold">بواسطة</th>
                        <th className="text-right p-3 font-semibold">المبلغ</th>
                      </tr>
                    </thead>
                    <tbody>
                      {data.rows.map((r) => (
                        <tr key={`${r.type}-${r.id}`} className="border-t hover:bg-accent/40">
                          <td className="p-3 whitespace-nowrap text-xs">{formatDateTime(r.date)}</td>
                          <td className="p-3">
                            <Badge variant={r.type === "income" ? "secondary" : "destructive"} className="text-[11px]">
                              {r.type === "income" ? "إيراد" : "مصروف"}
                            </Badge>
                          </td>
                          <td className="p-3 text-xs">
                            {r.type === "income" ? (
                              <>
                                <span dir="ltr" className="block font-medium">{r.reference}</span>
                                <span>{r.studentName} · {r.studentCode}</span>
                              </>
                            ) : (
                              <span>{r.category}</span>
                            )}
                          </td>
                          <td className="p-3 text-xs max-w-52 truncate">
                            {r.description}
                            {r.installmentType ? ` (${r.installmentType})` : ""}
                            {r.method ? ` - ${r.method === "CASH" ? "نقدي" : "إلكتروني"}` : ""}
                          </td>
                          <td className="p-3 text-xs">{r.by}</td>
                          <td className={cn("p-3 font-bold whitespace-nowrap text-right", r.type === "income" ? "text-emerald-700" : "text-red-600")}>
                            {r.type === "income" ? "+" : "-"}
                            {formatMoney(r.amount, currency)}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </CardContent>
          </Card>
        </>
      )}

      {/* قالب طباعة التقرير (PDF) — مستحقات الطلبة أو التقرير المالي */}
      <div id="print-area">
        {printTarget === "students" && statusData && filteredStudents.length > 0 && (
          <div dir="rtl" style={{ fontFamily: "Cairo, Tahoma, sans-serif", color: "#111", padding: 8 }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", borderBottom: "2px solid #333", paddingBottom: 10, marginBottom: 14 }}>
              <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
                {settings?.logoData && (
                  <img src={settings.logoData} alt="شعار" style={{ width: 52, height: 52, objectFit: "contain" }} />
                )}
                <div>
                  <h1 style={{ fontSize: 18, fontWeight: 800, margin: 0 }}>{settings?.nameAr || "المدرسة الأهلية"}</h1>
                  <p style={{ fontSize: 11, margin: 0, color: "#555" }}>{settings?.nameEn}</p>
                </div>
              </div>
              <div style={{ textAlign: "left" }}>
                <p style={{ fontSize: 13, fontWeight: 700, margin: 0 }}>
                  تقرير مستحقات الطلبة — حالة السداد{statusFilter !== "ALL" ? ` (${PAYMENT_STATUS_AR[statusFilter]})` : ""}
                </p>
                <p style={{ fontSize: 10, margin: 0, color: "#666" }}>
                  طُبع في {formatDateTime(new Date())} · نظام الإدارة المالية
                </p>
              </div>
            </div>

            <p style={{ fontSize: 10, margin: "0 0 10px", color: "#444", background: "#f9fafb", border: "1px solid #e5e7eb", borderRadius: 6, padding: "6px 10px" }}>
              قاعدة السداد: القسط الصافي مقسم على {INSTALLMENT_MONTHS} أشهر من تاريخ تسجيل كل طالب — كامل المبلغ يجب سداده قبل نهاية شهر نيسان (الشهر الرابع) من السنة الجديدة، وبعد هذا الموعد يصبح كامل المتبقي مستحقاً.
            </p>

            <div style={{ display: "flex", gap: 10, marginBottom: 14 }}>
              <div style={{ flex: 1, border: "1px solid #ccc", borderRadius: 8, padding: "8px 12px" }}>
                <p style={{ fontSize: 10, margin: 0, color: "#666" }}>إجمالي المستحق الآن ({statusData.summary.dueCount} طالب)</p>
                <p style={{ fontSize: 15, fontWeight: 800, margin: 0, color: "#b91c1c" }}>{formatMoney(statusData.summary.totalDueNow, currency)}</p>
              </div>
              <div style={{ flex: 1, border: "1px solid #ccc", borderRadius: 8, padding: "8px 12px" }}>
                <p style={{ fontSize: 10, margin: 0, color: "#666" }}>إجمالي المتبقي ({statusData.summary.remainingCount} طالب)</p>
                <p style={{ fontSize: 15, fontWeight: 800, margin: 0, color: "#b45309" }}>{formatMoney(statusData.summary.totalRemaining, currency)}</p>
              </div>
              <div style={{ flex: 1, border: "2px solid #333", borderRadius: 8, padding: "8px 12px" }}>
                <p style={{ fontSize: 10, margin: 0, color: "#666" }}>إجمالي المسدد ({statusData.summary.paidCount} طالب)</p>
                <p style={{ fontSize: 15, fontWeight: 800, margin: 0, color: "#047857" }}>{formatMoney(statusData.summary.totalPaid, currency)}</p>
              </div>
            </div>

            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 10 }} dir="rtl">
              <thead>
                <tr style={{ background: "#f3f4f6" }}>
                  <th style={thStyle}>الكود</th>
                  <th style={thStyle}>الاسم</th>
                  <th style={thStyle}>الصف / الشعبة</th>
                  <th style={thStyle}>تاريخ التسجيل</th>
                  <th style={thStyle}>القسط الصافي</th>
                  <th style={thStyle}>المسدد</th>
                  <th style={thStyle}>المستحق الآن</th>
                  <th style={thStyle}>المتبقي</th>
                  <th style={thStyle}>الحالة</th>
                </tr>
              </thead>
              <tbody>
                {filteredStudents.map((s) => (
                  <tr key={s.id}>
                    <td style={tdStyle} dir="ltr">{s.studentCode}</td>
                    <td style={tdStyle}>{s.nameAr}</td>
                    <td style={tdStyle}>{gradeLabel(s.grade, customLabels)} / {s.classroom}</td>
                    <td style={tdStyle}>{formatDate(s.registeredAt || s.createdAt)}</td>
                    <td style={tdStyle}>{formatMoney(s.netFee, currency)}</td>
                    <td style={{ ...tdStyle, color: "#047857" }}>{formatMoney(s.paid, currency)}</td>
                    <td style={{ ...tdStyle, fontWeight: 700, color: s.dueNow > 0 ? "#b91c1c" : "#666" }}>
                      {s.dueNow > 0 ? formatMoney(s.dueNow, currency) : "—"}
                    </td>
                    <td style={{ ...tdStyle, color: s.remaining > 0 ? "#b45309" : "#047857" }}>{formatMoney(s.remaining, currency)}</td>
                    <td style={{ ...tdStyle, fontWeight: 700 }}>
                      {PAYMENT_STATUS_AR[s.status]}{s.pastDeadline ? " (متأخر)" : ""}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>

            <p style={{ fontSize: 9, color: "#777", textAlign: "center", marginTop: 12, borderTop: "1px solid #ccc", paddingTop: 6 }}>
              {settings?.footerText || "تقرير مالي رسمي"} — عدد الطلبة المعروضين: {filteredStudents.length}
            </p>
          </div>
        )}
        {printTarget === "financial" && data && (
          <div dir="rtl" style={{ fontFamily: "Cairo, Tahoma, sans-serif", color: "#111", padding: 8 }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", borderBottom: "2px solid #333", paddingBottom: 10, marginBottom: 14 }}>
              <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
                {settings?.logoData && (
                  <img src={settings.logoData} alt="شعار" style={{ width: 52, height: 52, objectFit: "contain" }} />
                )}
                <div>
                  <h1 style={{ fontSize: 18, fontWeight: 800, margin: 0 }}>{settings?.nameAr || "المدرسة الأهلية"}</h1>
                  <p style={{ fontSize: 11, margin: 0, color: "#555" }}>{settings?.nameEn}</p>
                </div>
              </div>
              <div style={{ textAlign: "left" }}>
                <p style={{ fontSize: 13, fontWeight: 700, margin: 0 }}>{data.periodLabel}</p>
                <p style={{ fontSize: 10, margin: 0, color: "#666" }}>
                  طُبع في {formatDateTime(new Date())} · نظام الإدارة المالية
                </p>
              </div>
            </div>

            <div style={{ display: "flex", gap: 10, marginBottom: 14 }}>
              <div style={{ flex: 1, border: "1px solid #ccc", borderRadius: 8, padding: "8px 12px" }}>
                <p style={{ fontSize: 10, margin: 0, color: "#666" }}>إجمالي الإيرادات</p>
                <p style={{ fontSize: 16, fontWeight: 800, margin: 0, color: "#047857" }}>{formatMoney(data.totals.income, currency)}</p>
              </div>
              <div style={{ flex: 1, border: "1px solid #ccc", borderRadius: 8, padding: "8px 12px" }}>
                <p style={{ fontSize: 10, margin: 0, color: "#666" }}>إجمالي المصروفات</p>
                <p style={{ fontSize: 16, fontWeight: 800, margin: 0, color: "#b91c1c" }}>{formatMoney(data.totals.expenses, currency)}</p>
              </div>
              <div style={{ flex: 1, border: "2px solid #333", borderRadius: 8, padding: "8px 12px" }}>
                <p style={{ fontSize: 10, margin: 0, color: "#666" }}>الصافي</p>
                <p style={{ fontSize: 16, fontWeight: 800, margin: 0 }}>{formatMoney(data.totals.net, currency)}</p>
              </div>
            </div>

            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 10 }} dir="rtl">
              <thead>
                <tr style={{ background: "#f3f4f6" }}>
                  <th style={thStyle}>التاريخ</th>
                  <th style={thStyle}>النوع</th>
                  <th style={thStyle}>المرجع</th>
                  <th style={thStyle}>الطالب / الفئة</th>
                  <th style={thStyle}>البيان</th>
                  <th style={thStyle}>بواسطة</th>
                  <th style={thStyle}>المبلغ</th>
                </tr>
              </thead>
              <tbody>
                {data.rows.map((r) => (
                  <tr key={`${r.type}-${r.id}`}>
                    <td style={tdStyle}>{formatDateTime(r.date)}</td>
                    <td style={tdStyle}>{r.type === "income" ? "إيراد" : "مصروف"}</td>
                    <td style={tdStyle} dir="ltr">{r.reference}</td>
                    <td style={tdStyle}>{r.studentName || r.category}</td>
                    <td style={tdStyle}>{r.description}</td>
                    <td style={tdStyle}>{r.by}</td>
                    <td style={{ ...tdStyle, fontWeight: 700, color: r.type === "income" ? "#047857" : "#b91c1c" }}>
                      {r.type === "income" ? "+" : "-"}
                      {formatMoney(r.amount, currency)}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>

            <p style={{ fontSize: 9, color: "#777", textAlign: "center", marginTop: 12, borderTop: "1px solid #ccc", paddingTop: 6 }}>
              {settings?.footerText || "تقرير مالي رسمي"} — عدد العمليات: {data.rows.length}
            </p>
          </div>
        )}
      </div>
    </div>
  );
}

const thStyle: React.CSSProperties = {
  border: "1px solid #ccc",
  padding: "6px 8px",
  fontSize: 10,
  textAlign: "right",
};

const tdStyle: React.CSSProperties = {
  border: "1px solid #ddd",
  padding: "5px 8px",
  fontSize: 10,
};
