"use client";

import { useCallback, useEffect, useRef, 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 { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Progress } from "@/components/ui/progress";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import { ReceiptPrintTemplate } from "@/components/receipt-template";
import { useToast } from "@/hooks/use-toast";
import { apiFetch, formatMoney, formatDate, formatDateTime, startOfLocalDay, gradeLabel, toLocalDateInput } from "@/lib/client-utils";
import { INSTALLMENT_TYPES, effectiveFee, GRADES } from "@/lib/constants";
import { StudentWithStatus, PaymentDTO, SchoolSettingsDTO } from "@/lib/types";
import { useStructure } from "@/lib/structure-context";
import {
  Search, Loader2, Printer, CreditCard, Banknote, CircleAlert,
  GraduationCap, Phone, UserRound, CheckCircle2, CalendarIcon,
} from "lucide-react";

interface PaymentViewProps {
  settings: SchoolSettingsDTO | null;
  onPaymentDone: () => void;
  preselectedId?: string | null;
}

export default function PaymentView({ settings, onPaymentDone, preselectedId }: PaymentViewProps) {
  const { toast } = useToast();
  const currency = settings?.currency || "د.ع";
  const { customLabels } = useStructure();

  const [query, setQuery] = useState("");
  const [searching, setSearching] = useState(false);
  const [results, setResults] = useState<StudentWithStatus[]>([]);
  const [selected, setSelected] = useState<StudentWithStatus | null>(null);

  // فلترة متتالية: الصف ← الشعبة (تسرّع الوصول للطالب بدون كتابة — قابلة للدمج مع البحث بالاسم)
  const [filterGrade, setFilterGrade] = useState("");
  const [filterClassroom, setFilterClassroom] = useState("");
  const [gradeSections, setGradeSections] = useState<{ classroom: string; count: number }[]>([]);

  const [receiptNumber, setReceiptNumber] = useState("");
  const [installmentType, setInstallmentType] = useState("قسط أول");
  const [amount, setAmount] = useState("");
  const [method, setMethod] = useState<"CASH" | "ELECTRONIC">("CASH");
  const [transactionRef, setTransactionRef] = useState("");
  const [notes, setNotes] = useState("");
  const [submitting, setSubmitting] = useState(false);

  // تاريخ الدفع (افتراضياً اليوم — قابل للتعديل إلى تاريخ سابق)
  const todayStr = toLocalDateInput(new Date());
  const [payDate, setPayDate] = useState(todayStr);

  const [receiptDialog, setReceiptDialog] = useState<null | {
    payment: PaymentDTO;
    paidAt: string;
    remaining: number;
    totalFee: number;
    paidTotal: number;
    reprint?: boolean;
  }>(null);

  // مدفوعات اليوم — لإعادة طباعة الوصل عند الحاجة
  const [todayPayments, setTodayPayments] = useState<PaymentDTO[]>([]);

  const [showGateway, setShowGateway] = useState(false);
  const searchTimer = useRef<ReturnType<typeof setTimeout> | null>(null);

  const loadToday = useCallback(async () => {
    try {
      const data = await apiFetch<{ payments: PaymentDTO[] }>("/api/payments?limit=200");
      const start = startOfLocalDay();
      setTodayPayments(data.payments.filter((p) => new Date(p.paidAt) >= start));
    } catch {
      setTodayPayments([]);
    }
  }, []);

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

  const runSearch = useCallback(async (q: string, grade: string, classroom: string) => {
    setSearching(true);
    try {
      const params = new URLSearchParams();
      params.set("q", q);
      // بدون كتابة: نعرض طلبة الفلتر مباشرة (الصف أو الصف + الشعبة)
      const limit = q.trim().length > 1 || grade || classroom ? 100 : 8;
      params.set("limit", String(limit));
      if (grade) params.set("grade", grade);
      if (classroom) params.set("classroom", classroom);
      const data = await apiFetch<{ students: StudentWithStatus[] }>(
        `/api/students?${params.toString()}`
      );
      setResults(data.students);
    } catch {
      setResults([]);
    } finally {
      setSearching(false);
    }
  }, []);

  // البحث الفوري مع تهدئة (debounce) — يتأثر بالفلترة أيضاً
  useEffect(() => {
    if (searchTimer.current) clearTimeout(searchTimer.current);
    searchTimer.current = setTimeout(() => {
      runSearch(query, filterGrade, filterClassroom);
    }, 300);
    return () => {
      if (searchTimer.current) clearTimeout(searchTimer.current);
    };
  }, [query, filterGrade, filterClassroom, runSearch]);

  // عند تغيير الصف: جلب شعب هذا الصف فقط (تتالي الصف ← الشعبة) وتصفير الشعبة المختارة
  useEffect(() => {
    setFilterClassroom("");
    setGradeSections([]);
    if (!filterGrade) return;
    let cancelled = false;
    (async () => {
      try {
        const data = await apiFetch<{ sections: { classroom: string; count: number }[] }>(
          `/api/classes/grade-students?grade=${encodeURIComponent(filterGrade)}`
        );
        if (!cancelled) setGradeSections(data.sections ?? []);
      } catch {
        if (!cancelled) setGradeSections([]);
      }
    })();
    return () => { cancelled = true; };
  }, [filterGrade]);

  // اختيار طالب مسبقاً عند الانتقال من صفحة الطلبة
  useEffect(() => {
    if (!preselectedId) return;
    let cancelled = false;
    (async () => {
      try {
        const data = await apiFetch<{ student: StudentWithStatus & { payments: unknown[] } }>(
          `/api/students/${preselectedId}`
        );
        if (!cancelled && data.student) {
          const s = data.student;
          const mapped: StudentWithStatus = {
            id: s.id,
            studentCode: s.studentCode,
            nameAr: s.nameAr,
            nameEn: s.nameEn,
            grade: s.grade,
            classroom: s.classroom,
            guardianName: s.guardianName,
            guardianPhone: s.guardianPhone,
            totalFee: s.totalFee,
            feeDueDate: s.feeDueDate,
            registeredAt: s.registeredAt,
            createdAt: s.createdAt,
            paid: s.paid,
            remaining: s.remaining,
            paymentsCount: Array.isArray(s.payments) ? s.payments.length : 0,
          };
          pickStudent(mapped);
          setQuery(s.nameAr);
          setResults([mapped]);
        }
      } catch {
        /* تجاهل */
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [preselectedId]);

  function pickStudent(s: StudentWithStatus) {
    setSelected(s);
    setAmount(s.remaining > 0 ? String(s.remaining) : "");
    setReceiptNumber("");
    setTransactionRef("");
    setNotes("");
    setInstallmentType("قسط أول");
    setMethod("CASH");
    setPayDate(toLocalDateInput(new Date()));
  }

  const paidPercent = selected && selected.totalFee > 0 ? Math.min(100, (selected.paid / (selected.effectiveFee || selected.totalFee)) * 100) : 0;
  const fullyPaid = !!selected && selected.remaining <= 0;
  const selectedNetFee = selected ? effectiveFee(selected.totalFee, selected.discountPercent ?? 0) : 0;

  async function submitPayment() {
    if (!selected) return;
    if (!receiptNumber.trim()) {
      toast({ title: "رقم الوصل مطلوب", description: "لا يمكن إتمام الدفع دون إدخال رقم الوصل الورقي", variant: "destructive" });
      return;
    }
    const amt = Number(amount);
    if (!amt || amt <= 0) {
      toast({ title: "المبلغ غير صالح", description: "يرجى إدخال مبلغ صحيح", variant: "destructive" });
      return;
    }
    if (!payDate) {
      toast({ title: "تاريخ الدفع مطلوب", description: "حدد تاريخ الدفع", variant: "destructive" });
      return;
    }
    if (payDate > toLocalDateInput(new Date())) {
      toast({ title: "تاريخ مستقبلي", description: "لا يمكن تسجيل دفع بتاريخ مستقبلي", variant: "destructive" });
      return;
    }
    if (method === "ELECTRONIC" && transactionRef.trim().length < 4) {
      toast({ title: "رقم المرجع الإلكتروني مطلوب", description: "يرجى إدخال رقم مرجع عملية البوابة الإلكترونية", variant: "destructive" });
      return;
    }
    setSubmitting(true);
    try {
      // دمج التاريخ المختار مع وقت التسجيل الحالي
      const nowTime = new Date();
      const hh = String(nowTime.getHours()).padStart(2, "0");
      const mm = String(nowTime.getMinutes()).padStart(2, "0");
      const paidAtIso = new Date(`${payDate}T${hh}:${mm}`).toISOString();
      const data = await apiFetch<{
        payment: PaymentDTO;
        studentStatus: { paid: number; remaining: number; totalFee: number };
      }>("/api/payments", {
        method: "POST",
        body: JSON.stringify({
          studentId: selected.id,
          receiptNumber: receiptNumber.trim(),
          amount: amt,
          installmentType,
          method,
          transactionRef: method === "ELECTRONIC" ? transactionRef.trim() : undefined,
          notes: notes.trim() || undefined,
          paidAt: paidAtIso,
        }),
      });
      setReceiptDialog({
        payment: data.payment,
        paidAt: paidAtIso,
        remaining: data.studentStatus.remaining,
        totalFee: data.studentStatus.totalFee,
        paidTotal: data.studentStatus.paid,
      });
      toast({ title: "تم الدفع بنجاح", description: `سُجل القسط تحت وصل رقم ${data.payment.receiptNumber}` });
      onPaymentDone();
      loadToday();
      // تحديث حالة الطالب المحدد
      setSelected({ ...selected, paid: data.studentStatus.paid, remaining: data.studentStatus.remaining });
      setResults((prev) =>
        prev.map((r) =>
          r.id === selected.id
            ? { ...r, paid: data.studentStatus.paid, remaining: data.studentStatus.remaining }
            : r
        )
      );
    } catch (err) {
      toast({ title: "فشل إتمام الدفع", description: err instanceof Error ? err.message : "", variant: "destructive" });
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <div className="space-y-5">
      {/* مربع البحث السريع */}
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="text-lg flex items-center gap-2">
            <Search className="w-5 h-5 text-primary" />
            البحث السريع عن الطالب
          </CardTitle>
          <CardDescription>ابحث بالاسم العربي أو الإنجليزي أو كود الطالب أو رقم هاتف ولي الأمر</CardDescription>
        </CardHeader>
        <CardContent>
          {/* فلترة متتالية: الصف ← الشعبة (تسرّع الوصول للطالب بدون كتابة) */}
          <div className="grid grid-cols-2 gap-2 mb-3">
            <Select value={filterGrade || "all"} onValueChange={(v) => setFilterGrade(v === "all" ? "" : v)}>
              <SelectTrigger aria-label="فلترة حسب الصف">
                <SelectValue placeholder="كل الصفوف" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">كل الصفوف</SelectItem>
                {GRADES.map((g) => (
                  <SelectItem key={g.code} value={g.code}>{gradeLabel(g.code, customLabels)}</SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Select
              value={filterClassroom || "all"}
              onValueChange={(v) => setFilterClassroom(v === "all" ? "" : v)}
              disabled={!filterGrade}
            >
              <SelectTrigger aria-label="فلترة حسب الشعبة">
                <SelectValue placeholder={filterGrade ? "كل الشعب" : "اختر الصف أولاً"} />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">كل الشعب</SelectItem>
                {gradeSections.map((s) => (
                  <SelectItem key={s.classroom} value={s.classroom}>
                    شعبة {s.classroom} ({s.count} طالب)
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="relative">
            <Search className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
            <Input
              className="pr-9 h-12 text-base"
              placeholder="اكتب اسم الطالب أو الكود... مثال: أحمد أو G5-2026-0001"
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              aria-label="بحث عن طالب"
            />
            {searching && <Loader2 className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 animate-spin text-primary" />}
          </div>

          {/* نتائج البحث */}
          {results.length > 0 && (
            <div className="mt-3 grid gap-2 max-h-72 overflow-y-auto">
              {results.map((s) => (
                <button
                  key={s.id}
                  onClick={() => pickStudent(s)}
                  className={`flex items-center justify-between gap-3 rounded-xl border p-3 text-right transition-colors hover:bg-accent ${
                    selected?.id === s.id ? "border-primary bg-primary/5" : ""
                  }`}
                >
                  <div className="flex items-center gap-3 min-w-0">
                    <div className="w-10 h-10 rounded-full bg-primary/10 text-primary flex items-center justify-center shrink-0">
                      <GraduationCap className="w-5 h-5" />
                    </div>
                    <div className="min-w-0">
                      <p className="font-semibold truncate">{s.nameAr}</p>
                      <p className="text-xs text-muted-foreground truncate" dir="ltr">
                        {s.studentCode} · {s.nameEn}
                      </p>
                    </div>
                  </div>
                  <div className="shrink-0">
                    <Badge variant={s.remaining > 0 ? "destructive" : "secondary"} className="mb-1">
                      {s.remaining > 0 ? `متبقي ${formatMoney(s.remaining, currency)}` : "مكتفي"}
                    </Badge>
                    <p className="text-[11px] text-muted-foreground">
                      {gradeLabel(s.grade, customLabels)} / {s.classroom}
                    </p>
                  </div>
                </button>
              ))}
            </div>
          )}
          {query.trim().length > 1 && !searching && results.length === 0 && (
            <p className="mt-3 text-sm text-muted-foreground text-center py-4">لا توجد نتائج مطابقة لبحثك</p>
          )}
        </CardContent>
      </Card>

      {/* نموذج الدفع */}
      {selected && (
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-lg">إجراء عملية الدفع</CardTitle>
            <CardDescription>بيانات الطالب المحدد وحالة أقساطه</CardDescription>
          </CardHeader>
          <CardContent className="space-y-5">
            {/* ملخص حالة الطالب */}
            <div className="rounded-xl border bg-card p-4 space-y-3">
              <div className="flex flex-wrap items-center justify-between gap-2">
                <div>
                  <p className="font-bold text-base">{selected.nameAr}</p>
                  <p className="text-xs text-muted-foreground" dir="ltr">{selected.nameEn}</p>
                </div>
                <div className="flex flex-col items-start text-xs text-muted-foreground">
                  <span className="flex items-center gap-1" dir="ltr"><span>#{selected.studentCode}</span></span>
                  <span className="flex items-center gap-1"><GraduationCap className="w-3.5 h-3.5" /> {gradeLabel(selected.grade, customLabels)} — شعبة {selected.classroom}</span>
                  <span className="flex items-center gap-1"><UserRound className="w-3.5 h-3.5" /> {selected.guardianName}</span>
                  <span className="flex items-center gap-1" dir="ltr"><Phone className="w-3.5 h-3.5" /> {selected.guardianPhone}</span>
                  <span className="flex items-center gap-1"><CalendarIcon className="w-3.5 h-3.5" /> تاريخ التسجيل: {formatDate(selected.registeredAt || selected.createdAt)}</span>
                </div>
              </div>
              <div className="grid grid-cols-2 sm:grid-cols-4 gap-2 text-center">
                <div className="rounded-lg bg-muted p-2">
                  <p className="text-[11px] text-muted-foreground">القسط الكلي</p>
                  <p className="font-bold text-sm">{formatMoney(selected.totalFee, currency)}</p>
                </div>
                {(selected.discountPercent ?? 0) > 0 && (
                  <div className="rounded-lg bg-emerald-50 p-2">
                    <p className="text-[11px] text-muted-foreground">الخصم</p>
                    <p className="font-bold text-sm text-emerald-700">{selected.discountPercent}% ({formatMoney(selected.totalFee - selectedNetFee, currency)})</p>
                  </div>
                )}
                <div className="rounded-lg bg-primary/10 p-2">
                  <p className="text-[11px] text-muted-foreground">{(selected.discountPercent ?? 0) > 0 ? "الصافي المطلوب" : "المسدد"}</p>
                  <p className="font-bold text-sm text-primary">{(selected.discountPercent ?? 0) > 0 ? formatMoney(selectedNetFee, currency) : formatMoney(selected.paid, currency)}</p>
                </div>
                <div className={`rounded-lg p-2 ${selected.remaining > 0 ? "bg-destructive/10" : "bg-emerald-100"}`}>
                  <p className="text-[11px] text-muted-foreground">المتبقي المستحق</p>
                  <p className={`font-bold text-sm ${selected.remaining > 0 ? "text-destructive" : "text-emerald-700"}`}>
                    {formatMoney(selected.remaining, currency)}
                  </p>
                </div>
              </div>
              <div className="space-y-1">
                <div className="flex justify-between text-xs text-muted-foreground">
                  <span>نسبة السداد</span>
                  <span>{Math.round(paidPercent)}%</span>
                </div>
                <Progress value={paidPercent} className="h-2" />
              </div>
              {selected.remaining === 0 && (
                <div className="flex items-center gap-2 text-sm text-emerald-700 bg-emerald-50 border border-emerald-200 rounded-lg p-2">
                  <CheckCircle2 className="w-4 h-4 shrink-0" />
                  هذا الطالب مكتفي الأقساط — تم سداد كامل الرسوم الدراسية
                </div>
              )}
            </div>

            <Separator />

            {fullyPaid && (
              <div className="flex items-start gap-2 text-sm text-amber-900 bg-amber-50 border border-amber-300 rounded-lg p-3">
                <CircleAlert className="w-4 h-4 mt-0.5 shrink-0 text-amber-600" />
                <div className="space-y-0.5">
                  <p className="font-bold">لا يوجد مبلغ متبقٍ لاستلامه من هذا الطالب</p>
                  <p className="text-xs leading-relaxed">
                    خانة رقم الوصل الورقي تُصبح جاهزة للكتابة تلقائياً عند اختيار طالب لديه أقساط مستحقة، ولا يمكن تسجيل دفع جديد لطالب أكمل سداد رسومه.
                  </p>
                </div>
              </div>
            )}

            <div className="grid gap-4 md:grid-cols-2">
                {/* رقم الوصل الورقي - إجباري ويظهر دائماً */}
                <div className="space-y-2 md:col-span-2 rounded-xl border-2 border-amber-400/70 bg-amber-50/60 p-4">
                  <Label htmlFor="receipt" className="text-sm font-bold">
                    رقم الوصل الورقي <span className="text-destructive font-bold">*</span> (إجباري لإتمام الدفع)
                  </Label>
                  <Input
                    id="receipt"
                    autoFocus
                    disabled={fullyPaid}
                    placeholder="مثال: 12547"
                    value={receiptNumber}
                    onChange={(e) => setReceiptNumber(e.target.value)}
                    className="h-12 text-lg font-bold bg-white"
                    required
                  />
                  <p className="text-xs text-muted-foreground flex items-center gap-1">
                    <CircleAlert className="w-3.5 h-3.5" />
                    يجب إدخال الرقم المدوّن على الوصل الورقي الموقع من ولي الأمر قبل التسجيل
                  </p>
                </div>

                  <div className="space-y-2">
                    <Label htmlFor="pay-date" className="flex items-center gap-1">
                      <CalendarIcon className="w-3.5 h-3.5 text-primary" />
                      تاريخ الدفع
                    </Label>
                    <Input
                      id="pay-date"
                      type="date"
                      value={payDate}
                      max={todayStr}
                      onChange={(e) => setPayDate(e.target.value)}
                      className="h-11 bg-white"
                      disabled={fullyPaid}
                    />
                    <p className="text-xs text-muted-foreground">
                      افتراضياً اليوم — يمكن تغييره لتاريخ سابق لتسجيل دفع متأخر
                    </p>
                  </div>

                  <div className="space-y-2">
                    <Label>نوع القسط</Label>
                    <Select value={installmentType} onValueChange={setInstallmentType} disabled={fullyPaid}>
                      <SelectTrigger className="h-11"><SelectValue /></SelectTrigger>
                      <SelectContent>
                        {INSTALLMENT_TYPES.map((t) => (
                          <SelectItem key={t} value={t}>{t}</SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="amount">المبلغ المستلم ({currency})</Label>
                    <div className="flex gap-2">
                      <Input
                        id="amount"
                        type="number"
                        min={1}
                        max={selected.remaining}
                        value={amount}
                        onChange={(e) => setAmount(e.target.value)}
                        className="h-11 text-lg font-bold"
                        disabled={fullyPaid}
                      />
                      <Button variant="outline" className="h-11 shrink-0" onClick={() => setAmount(String(selected.remaining))} disabled={fullyPaid}>
                        المتبقي كاملاً
                      </Button>
                    </div>
                  </div>

                  {/* طريقة الدفع */}
                  <div className="space-y-2">
                    <Label>طريقة الدفع</Label>
                    <RadioGroup value={method} onValueChange={(v) => setMethod(v as "CASH" | "ELECTRONIC")} disabled={fullyPaid} className="flex gap-3">
                      <Label
                        htmlFor="m-cash"
                        className={`flex flex-1 items-center gap-2 rounded-xl border p-3 cursor-pointer transition-colors ${method === "CASH" ? "border-primary bg-primary/5" : ""}`}
                      >
                        <RadioGroupItem value="CASH" id="m-cash" />
                        <Banknote className="w-4 h-4" />
                        <span className="text-sm font-medium">نقدي / وصل ورقي</span>
                      </Label>
                      <Label
                        htmlFor="m-elec"
                        className={`flex flex-1 items-center gap-2 rounded-xl border p-3 cursor-pointer transition-colors ${method === "ELECTRONIC" ? "border-primary bg-primary/5" : ""}`}
                      >
                        <RadioGroupItem value="ELECTRONIC" id="m-elec" />
                        <CreditCard className="w-4 h-4" />
                        <span className="text-sm font-medium">دفع إلكتروني</span>
                      </Label>
                    </RadioGroup>
                  </div>

                  {method === "ELECTRONIC" && (
                    <div className="space-y-2 md:col-span-2 rounded-xl border border-dashed p-4 bg-muted/40">
                      <div className="flex items-center justify-between gap-2">
                        <Label>بوابة الدفع الإلكتروني (Electronic Payment Gateway)</Label>
                        {!transactionRef && (
                          <Button variant="outline" size="sm" onClick={() => setShowGateway(true)}>
                            <CreditCard className="w-4 h-4 ml-1" />
                            فتح البوابة
                          </Button>
                        )}
                      </div>
                      <Input
                        placeholder="رقم مرجع العملية من البوابة (مثال: TXN-88213)"
                        value={transactionRef}
                        onChange={(e) => setTransactionRef(e.target.value)}
                        className="h-11"
                        dir="ltr"
                      />
                      <p className="text-xs text-muted-foreground">
                        بعد إتمام العملية في البوابة الإلكترونية، أدخل رقم المرجع هنا لتوثيق الدفع
                      </p>
                    </div>
                  )}

                  <div className="space-y-2 md:col-span-2">
                    <Label htmlFor="notes">ملاحظات (اختياري)</Label>
                    <Input id="notes" value={notes} onChange={(e) => setNotes(e.target.value)} placeholder="أي ملاحظات إضافية عن العملية" className="h-11" disabled={fullyPaid} />
                  </div>
                </div>

                <div className="flex flex-col sm:flex-row gap-3">
                  <Button className="flex-1 h-12 text-base font-bold" onClick={submitPayment} disabled={submitting || fullyPaid}>
                    {submitting ? <Loader2 className="w-5 h-5 ml-2 animate-spin" /> : <Banknote className="w-5 h-5 ml-2" />}
                    {submitting ? "جارٍ تسجيل الدفع..." : fullyPaid ? "لا يوجد مبلغ مستحق" : `تسجيل الدفع ${amount ? `(${formatMoney(Number(amount) || 0, currency)})` : ""}`}
                  </Button>
                  <Button variant="outline" className="sm:w-40 h-12" onClick={() => setSelected(null)}>
                    إلغاء
                  </Button>
                </div>
          </CardContent>
        </Card>
      )}

      {/* مدفوعات اليوم — لإعادة طباعة الوصل */}
      {todayPayments.length > 0 && (
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-lg flex items-center gap-2">
              <Printer className="w-5 h-5 text-primary" />
              مدفوعات اليوم
              <Badge variant="secondary">{todayPayments.length}</Badge>
            </CardTitle>
            <CardDescription>الأقساط المستلمة اليوم فقط — لإعادة طباعة أي وصل اضغط زر الطباعة</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-2 max-h-80 overflow-y-auto">
              {todayPayments.map((p) => (
                <div key={p.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 truncate">{p.student?.nameAr}</span>
                      <Badge variant="outline" dir="ltr">{p.receiptNumber}</Badge>
                      <Badge variant="secondary">{p.installmentType}</Badge>
                    </div>
                    <span className="font-bold text-emerald-700">+{formatMoney(p.amount, currency)}</span>
                  </div>
                  <div className="flex items-center justify-between gap-2 flex-wrap">
                    <p className="text-[11px] text-muted-foreground">
                      {formatDateTime(p.paidAt)} · {p.method === "CASH" ? "نقدي" : "إلكتروني"} · بواسطة {p.creator?.fullName ?? "-"}
                    </p>
                    <Button
                      variant="outline"
                      size="sm"
                      className="h-8 shrink-0"
                      onClick={() =>
                        setReceiptDialog({
                          payment: p,
                          paidAt: p.paidAt,
                          remaining: p.remaining ?? 0,
                          totalFee: p.student?.totalFee ?? 0,
                          paidTotal: p.paidTotal ?? 0,
                          reprint: true,
                        })
                      }
                      aria-label={`إعادة طباعة وصل ${p.receiptNumber}`}
                    >
                      <Printer className="w-4 h-4 ml-1" />
                      طباعة الوصل
                    </Button>
                  </div>
                </div>
              ))}
            </div>
            <p className="text-[11px] text-muted-foreground mt-3">
              إجمالي مبالغ اليوم: <span className="font-bold text-emerald-700">{formatMoney(todayPayments.reduce((s, p) => s + p.amount, 0), currency)}</span>
            </p>
          </CardContent>
        </Card>
      )}

      {/* حوار بوابة الدفع الإلكتروني (محاكاة) */}
      <Dialog open={showGateway} onOpenChange={setShowGateway}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <CreditCard className="w-5 h-5 text-primary" />
              بوابة الدفع الإلكتروني
            </DialogTitle>
            <DialogDescription>
              صفحة محاكاة للبوابة الإلكترونية — في النسخة النهائية تُستبدل ببوابة دفع حقيقية (ZainCash / FIB / Qi Card)
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-3">
            <div className="rounded-xl border p-4 space-y-2 text-sm">
              <div className="flex justify-between"><span className="text-muted-foreground">الطالب</span><span className="font-semibold">{selected?.nameAr}</span></div>
              <div className="flex justify-between"><span className="text-muted-foreground">كود الطالب</span><span dir="ltr">{selected?.studentCode}</span></div>
              <div className="flex justify-between border-t pt-2"><span className="text-muted-foreground">المبلغ</span><span className="font-bold text-primary">{formatMoney(Number(amount) || 0, currency)}</span></div>
            </div>
            <div className="grid grid-cols-2 gap-2">
              {["ZainCash", "FIB", "Qi Card", "FastPay"].map((g) => (
                <Button
                  key={g}
                  variant="outline"
                  onClick={() => {
                    setTransactionRef(`TXN-${Math.floor(10000 + Math.random() * 89999)}`);
                    setShowGateway(false);
                    toast({ title: `تمت العملية عبر ${g}`, description: "أُدخل رقم المرجع تلقائياً في نموذج الدفع" });
                  }}
                >
                  الدفع عبر {g}
                </Button>
              ))}
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* حوار الوصل بعد الدفع */}
      <Dialog open={!!receiptDialog} onOpenChange={(open) => !open && setReceiptDialog(null)}>
        <DialogContent className="sm:max-w-lg">
          <DialogHeader>
            <DialogTitle className={`flex items-center gap-2 ${receiptDialog?.reprint ? "text-primary" : "text-emerald-700"}`}>
              {receiptDialog?.reprint ? <Printer className="w-5 h-5" /> : <CheckCircle2 className="w-5 h-5" />}
              {receiptDialog?.reprint ? "إعادة طباعة الوصل" : "تم تسجيل الدفع بنجاح"}
            </DialogTitle>
            <DialogDescription>
              وصل رقم {receiptDialog?.payment.receiptNumber} — يمكنك طباعته الآن أو حفظه كـ PDF
            </DialogDescription>
          </DialogHeader>
          {receiptDialog && (
            <>
              <div className="max-h-[45vh] overflow-y-auto rounded-lg border p-3 text-sm space-y-1.5">
                <div className="flex justify-between"><span className="text-muted-foreground">الطالب</span><span className="font-semibold">{receiptDialog.payment.student?.nameAr}</span></div>
                <div className="flex justify-between"><span className="text-muted-foreground">كود الطالب</span><span dir="ltr">{receiptDialog.payment.student?.studentCode}</span></div>
                <div className="flex justify-between"><span className="text-muted-foreground">نوع القسط</span><span>{receiptDialog.payment.installmentType}</span></div>
                <div className="flex justify-between"><span className="text-muted-foreground">طريقة الدفع</span><span>{receiptDialog.payment.method === "CASH" ? "نقدي" : "إلكتروني"}</span></div>
                <div className="flex justify-between"><span className="text-muted-foreground">المبلغ المدفوع</span><span className="font-bold text-primary">{formatMoney(receiptDialog.payment.amount, currency)}</span></div>
                <div className="flex justify-between"><span className="text-muted-foreground">المتبقي بعد الدفع</span><span className="font-bold">{formatMoney(receiptDialog.remaining, currency)}</span></div>
                <div className="flex justify-between"><span className="text-muted-foreground">التاريخ</span><span>{formatDate(receiptDialog.paidAt)}</span></div>
              </div>
              <div className="flex gap-2">
                <Button
                  className="flex-1"
                  onClick={() => {
                    window.print();
                  }}
                >
                  <Printer className="w-4 h-4 ml-2" />
                  طباعة الوصل / حفظ PDF
                </Button>
                <Button variant="outline" onClick={() => setReceiptDialog(null)}>إغلاق</Button>
              </div>
            </>
          )}
        </DialogContent>
      </Dialog>

      {/* قالب الطباعة (يظهر فقط في وضع الطباعة) */}
      <div id="print-area">
        {receiptDialog && (
          <ReceiptPrintTemplate
            payment={receiptDialog.payment}
            settings={settings}
            paidAt={receiptDialog.paidAt}
            remaining={receiptDialog.remaining}
            totalFee={receiptDialog.totalFee}
            paidTotal={receiptDialog.paidTotal}
            discountPercent={receiptDialog.payment.student?.discountPercent ?? 0}
          />
        )}
      </div>
    </div>
  );
}
