"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 { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Checkbox } from "@/components/ui/checkbox";
import { useToast } from "@/hooks/use-toast";
import { apiFetch, formatMoney, formatDate, gradeLabel, todayISO, toLocalDateInput } from "@/lib/client-utils";
import { StudentWithStatus, SchoolSettingsDTO, PaymentDTO } from "@/lib/types";
import { useStructure } from "@/lib/structure-context";
import { effectiveFee, QUAD_NAME_WORDS } from "@/lib/constants";
import { cn } from "@/lib/utils";
import { StudentStatementDialog } from "@/components/student-statement-dialog";
import {
  UserPlus, Search, Loader2, Languages, Wand2, CalendarIcon,
  GraduationCap, Eye, CheckCircle2, NotebookPen, Pencil, CircleAlert, RotateCcw, Percent, Trash2,
  Download, Upload, FileSpreadsheet, XCircle, AlertTriangle, FileText,
} from "lucide-react";

/** نتيجة فحص صف في ملف الاستيراد */
interface ImportRowResult {
  row: number;
  name: string;
  grade: string;
  classroom: string;
  status: "ready" | "imported" | "skipped" | "error";
  reason: string;
}

interface ImportCounts {
  ready: number;
  imported: number;
  skipped: number;
  error: number;
}

interface StudentsViewProps {
  settings: SchoolSettingsDTO | null;
  userRole: string;
  onStudentsChanged: () => void;
  onGoPayment: (studentId: string) => void;
}

const NAME_PART_LABELS = ["الاسم", "اسم الأب", "اسم الجد", "اللقب"];

/** أسماء الطلبة المطابقة من فحص التطابق */
interface NameMatch {
  id: string;
  nameAr: string;
  studentCode: string;
  grade: string;
  classroom: string;
}

export default function StudentsView({ settings, userRole, onStudentsChanged, onGoPayment }: StudentsViewProps) {
  const { toast } = useToast();
  const currency = settings?.currency || "د.ع";
  const { grades, classrooms, customLabels, reload } = useStructure();
  const canRegister = userRole === "ADMIN" || userRole === "STAFF" || userRole === "SUPER_ADMIN";

  const [query, setQuery] = useState("");
  const [results, setResults] = useState<StudentWithStatus[]>([]);
  const [loading, setLoading] = useState(false);

  // نموذج التسجيل
  const [nameAr, setNameAr] = useState("");
  const [nameEn, setNameEn] = useState("");
  const [translating, setTranslating] = useState(false);
  const [grade, setGrade] = useState("");
  const [classroom, setClassroom] = useState("");
  const [guardianName, setGuardianName] = useState("");
  const [guardianTouched, setGuardianTouched] = useState(false);
  const [guardianPhone, setGuardianPhone] = useState("");
  const [guardianAddress, setGuardianAddress] = useState("");
  const [totalFee, setTotalFee] = useState("");
  const [discountPercent, setDiscountPercent] = useState("");
  const [registeredDate, setRegisteredDate] = useState(todayISO());
  const [notes, setNotes] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [allowDuplicate, setAllowDuplicate] = useState(false);

  // فحص تطابق الاسم
  const [nameMatches, setNameMatches] = useState<NameMatch[]>([]);
  const nameCheckTimer = useRef<ReturnType<typeof setTimeout> | null>(null);

  // معاينة الكود التلقائي
  const [codePreview, setCodePreview] = useState("");
  const [successDialog, setSuccessDialog] = useState<null | { nameAr: string; code: string }>(null);

  // تفاصيل الطالب
  const [detailsOpen, setDetailsOpen] = useState(false);
  const [detailsStudent, setDetailsStudent] = useState<(StudentWithStatus & { paymentsList?: PaymentDTO[] }) | null>(null);
  const [detailsLoading, setDetailsLoading] = useState(false);

  // تعديل الطالب (إصلاح خطأ التسجيل)
  const [editOpen, setEditOpen] = useState(false);
  const [editSaving, setEditSaving] = useState(false);
  const [editForm, setEditForm] = useState<{
    id: string; studentCode: string;
    nameAr: string; nameEn: string;
    grade: string; classroom: string;
    guardianName: string; guardianPhone: string;
    discountPercent: string;
    registeredDate: string;
  } | null>(null);
  const [editMatches, setEditMatches] = useState<NameMatch[]>([]);
  const [editAllowDuplicate, setEditAllowDuplicate] = useState(false);

  // حذف طالب (مدير فقط) — تعطيل منطقي، تبقى أقساطه وسجلاته محفوظة
  const [deleteStudent, setDeleteStudent] = useState<StudentWithStatus | null>(null);
  // كشف الحساب التراكمي (v8.1)
  const [statementStudentId, setStatementStudentId] = useState<string | null>(null);
  const [statementOpen, setStatementOpen] = useState(false);
  const [deletingStudent, setDeletingStudent] = useState(false);

  // تصدير واستيراد الطلبة (Excel)
  const [exporting, setExporting] = useState(false);
  const [importOpen, setImportOpen] = useState(false);
  const [importStage, setImportStage] = useState<"select" | "preview" | "done">("select");
  const [importFile, setImportFile] = useState<File | null>(null);
  const [importRows, setImportRows] = useState<ImportRowResult[]>([]);
  const [importCounts, setImportCounts] = useState<ImportCounts>({ ready: 0, imported: 0, skipped: 0, error: 0 });
  const [importTotal, setImportTotal] = useState(0);
  const [importBusy, setImportBusy] = useState(false);

  const translateTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
  const lastTranslated = useRef("");

  // كلمات الاسم الرباعي
  const nameWords = nameAr.trim().replace(/\s+/g, " ").split(" ").filter(Boolean);
  const wordCount = nameAr.trim() ? nameWords.length : 0;
  const quadComplete = wordCount >= QUAD_NAME_WORDS;

  // الترجمة التلقائية للاسم العربي إلى الإنجليزية
  useEffect(() => {
    if (translateTimer.current) clearTimeout(translateTimer.current);
    const name = nameAr.trim();
    if (name.length < 2 || !/[\u0600-\u06FF]/.test(name)) return;
    if (name === lastTranslated.current) return;
    translateTimer.current = setTimeout(async () => {
      setTranslating(true);
      try {
        const data = await apiFetch<{ nameEn: string }>("/api/translate-name", {
          method: "POST",
          body: JSON.stringify({ nameAr: name }),
        });
        if (data.nameEn) {
          setNameEn(data.nameEn);
          lastTranslated.current = name;
        }
      } catch {
        /* الترجمة صامتة عند الفشل - يكتب الموظف الاسم يدوياً */
      } finally {
        setTranslating(false);
      }
    }, 700);
    return () => {
      if (translateTimer.current) clearTimeout(translateTimer.current);
    };
  }, [nameAr]);

  // ملء اسم الأب (ولي الأمر) تلقائياً من الاسم الرباعي: الأب + الجد + اللقب
  useEffect(() => {
    if (guardianTouched) return;
    if (wordCount >= 2) {
      setGuardianName(nameWords.slice(1).join(" "));
    } else {
      setGuardianName("");
    }
  }, [nameAr, guardianTouched]);

  // فحص تطابق الاسم أثناء الكتابة
  useEffect(() => {
    if (nameCheckTimer.current) clearTimeout(nameCheckTimer.current);
    const name = nameAr.trim().replace(/\s+/g, " ");
    if (name.length < 3 || wordCount < 2) {
      setNameMatches([]);
      return;
    }
    nameCheckTimer.current = setTimeout(async () => {
      try {
        const data = await apiFetch<{ matches: NameMatch[] }>(
          `/api/students/check-name?name=${encodeURIComponent(name)}`
        );
        setNameMatches(data.matches || []);
      } catch {
        setNameMatches([]);
      }
    }, 400);
    return () => {
      if (nameCheckTimer.current) clearTimeout(nameCheckTimer.current);
    };
  }, [nameAr]);

  useEffect(() => {
    setAllowDuplicate(false);
  }, [nameMatches.length]);

  // معاينة الكود التلقائي حسب المرحلة
  const fetchCodePreview = useCallback(async (g: string) => {
    if (!g || !canRegister) return;
    try {
      const data = await apiFetch<{ code: string }>(`/api/student-code-preview?grade=${encodeURIComponent(g)}`);
      setCodePreview(data.code);
    } catch {
      setCodePreview("");
    }
  }, [canRegister]);

  useEffect(() => {
    fetchCodePreview(grade);
  }, [grade, fetchCodePreview]);

  // البحث عن الطلاب
  const runSearch = useCallback(async (q: string) => {
    setLoading(true);
    try {
      const data = await apiFetch<{ students: StudentWithStatus[] }>(
        `/api/students?limit=60&q=${encodeURIComponent(q)}`
      );
      setResults(data.students);
    } catch {
      setResults([]);
    } finally {
      setLoading(false);
    }
  }, []);

  async function confirmDeleteStudent() {
    if (!deleteStudent) return;
    setDeletingStudent(true);
    try {
      await apiFetch(`/api/students/${deleteStudent.id}`, { method: "DELETE" });
      toast({ title: "تم حذف الطالب", description: "تبقت أقساطه وسجلاته محفوظة باسمه" });
      setDeleteStudent(null);
      onStudentsChanged();
      runSearch(query);
    } catch (err) {
      toast({ title: "فشل الحذف", description: err instanceof Error ? err.message : "", variant: "destructive" });
    } finally {
      setDeletingStudent(false);
    }
  }

  useEffect(() => {
    const t = setTimeout(() => runSearch(query), 300);
    return () => clearTimeout(t);
  }, [query, runSearch]);

  // ===== تصدير واستيراد الطلبة =====
  async function downloadFile(url: string, fallbackName: string) {
    const res = await fetch(url);
    if (!res.ok) {
      const data = await res.json().catch(() => ({}));
      throw new Error((data as { error?: string }).error || "فشل تحميل الملف");
    }
    const blob = await res.blob();
    const dispo = res.headers.get("Content-Disposition") || "";
    const m = dispo.match(/filename="?([^";]+)"?/);
    const a = document.createElement("a");
    a.href = URL.createObjectURL(blob);
    a.download = m?.[1] || fallbackName;
    document.body.appendChild(a);
    a.click();
    a.remove();
    setTimeout(() => URL.revokeObjectURL(a.href), 5000);
  }

  async function handleExportStudents() {
    setExporting(true);
    try {
      await downloadFile("/api/students/export", "students.xlsx");
      toast({ title: "تم تصدير الطلبة", description: "نزّل ملف Excel من مجلد التنزيلات" });
    } catch (err) {
      toast({ title: "فشل التصدير", description: err instanceof Error ? err.message : "", variant: "destructive" });
    } finally {
      setExporting(false);
    }
  }

  async function handleDownloadTemplate() {
    try {
      await downloadFile("/api/students/import", "students-import-template.xlsx");
      toast({ title: "تم تحميل القالب", description: "املأ بيانات الطلبة ثم ارفعه للاستيراد" });
    } catch (err) {
      toast({ title: "فشل تحميل القالب", description: err instanceof Error ? err.message : "", variant: "destructive" });
    }
  }

  async function sendImportFile(file: File, mode: "preview" | "commit") {
    const fd = new FormData();
    fd.append("file", file);
    fd.append("mode", mode);
    const res = await fetch("/api/students/import", { method: "POST", body: fd });
    const data = await res.json().catch(() => ({}));
    if (!res.ok) throw new Error((data as { error?: string }).error || "فشل استيراد الملف");
    return data as { totalRows: number; counts: ImportCounts; rows: ImportRowResult[] };
  }

  async function handleImportPreview(file: File) {
    setImportBusy(true);
    try {
      const data = await sendImportFile(file, "preview");
      setImportRows(data.rows);
      setImportCounts(data.counts);
      setImportTotal(data.totalRows);
      setImportStage("preview");
    } catch (err) {
      toast({ title: "فشل فحص الملف", description: err instanceof Error ? err.message : "", variant: "destructive" });
    } finally {
      setImportBusy(false);
    }
  }

  async function confirmImport() {
    if (!importFile) return;
    setImportBusy(true);
    try {
      const data = await sendImportFile(importFile, "commit");
      setImportRows(data.rows);
      setImportCounts(data.counts);
      setImportStage("done");
      toast({ title: `تم استيراد ${data.counts.imported} طالباً بنجاح` });
      onStudentsChanged();
      runSearch(query);
    } catch (err) {
      toast({ title: "فشل الاستيراد", description: err instanceof Error ? err.message : "", variant: "destructive" });
    } finally {
      setImportBusy(false);
    }
  }

  function openImportDialog() {
    setImportStage("select");
    setImportRows([]);
    setImportCounts({ ready: 0, imported: 0, skipped: 0, error: 0 });
    setImportTotal(0);
    setImportFile(null);
    setImportOpen(true);
  }

  function importStatusBadge(st: ImportRowResult["status"]) {
    if (st === "ready") return <Badge variant="secondary">جاهز</Badge>;
    if (st === "imported") return <Badge className="bg-emerald-600 hover:bg-emerald-600">تم</Badge>;
    if (st === "skipped") return <Badge variant="outline" className="text-amber-600 border-amber-300">تجاوز</Badge>;
    return <Badge variant="destructive">خطأ</Badge>;
  }

  // الشعب الافتراضية عند التحميل
  useEffect(() => {
    if (!classroom && classrooms.length > 0) setClassroom(classrooms[0].name);
  }, [classrooms, classroom]);

  async function openDetails(s: StudentWithStatus) {
    setDetailsStudent(s);
    setDetailsOpen(true);
    setDetailsLoading(true);
    try {
      const data = await apiFetch<{ student: StudentWithStatus & { payments: (PaymentDTO & { paidAt: string })[] } }>(
        `/api/students/${s.id}`
      );
      setDetailsStudent({ ...data.student, paymentsList: data.student.payments });
    } catch {
      toast({ title: "تعذر جلب تفاصيل الطالب", variant: "destructive" });
    } finally {
      setDetailsLoading(false);
    }
  }

  function openEdit(s: StudentWithStatus) {
    setEditForm({
      id: s.id,
      studentCode: s.studentCode,
      nameAr: s.nameAr,
      nameEn: s.nameEn,
      grade: s.grade,
      classroom: s.classroom,
      guardianName: s.guardianName,
      guardianPhone: s.guardianPhone,
      discountPercent: String(s.discountPercent ?? 0),
      registeredDate: toLocalDateInput(new Date(s.registeredAt ?? s.createdAt)),
    });
    setEditMatches([]);
    setEditAllowDuplicate(false);
    setEditOpen(true);
  }

  // فحص التطابق عند تعديل الاسم في نافذة التعديل
  useEffect(() => {
    if (!editOpen || !editForm) return;
    const name = editForm.nameAr.trim().replace(/\s+/g, " ");
    if (name.length < 3 || name.split(" ").filter(Boolean).length < 2) {
      setEditMatches([]);
      return;
    }
    const t = setTimeout(async () => {
      try {
        const data = await apiFetch<{ matches: NameMatch[] }>(
          `/api/students/check-name?name=${encodeURIComponent(name)}&excludeId=${editForm.id}`
        );
        setEditMatches(data.matches || []);
      } catch {
        setEditMatches([]);
      }
    }, 400);
    return () => clearTimeout(t);
  }, [editOpen, editForm]);

  async function saveEdit() {
    if (!editForm) return;
    const words = editForm.nameAr.trim().replace(/\s+/g, " ").split(" ").filter(Boolean);
    if (words.length < QUAD_NAME_WORDS) {
      toast({ title: "الاسم الرباعي إجباري", description: "الاسم + الأب + الجد + اللقب", variant: "destructive" });
      return;
    }
    if (editMatches.length > 0 && !editAllowDuplicate) {
      toast({ title: "الاسم مسجل مسبقاً", description: "فعّل خيار السماح بالتكرار إذا كان طالباً مختلفاً", variant: "destructive" });
      return;
    }
    const discount = Number(editForm.discountPercent || 0);
    if (isNaN(discount) || discount < 0 || discount > 100) {
      toast({ title: "نسبة الخصم غير صالحة", description: "بين 0 و 100", variant: "destructive" });
      return;
    }
    if (!editForm.registeredDate) {
      toast({ title: "تاريخ التسجيل مطلوب", description: "حدد تاريخ التسجيل الفعلي للطالب", variant: "destructive" });
      return;
    }
    setEditSaving(true);
    try {
      await apiFetch(`/api/students/${editForm.id}`, {
        method: "PATCH",
        body: JSON.stringify({
          nameAr: editForm.nameAr.trim().replace(/\s+/g, " "),
          nameEn: editForm.nameEn.trim(),
          grade: editForm.grade,
          classroom: editForm.classroom,
          guardianName: editForm.guardianName.trim(),
          guardianPhone: editForm.guardianPhone.trim(),
          discountPercent: discount,
          registeredAt: new Date(`${editForm.registeredDate}T12:00:00`).toISOString(),
          allowDuplicate: editAllowDuplicate,
        }),
      });
      toast({ title: "تم تعديل بيانات الطالب بنجاح" });
      setEditOpen(false);
      setEditForm(null);
      onStudentsChanged();
      runSearch(query);
    } catch (err) {
      toast({ title: "فشل التعديل", description: err instanceof Error ? err.message : "", variant: "destructive" });
    } finally {
      setEditSaving(false);
    }
  }

  async function registerStudent(e: React.FormEvent) {
    e.preventDefault();
    if (!canRegister) return;
    if (!quadComplete) {
      toast({
        title: "الاسم الرباعي إجباري",
        description: `أدخل الاسم بصيغة: الاسم + الأب + الجد + اللقب (${wordCount} كلمات فقط)`,
        variant: "destructive",
      });
      return;
    }
    if (nameMatches.length > 0 && !allowDuplicate) {
      toast({ title: "الاسم مسجل مسبقاً", description: "راجع تنبيه التطابق أعلى النموذج", variant: "destructive" });
      return;
    }
    if (nameEn.trim().length < 3) {
      toast({ title: "الاسم الإنجليزي مطلوب", description: "انتظر الترجمة التلقائية أو اكتبه يدوياً", variant: "destructive" });
      return;
    }
    if (!grade || !classroom) {
      toast({ title: "بيانات ناقصة", description: "اختر الصف الدراسي والشعبة", variant: "destructive" });
      return;
    }
    if (guardianName.trim().length < 3 || guardianPhone.trim().length < 7) {
      toast({ title: "بيانات ولي الأمر ناقصة", description: "أدخل اسم ولي الأمر ورقم هاتفه", variant: "destructive" });
      return;
    }
    const fee = Number(totalFee);
    if (!fee || fee <= 0) {
      toast({ title: "القسط الكلي غير صالح", description: "أدخل مبلغ القسط الكلي الإجمالي", variant: "destructive" });
      return;
    }
    const discount = Number(discountPercent || 0);
    if (isNaN(discount) || discount < 0 || discount > 100) {
      toast({ title: "نسبة الخصم غير صالحة", description: "أدخل نسبة بين 0 و 100", variant: "destructive" });
      return;
    }
    if (!registeredDate) {
      toast({ title: "تاريخ التسجيل مطلوب", description: "حدد تاريخ التسجيل الفعلي (مثل تاريخ شهر آب)", variant: "destructive" });
      return;
    }
    setSubmitting(true);
    try {
      const now = new Date();
      const hh = String(now.getHours()).padStart(2, "0");
      const mm = String(now.getMinutes()).padStart(2, "0");
      const data = await apiFetch<{ student: { id: string; nameAr: string; studentCode: string } }>("/api/students", {
        method: "POST",
        body: JSON.stringify({
          nameAr: nameAr.trim().replace(/\s+/g, " "),
          nameEn: nameEn.trim(),
          grade,
          classroom,
          guardianName: guardianName.trim(),
          guardianPhone: guardianPhone.trim(),
          guardianAddress: guardianAddress.trim() || undefined,
          totalFee: fee,
          discountPercent: discount,
          registeredAt: new Date(`${registeredDate}T${hh}:${mm}`).toISOString(),
          notes: notes.trim() || undefined,
          allowDuplicate,
        }),
      });
      setSuccessDialog({ nameAr: data.student.nameAr, code: data.student.studentCode });
      setNameAr("");
      setNameEn("");
      setGrade("");
      setClassroom(classrooms[0]?.name ?? "");
      setGuardianName("");
      setGuardianTouched(false);
      setGuardianPhone("");
      setGuardianAddress("");
      setTotalFee("");
      setDiscountPercent("");
      setRegisteredDate(todayISO());
      setNotes("");
      setAllowDuplicate(false);
      setNameMatches([]);
      lastTranslated.current = "";
      onStudentsChanged();
      runSearch(query);
      reload();
    } catch (err) {
      toast({ title: "فشل تسجيل الطالب", description: err instanceof Error ? err.message : "", variant: "destructive" });
    } finally {
      setSubmitting(false);
    }
  }

  const discountNum = Number(discountPercent || 0);
  const feeNum = Number(totalFee || 0);
  const netFee = effectiveFee(feeNum, discountNum);

  return (
    <div className="space-y-5">
      <div className="grid gap-5 lg:grid-cols-[420px_1fr] items-start">
        {/* نموذج التسجيل */}
        {canRegister ? (
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-lg flex items-center gap-2">
                <UserPlus className="w-5 h-5 text-primary" />
                تسجيل طالب جديد
              </CardTitle>
              <CardDescription>الاسم الرباعي إجباري واسم ولي الأمر يُملأ تلقائياً منه</CardDescription>
            </CardHeader>
            <CardContent>
              <form onSubmit={registerStudent} className="space-y-4">
                {/* تنبيه تطابق الاسم */}
                {nameMatches.length > 0 && (
                  <div className="rounded-xl border-2 border-red-400 bg-red-50 p-3 space-y-2">
                    <div className="flex items-start gap-2 text-red-800">
                      <CircleAlert className="w-5 h-5 shrink-0 mt-0.5" />
                      <div className="space-y-1 text-sm">
                        <p className="font-bold">تنبيه: هذا الاسم مسجل مسبقاً في النظام!</p>
                        {nameMatches.map((m) => (
                          <p key={m.id} className="text-xs">
                            الطالب: <span className="font-semibold">{m.nameAr}</span> — كود{" "}
                            <span dir="ltr">{m.studentCode}</span> — {gradeLabel(m.grade, customLabels)} / شعبة {m.classroom}
                          </p>
                        ))}
                      </div>
                    </div>
                    <label className="flex items-start gap-2 text-xs text-red-900 bg-white/70 rounded-lg p-2 cursor-pointer">
                      <Checkbox checked={allowDuplicate} onCheckedChange={(v) => setAllowDuplicate(v === true)} />
                      <span>هذا طالب مختلف (من عائلة أخرى بنفس الاسم) — اسمح بالتسجيل بنفس الاسم</span>
                    </label>
                  </div>
                )}

                <div className="space-y-2">
                  <Label htmlFor="nameAr">
                    الاسم الرباعي للطالب بالعربية <span className="text-destructive">*</span>
                    <span className="text-[11px] font-normal text-muted-foreground"> (الاسم + الأب + الجد + اللقب)</span>
                  </Label>
                  <Input
                    id="nameAr"
                    placeholder="مثال: محمد علي حسن محمود"
                    value={nameAr}
                    onChange={(e) => setNameAr(e.target.value)}
                    required
                    className={cn("h-12 text-base font-semibold", wordCount > 0 && !quadComplete && "border-amber-400 focus-visible:ring-amber-400", quadComplete && nameMatches.length === 0 && "border-emerald-500 focus-visible:ring-emerald-500")}
                  />
                  {/* تفكيك أجزاء الاسم */}
                  <div className="flex gap-1.5 flex-wrap">
                    {NAME_PART_LABELS.map((label, i) => (
                      <span
                        key={label}
                        className={cn(
                          "rounded-lg border px-2 py-1 text-[11px] transition-colors",
                          nameWords[i]
                            ? "border-emerald-300 bg-emerald-50 text-emerald-800"
                            : "border-dashed border-muted-foreground/40 text-muted-foreground"
                        )}
                      >
                        <span className="font-semibold">{label}:</span>{" "}
                        {nameWords[i] ?? "—"}
                      </span>
                    ))}
                    {wordCount > QUAD_NAME_WORDS && (
                      <span className="rounded-lg border border-amber-300 bg-amber-50 px-2 py-1 text-[11px] text-amber-800">
                        + {wordCount - QUAD_NAME_WORDS} كلمات إضافية
                      </span>
                    )}
                  </div>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="nameEn" className="flex items-center gap-1">
                    الاسم بالإنجليزية
                    {translating ? <Loader2 className="w-3.5 h-3.5 animate-spin text-primary" /> : <Languages className="w-3.5 h-3.5 text-emerald-600" />}
                  </Label>
                  <Input
                    id="nameEn"
                    placeholder="Mohammed Ali Hassan Mahmoud"
                    value={nameEn}
                    onChange={(e) => setNameEn(e.target.value)}
                    dir="ltr"
                    className="text-left"
                  />
                  <p className="text-[11px] text-muted-foreground flex items-center gap-1">
                    <Wand2 className="w-3 h-3" />
                    تُترجم تلقائياً عند كتابة الاسم العربي
                  </p>
                </div>

                <div className="rounded-xl border border-dashed bg-muted/40 p-3 flex items-center justify-between gap-2">
                  <div>
                    <p className="text-xs text-muted-foreground">الكود التلقائي المتوقع للطالب (Auto Student ID)</p>
                    <p className="font-bold text-lg tracking-wide" dir="ltr">{codePreview || "— اختر الصف أولاً —"}</p>
                  </div>
                  <Badge variant="outline" className="shrink-0">{new Date().getFullYear()}</Badge>
                </div>

                <div className="grid gap-3 sm:grid-cols-2">
                  <div className="space-y-2">
                    <Label>
                      الصف الدراسي <span className="text-destructive">*</span>
                    </Label>
                    <Select value={grade} onValueChange={setGrade}>
                      <SelectTrigger><SelectValue placeholder="اختر الصف" /></SelectTrigger>
                      <SelectContent className="max-h-72">
                        {grades.map((g) => (
                          <SelectItem key={g.code} value={g.code}>{g.labelAr}</SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                  <div className="space-y-2">
                    <Label>
                      الشعبة <span className="text-destructive">*</span>
                    </Label>
                    <Select value={classroom} onValueChange={setClassroom}>
                      <SelectTrigger><SelectValue placeholder="اختر الشعبة" /></SelectTrigger>
                      <SelectContent>
                        {classrooms.map((c) => (
                          <SelectItem key={c.id} value={c.name}>شعبة {c.name}</SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                <div className="grid gap-3 sm:grid-cols-2">
                  <div className="space-y-2">
                    <Label htmlFor="guardian" className="flex items-center gap-1">
                      اسم ولي الأمر (الأب) <span className="text-destructive">*</span>
                      {guardianTouched && (
                        <button
                          type="button"
                          className="text-[10px] text-primary hover:underline flex items-center gap-0.5"
                          onClick={() => setGuardianTouched(false)}
                        >
                          <RotateCcw className="w-3 h-3" />
                          إعادة الملء التلقائي
                        </button>
                      )}
                    </Label>
                    <Input
                      id="guardian"
                      placeholder="يُملأ تلقائياً من الاسم الرباعي"
                      value={guardianName}
                      onChange={(e) => {
                        setGuardianName(e.target.value);
                        setGuardianTouched(true);
                      }}
                      required
                      className={cn(!guardianTouched && guardianName && "bg-emerald-50/60")}
                    />
                    <p className="text-[11px] text-muted-foreground">
                      {guardianTouched ? "تم التعديل اليدوي — لن يُستبدل تلقائياً" : "يُملأ تلقائياً (الأب + الجد + اللقب) ويمكن تعديله"}
                    </p>
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="phone">
                      هاتف ولي الأمر <span className="text-destructive">*</span>
                    </Label>
                    <Input id="phone" placeholder="07XX XXX XXXX" value={guardianPhone} onChange={(e) => setGuardianPhone(e.target.value)} dir="ltr" className="text-left" required />
                  </div>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="address">عنوان السكن (اختياري)</Label>
                  <Input id="address" value={guardianAddress} onChange={(e) => setGuardianAddress(e.target.value)} />
                </div>

                <div className="grid gap-3 sm:grid-cols-2">
                  <div className="space-y-2">
                    <Label htmlFor="fee">
                      القسط الكلي الإجمالي ({currency}) <span className="text-destructive">*</span>
                    </Label>
                    <Input id="fee" type="number" min={0} value={totalFee} onChange={(e) => setTotalFee(e.target.value)} className="font-bold" required />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="discount" className="flex items-center gap-1">
                      <Percent className="w-3.5 h-3.5 text-primary" />
                      نسبة الخصم (اختياري)
                    </Label>
                    <Input
                      id="discount"
                      type="number"
                      min={0}
                      max={100}
                      value={discountPercent}
                      onChange={(e) => setDiscountPercent(e.target.value)}
                      placeholder="0 - 100"
                    />
                  </div>
                </div>

                {/* ملخص القسط بعد الخصم */}
                {feeNum > 0 && (
                  <div className="rounded-xl border bg-primary/5 p-3 text-sm space-y-1">
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">القسط الكلي قبل الخصم</span>
                      <span>{formatMoney(feeNum, currency)}</span>
                    </div>
                    {discountNum > 0 && (
                      <div className="flex justify-between text-emerald-700">
                        <span>الخصم ({discountNum}%)</span>
                        <span>- {formatMoney(feeNum - netFee, currency)}</span>
                      </div>
                    )}
                    <div className="flex justify-between border-t pt-1 font-bold">
                      <span>الصافي المطلوب سداده</span>
                      <span className="text-primary">{formatMoney(netFee, currency)}</span>
                    </div>
                  </div>
                )}

                <div className="space-y-2 rounded-xl border-2 border-amber-400/70 bg-amber-50/60 p-3">
                  <Label htmlFor="reg-date" className="flex items-center gap-1 font-bold">
                    <CalendarIcon className="w-4 h-4 text-amber-600" />
                    تاريخ التسجيل <span className="text-destructive">*</span>
                  </Label>
                  <Input
                    id="reg-date"
                    type="date"
                    value={registeredDate}
                    max={todayISO()}
                    onChange={(e) => setRegisteredDate(e.target.value)}
                    required
                    className="h-11 font-semibold bg-white"
                  />
                  <p className="text-[11px] text-muted-foreground flex items-center gap-1">
                    <CircleAlert className="w-3.5 h-3.5 shrink-0 text-amber-600" />
                    هذا هو تاريخ التسجيل الفعلي للطالب (مثلاً تاريخ شهر آب) وليس تاريخ استحقاق التسديد — يقسم القسط الصافي على 8 أشهر انطلاقاً منه
                  </p>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="st-notes">ملاحظات (اختياري)</Label>
                  <Textarea id="st-notes" rows={2} value={notes} onChange={(e) => setNotes(e.target.value)} />
                </div>

                <Button type="submit" className="w-full h-12 text-base font-bold" disabled={submitting || !quadComplete}>
                  {submitting ? <Loader2 className="w-5 h-5 ml-2 animate-spin" /> : <UserPlus className="w-5 h-5 ml-2" />}
                  {submitting ? "جارٍ التسجيل..." : !quadComplete ? "أكمل الاسم الرباعي أولاً" : "تسجيل الطالب"}
                </Button>
              </form>
            </CardContent>
          </Card>
        ) : (
          <Card>
            <CardContent className="pt-6 text-sm text-muted-foreground flex items-center gap-2">
              <NotebookPen className="w-5 h-5 shrink-0" />
              صلاحية حسابك (محاسب) تسمح بالبحث والاطلاع على بيانات الطلبة فقط — تسجيل الطلبة يتم عبر الموظف الإداري أو المدير.
            </CardContent>
          </Card>
        )}

        {/* قائمة الطلاب */}
        <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="flex flex-wrap items-center gap-2 mb-3">
              <Button variant="outline" size="sm" onClick={handleExportStudents} disabled={exporting}>
                {exporting ? <Loader2 className="w-4 h-4 ml-1 animate-spin" /> : <Download className="w-4 h-4 ml-1" />}
                تصدير الطلبة
              </Button>
              {canRegister && (
                <Button variant="outline" size="sm" onClick={openImportDialog}>
                  <Upload className="w-4 h-4 ml-1" />
                  استيراد طلبة
                </Button>
              )}
              <span className="text-xs text-muted-foreground">ملف Excel بأسماء الطلبة وأقساطهم</span>
            </div>
            <div className="relative mb-3">
              <Search className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
              <Input className="pr-9 h-11" placeholder="بحث سريع..." value={query} onChange={(e) => setQuery(e.target.value)} aria-label="بحث في الطلاب" />
              {loading && <Loader2 className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 animate-spin text-primary" />}
            </div>
            <div className="grid gap-2 max-h-[560px] overflow-y-auto">
              {results.map((s) => (
                <div
                  key={s.id}
                  className="flex flex-wrap items-center justify-between gap-2 rounded-xl border p-3 hover:bg-accent/50 transition-colors"
                >
                  <button onClick={() => openDetails(s)} className="flex items-center gap-3 min-w-0 flex-1 text-right">
                    <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>
                      <p className="text-[11px] text-muted-foreground">
                        {gradeLabel(s.grade, customLabels)} / شعبة {s.classroom}
                      </p>
                    </div>
                  </button>
                  <div className="shrink-0 flex items-center gap-2">
                    <div>
                      <Badge variant={s.remaining > 0 ? "destructive" : "secondary"}>
                        {s.remaining > 0 ? `متبقي ${formatMoney(s.remaining, currency)}` : "مكتفي"}
                      </Badge>
                      {(s.discountPercent ?? 0) > 0 && (
                        <p className="text-[10px] text-emerald-700 mt-1">خصم {s.discountPercent}%</p>
                      )}
                    </div>
                    {canRegister && (
                      <Button variant="ghost" size="icon" className="h-8 w-8 shrink-0" onClick={() => openEdit(s)} aria-label={`تعديل بيانات ${s.nameAr}`}>
                        <Pencil className="w-4 h-4" />
                      </Button>
                    )}
                    <Button variant="ghost" size="icon" className="h-8 w-8 shrink-0" onClick={() => { setStatementStudentId(s.id); setStatementOpen(true); }} aria-label={`كشف حساب ${s.nameAr}`}>
                      <FileText className="w-4 h-4" />
                    </Button>
                    {userRole === "ADMIN" && (
                      <Button variant="ghost" size="icon" className="h-8 w-8 shrink-0 text-destructive" onClick={() => setDeleteStudent(s)} aria-label={`حذف الطالب ${s.nameAr}`}>
                        <Trash2 className="w-4 h-4" />
                      </Button>
                    )}
                    <Eye className="w-4 h-4 text-muted-foreground shrink-0" />
                  </div>
                </div>
              ))}
              {!loading && results.length === 0 && (
                <p className="text-sm text-muted-foreground text-center py-8">لا يوجد طلبة مطابقون</p>
              )}
            </div>
          </CardContent>
        </Card>
      </div>

      {/* حوار نجاح التسجيل */}
      <Dialog open={!!successDialog} onOpenChange={(o) => !o && setSuccessDialog(null)}>
        <DialogContent className="sm:max-w-sm">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2 text-emerald-700">
              <CheckCircle2 className="w-5 h-5" />
              تم تسجيل الطالب بنجاح
            </DialogTitle>
            <DialogDescription>أُنشئ كود مميز تلقائياً للطالب حسب صفه وسنة التسجيل</DialogDescription>
          </DialogHeader>
          <div className="rounded-xl border bg-muted/40 p-4 text-center">
            <p className="text-sm text-muted-foreground mb-1">{successDialog?.nameAr}</p>
            <p className="text-2xl font-extrabold tracking-wider" dir="ltr">{successDialog?.code}</p>
          </div>
          <div className="flex gap-2">
            <Button className="flex-1" onClick={() => setSuccessDialog(null)}>تسجيل طالب آخر</Button>
          </div>
        </DialogContent>
      </Dialog>

      {/* حوار تفاصيل الطالب */}
      <Dialog open={detailsOpen} onOpenChange={setDetailsOpen}>
        <DialogContent className="sm:max-w-2xl max-h-[85vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{detailsStudent?.nameAr}</DialogTitle>
            <DialogDescription dir="ltr">{detailsStudent?.nameEn} · #{detailsStudent?.studentCode}</DialogDescription>
          </DialogHeader>
          {detailsStudent && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 sm:grid-cols-4 gap-2 text-sm">
                <div className="rounded-lg border p-2">
                  <p className="text-[11px] text-muted-foreground">الصف</p>
                  <p className="font-semibold">{gradeLabel(detailsStudent.grade, customLabels)}</p>
                </div>
                <div className="rounded-lg border p-2">
                  <p className="text-[11px] text-muted-foreground">الشعبة</p>
                  <p className="font-semibold">{detailsStudent.classroom}</p>
                </div>
                <div className="rounded-lg border p-2">
                  <p className="text-[11px] text-muted-foreground">ولي الأمر</p>
                  <p className="font-semibold truncate">{detailsStudent.guardianName}</p>
                </div>
                <div className="rounded-lg border p-2">
                  <p className="text-[11px] text-muted-foreground">الهاتف</p>
                  <p className="font-semibold" dir="ltr">{detailsStudent.guardianPhone}</p>
                </div>
              </div>
              <div className="grid grid-cols-2 sm:grid-cols-4 gap-2 text-center">
                <div className="rounded-lg bg-muted p-2 text-sm">
                  <p className="text-[11px] text-muted-foreground">القسط الكلي</p>
                  <p className="font-bold">{formatMoney(detailsStudent.totalFee, currency)}</p>
                </div>
                {(detailsStudent.discountPercent ?? 0) > 0 && (
                  <div className="rounded-lg bg-emerald-50 p-2 text-sm">
                    <p className="text-[11px] text-muted-foreground">الخصم</p>
                    <p className="font-bold text-emerald-700">{detailsStudent.discountPercent}%</p>
                  </div>
                )}
                <div className="rounded-lg bg-primary/10 p-2 text-sm">
                  <p className="text-[11px] text-muted-foreground">المسدد</p>
                  <p className="font-bold text-primary">{formatMoney(detailsStudent.paid, currency)}</p>
                </div>
                <div className="rounded-lg bg-destructive/10 p-2 text-sm">
                  <p className="text-[11px] text-muted-foreground">المتبقي</p>
                  <p className="font-bold text-destructive">{formatMoney(detailsStudent.remaining, currency)}</p>
                </div>
              </div>

              <p className="text-xs text-muted-foreground flex items-center gap-1 flex-wrap">
                <CalendarIcon className="w-3.5 h-3.5" />
                تاريخ التسجيل:
                <span className="font-bold text-foreground">{formatDate(detailsStudent.registeredAt || detailsStudent.createdAt)}</span>
                <span className="text-[10px]">(أساس حساب تقسيط الـ 8 أشهر)</span>
              </p>

              <div>
                <p className="text-sm font-semibold mb-2 flex items-center gap-1">
                  سجل المدفوعات ({detailsStudent.paymentsList?.length ?? 0})
                </p>
                {detailsLoading ? (
                  <div className="flex justify-center py-6"><Loader2 className="w-6 h-6 animate-spin text-primary" /></div>
                ) : (detailsStudent.paymentsList?.length ?? 0) > 0 ? (
                  <div className="space-y-1.5 max-h-60 overflow-y-auto">
                    {detailsStudent.paymentsList!.map((p) => (
                      <div key={p.id} className="flex items-center justify-between rounded-lg border px-3 py-2 text-sm">
                        <div className="min-w-0">
                          <p className="font-medium truncate">وصل #{p.receiptNumber} — {p.installmentType}</p>
                          <p className="text-[11px] text-muted-foreground">
                            {formatDate(p.paidAt)} · {p.method === "CASH" ? "نقدي" : "إلكتروني"} · بواسطة {p.creator?.fullName ?? "-"}
                          </p>
                        </div>
                        <span className="font-bold text-primary shrink-0">{formatMoney(p.amount, currency)}</span>
                      </div>
                    ))}
                  </div>
                ) : (
                  <p className="text-xs text-muted-foreground py-3 text-center border rounded-lg">لا توجد مدفوعات مسجلة بعد</p>
                )}
              </div>

              <div className="flex gap-2">
                {canRegister && (
                  <Button
                    variant="outline"
                    className="flex-1"
                    onClick={() => {
                      setDetailsOpen(false);
                      openEdit(detailsStudent);
                    }}
                  >
                    <Pencil className="w-4 h-4 ml-2" />
                    تعديل البيانات
                  </Button>
                )}
                <Button
                  variant="outline"
                  className="flex-1"
                  onClick={() => {
                    setDetailsOpen(false);
                    setStatementStudentId(detailsStudent.id);
                    setStatementOpen(true);
                  }}
                >
                  <FileText className="w-4 h-4 ml-2" />
                  كشف الحساب التراكمي
                </Button>
                {userRole === "ADMIN" || userRole === "ACCOUNTANT" ? (
                  <Button
                    className="flex-1"
                    onClick={() => {
                      setDetailsOpen(false);
                      onGoPayment(detailsStudent.id);
                    }}
                  >
                    الانتقال لاستلام قسط لهذا الطالب
                  </Button>
                ) : null}
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* حوار تعديل الطالب */}
      <Dialog open={editOpen} onOpenChange={(o) => { if (!o) { setEditOpen(false); setEditForm(null); } }}>
        <DialogContent className="sm:max-w-lg max-h-[85vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Pencil className="w-5 h-5 text-primary" />
              تعديل بيانات الطالب
            </DialogTitle>
            <DialogDescription>
              لإصلاح خطأ في الاسم أو البيانات — كود الطالب{" "}
              <span dir="ltr" className="font-bold">{editForm?.studentCode}</span> لا يتغير
            </DialogDescription>
          </DialogHeader>
          {editForm && (
            <div className="space-y-3">
              {editMatches.length > 0 && (
                <div className="rounded-xl border-2 border-red-400 bg-red-50 p-3 text-sm text-red-800 space-y-1">
                  <p className="font-bold flex items-center gap-1">
                    <CircleAlert className="w-4 h-4" />
                    الاسم مسجل مسبقاً لطالب آخر:
                  </p>
                  {editMatches.map((m) => (
                    <p key={m.id} className="text-xs">
                      {m.nameAr} — <span dir="ltr">{m.studentCode}</span> — {gradeLabel(m.grade, customLabels)} / شعبة {m.classroom}
                    </p>
                  ))}
                  <label className="flex items-start gap-2 text-xs bg-white/70 rounded-lg p-2 cursor-pointer">
                    <Checkbox checked={editAllowDuplicate} onCheckedChange={(v) => setEditAllowDuplicate(v === true)} />
                    <span>طالب مختلف — اسمح بحفظ نفس الاسم</span>
                  </label>
                </div>
              )}
              <div className="space-y-2">
                <Label>الاسم الرباعي بالعربية *</Label>
                <Input
                  value={editForm.nameAr}
                  onChange={(e) => setEditForm({ ...editForm, nameAr: e.target.value })}
                  className="h-11 font-semibold"
                />
                <p className={cn("text-[11px]", editForm.nameAr.trim().split(/\s+/).filter(Boolean).length >= 4 ? "text-emerald-700" : "text-amber-700")}>
                  {editForm.nameAr.trim().split(/\s+/).filter(Boolean).length} / 4 كلمات (الاسم + الأب + الجد + اللقب)
                </p>
              </div>
              <div className="space-y-2">
                <Label>الاسم بالإنجليزية</Label>
                <Input
                  value={editForm.nameEn}
                  onChange={(e) => setEditForm({ ...editForm, nameEn: e.target.value })}
                  dir="ltr"
                  className="text-left"
                />
              </div>
              <div className="grid gap-3 sm:grid-cols-2">
                <div className="space-y-2">
                  <Label>الصف</Label>
                  <Select value={editForm.grade} onValueChange={(v) => setEditForm({ ...editForm, grade: v })}>
                    <SelectTrigger><SelectValue /></SelectTrigger>
                    <SelectContent className="max-h-72">
                      {grades.map((g) => (
                        <SelectItem key={g.code} value={g.code}>{g.labelAr}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-2">
                  <Label>الشعبة</Label>
                  <Select value={editForm.classroom} onValueChange={(v) => setEditForm({ ...editForm, classroom: v })}>
                    <SelectTrigger><SelectValue /></SelectTrigger>
                    <SelectContent>
                      {classrooms.map((c) => (
                        <SelectItem key={c.id} value={c.name}>شعبة {c.name}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>
              <div className="grid gap-3 sm:grid-cols-2">
                <div className="space-y-2">
                  <Label>اسم ولي الأمر (الأب)</Label>
                  <Input value={editForm.guardianName} onChange={(e) => setEditForm({ ...editForm, guardianName: e.target.value })} />
                </div>
                <div className="space-y-2">
                  <Label>هاتف ولي الأمر</Label>
                  <Input value={editForm.guardianPhone} onChange={(e) => setEditForm({ ...editForm, guardianPhone: e.target.value })} dir="ltr" className="text-left" />
                </div>
              </div>
              <div className="space-y-2">
                <Label>نسبة الخصم (%)</Label>
                <Input
                  type="number" min={0} max={100}
                  value={editForm.discountPercent}
                  onChange={(e) => setEditForm({ ...editForm, discountPercent: e.target.value })}
                />
              </div>
              <div className="space-y-2">
                <Label>تاريخ التسجيل *</Label>
                <Input
                  type="date"
                  value={editForm.registeredDate}
                  max={todayISO()}
                  onChange={(e) => setEditForm({ ...editForm, registeredDate: e.target.value })}
                  className="font-semibold bg-amber-50/50"
                  required
                />
                <p className="text-[11px] text-muted-foreground">
                  صحيح تاريخ التسجيل الفعلي إذا سُجّل الطالب بتاريخ خاطئ — يؤثر على حساب المستحق
                </p>
              </div>
              <div className="flex gap-2">
                <Button className="flex-1" onClick={saveEdit} disabled={editSaving}>
                  {editSaving ? <Loader2 className="w-4 h-4 ml-1 animate-spin" /> : null}
                  حفظ التعديلات
                </Button>
                <Button variant="outline" onClick={() => { setEditOpen(false); setEditForm(null); }}>إلغاء</Button>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* تأكيد حذف طالب */}
      <AlertDialog open={!!deleteStudent} onOpenChange={(o) => !o && setDeleteStudent(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>حذف الطالب {deleteStudent?.nameAr}؟</AlertDialogTitle>
            <AlertDialogDescription>
              سيُحذف الطالب من قوائم النظام (كود {deleteStudent?.studentCode}). تبقت أقساطه المسجلة وسجلاته
              محفوظة باسمه في التقارير والسجل الأمني لحفظ صحة الحسابات. هل أنت متأكد من الحذف؟
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>إلغاء</AlertDialogCancel>
            <AlertDialogAction
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
              onClick={(e) => { e.preventDefault(); confirmDeleteStudent(); }}
              disabled={deletingStudent}
            >
              {deletingStudent && <Loader2 className="w-4 h-4 ml-2 animate-spin" />}
              نعم، حذف الطالب
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* استيراد طلبة من ملف Excel */}
      <Dialog open={importOpen} onOpenChange={(o) => !o && setImportOpen(false)}>
        <DialogContent className="sm:max-w-2xl max-h-[85vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <FileSpreadsheet className="w-5 h-5 text-emerald-700" />
              استيراد طلبة من ملف Excel
            </DialogTitle>
            <DialogDescription>
              فحص الملف أولاً ثم تأكيد الاستيراد — الأسماء المكررة تُتجاوز تلقائياً
            </DialogDescription>
          </DialogHeader>

          {importStage === "select" && (
            <div className="space-y-4">
              <div className="rounded-xl border-2 border-dashed p-4 space-y-2">
                <Input
                  type="file"
                  accept=".xlsx,.xls,.csv"
                  onChange={(e) => setImportFile(e.target.files?.[0] ?? null)}
                  className="cursor-pointer"
                />
                {importFile && (
                  <p className="text-xs text-muted-foreground text-center">
                    {importFile.name} — {Math.max(1, Math.round(importFile.size / 1024))} كيلوبايت
                  </p>
                )}
              </div>
              <div className="text-xs text-muted-foreground space-y-1 rounded-xl bg-muted/40 p-3 leading-relaxed">
                <p className="font-semibold text-foreground">شروط الملف:</p>
                <p>• عمود «الاسم» إجباري ورباعي (الاسم + الأب + الجد + اللقب)</p>
                <p>• الصف يُكتب كما يظهر في النظام (مثال: الصف الخامس الابتدائي) والشعبة يجب أن تكون موجودة</p>
                <p>• اسم ولي الأمر وهاتفه إجباريان — والقسط والخصم وتاريخ التسجيل اختيارية</p>
                <p>• إن تُرك الاسم بالإنجليزية فارغاً يُعبأ بالاسم العربي ويمكن تعديله لاحقاً</p>
                <p>• الحد الأقصى 500 صف — والملفات المدعومة: xlsx أو csv</p>
              </div>
              <div className="flex flex-wrap items-center gap-2">
                <Button variant="outline" size="sm" onClick={handleDownloadTemplate}>
                  <Download className="w-4 h-4 ml-1" />
                  تحميل القالب الجاهز
                </Button>
                <div className="flex-1" />
                <Button variant="outline" onClick={() => setImportOpen(false)}>إلغاء</Button>
                <Button onClick={() => importFile && handleImportPreview(importFile)} disabled={!importFile || importBusy}>
                  {importBusy ? <Loader2 className="w-4 h-4 ml-1 animate-spin" /> : <Search className="w-4 h-4 ml-1" />}
                  فحص الملف
                </Button>
              </div>
            </div>
          )}

          {(importStage === "preview" || importStage === "done") && (
            <div className="space-y-3">
              <div className="flex flex-wrap items-center gap-2 text-sm">
                <Badge variant="outline">إجمالي الصفوف: {importTotal}</Badge>
                {importStage === "preview" ? (
                  <Badge variant="secondary">جاهز للاستيراد: {importCounts.ready}</Badge>
                ) : (
                  <Badge className="bg-emerald-600 hover:bg-emerald-600">تم استيراد: {importCounts.imported}</Badge>
                )}
                <Badge variant="outline" className="text-amber-600 border-amber-300">تجاوز مكرر: {importCounts.skipped}</Badge>
                <Badge variant="destructive">أخطاء: {importCounts.error}</Badge>
              </div>

              {importStage === "done" && importCounts.imported > 0 && (
                <div className="flex items-center gap-2 rounded-xl bg-emerald-50 border border-emerald-200 p-3 text-sm text-emerald-800">
                  <CheckCircle2 className="w-4 h-4 shrink-0" />
                  تم تسجيل الطلبة الجدد بأكواد تلقائية حسب صفوفهم — ظهروا الآن في قائمة الطلبة
                </div>
              )}

              <div className="rounded-xl border overflow-hidden">
                <div className="max-h-[320px] overflow-y-auto">
                  <table className="w-full text-sm">
                    <thead className="bg-muted/60 sticky top-0">
                      <tr>
                        <th className="p-2 text-right font-semibold w-12">#</th>
                        <th className="p-2 text-right font-semibold">الاسم</th>
                        <th className="p-2 text-right font-semibold">الصف</th>
                        <th className="p-2 text-right font-semibold w-16">الشعبة</th>
                        <th className="p-2 text-right font-semibold w-20">الحالة</th>
                        <th className="p-2 text-right font-semibold">التفاصيل</th>
                      </tr>
                    </thead>
                    <tbody>
                      {importRows.slice(0, 100).map((r) => (
                        <tr key={r.row} className="border-t">
                          <td className="p-2 text-muted-foreground">{r.row}</td>
                          <td className="p-2 font-medium max-w-[180px] truncate">{r.name}</td>
                          <td className="p-2 text-xs text-muted-foreground">{r.grade || "—"}</td>
                          <td className="p-2 text-center text-xs">{r.classroom || "—"}</td>
                          <td className="p-2">{importStatusBadge(r.status)}</td>
                          <td className="p-2 text-xs text-muted-foreground">
                            {r.status === "error" && <span className="flex items-center gap-1 text-destructive"><XCircle className="w-3 h-3 shrink-0" />{r.reason}</span>}
                            {r.status === "skipped" && <span className="flex items-center gap-1 text-amber-600"><AlertTriangle className="w-3 h-3 shrink-0" />{r.reason}</span>}
                            {(r.status === "ready" || r.status === "imported") && "—"}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
                {importRows.length > 100 && (
                  <p className="text-xs text-muted-foreground p-2 border-t bg-muted/30 text-center">
                    يُعرض أول 100 صف من {importRows.length}
                  </p>
                )}
              </div>

              <div className="flex flex-wrap items-center gap-2">
                {importStage === "preview" ? (
                  <>
                    <Button variant="outline" onClick={() => setImportStage("select")} disabled={importBusy}>رجوع</Button>
                    <div className="flex-1" />
                    <Button onClick={confirmImport} disabled={importCounts.ready === 0 || importBusy}>
                      {importBusy ? <Loader2 className="w-4 h-4 ml-1 animate-spin" /> : <Upload className="w-4 h-4 ml-1" />}
                      تأكيد استيراد {importCounts.ready} طالب
                    </Button>
                  </>
                ) : (
                  <>
                    <div className="flex-1" />
                    <Button onClick={() => setImportOpen(false)}>إغلاق</Button>
                  </>
                )}
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* كشف الحساب التراكمي للطالب (v8.1) */}
      <StudentStatementDialog
        studentId={statementStudentId}
        open={statementOpen}
        onOpenChange={setStatementOpen}
        gradeLabels={customLabels}
      />
    </div>
  );
}
