"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 { 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 { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useToast } from "@/hooks/use-toast";
import { apiFetch, formatMoney, formatDateTime, toLocalDateInput } from "@/lib/client-utils";
import PayrollView from "@/components/payroll-view";
import SuppliersView from "@/components/suppliers-view";
import { ActivityLoansView } from "@/components/activity-loans-view";
import { EXPENSE_CATEGORIES, INSTALLMENT_TYPES } from "@/lib/constants";
import { EXPENSE_KINDS, EXPENSE_KIND_AR, OTHER_INCOME_KINDS, OTHER_INCOME_KIND_AR, inferExpenseKind } from "@/lib/finance-kinds";
import { PaymentDTO, SchoolSettingsDTO, OtherIncomeDTO } from "@/lib/types";
import { ReceiptPrintTemplate } from "@/components/receipt-template";
import {
  Wallet, TrendingUp, TrendingDown, Loader2, Plus, Paperclip,
  Scale, Trash2, ReceiptText, Download, Eye, FileText, Printer, Pencil,
  Search, PlusCircle, Coins,
} from "lucide-react";

interface ExpenseRow {
  id: string;
  category: string;
  description: string;
  amount: number;
  /** رقم وصل الصرف (v8.1) */
  voucherNumber?: string | null;
  /** البند المالي الموحد (v8.1) */
  kind?: string;
  kindLabel?: string;
  invoiceName?: string | null;
  invoiceData?: string | null;
  spentAt: string;
  createdAt: string;
  creator?: { fullName: string } | null;
}

interface FinanceViewProps {
  settings: SchoolSettingsDTO | null;
  userRole: string;
  refreshKey: number;
  onFinanceChanged: () => void;
}

export default function FinanceView({ settings, userRole, refreshKey, onFinanceChanged }: FinanceViewProps) {
  const { toast } = useToast();
  const currency = settings?.currency || "د.ع";
  const isAdmin = userRole === "ADMIN" || userRole === "SUPER_ADMIN";
  const canManageReceipts = isAdmin || userRole === "ACCOUNTANT";

  const [tab, setTab] = useState("expenses");
  const [expenses, setExpenses] = useState<ExpenseRow[]>([]);
  const [payments, setPayments] = useState<PaymentDTO[]>([]);
  const [summary, setSummary] = useState({ totalIncome: 0, studentIncome: 0, otherIncome: 0, totalExpenses: 0, netBalance: 0 });
  const [loading, setLoading] = useState(true);

  // نموذج مصروف
  const [category, setCategory] = useState(EXPENSE_CATEGORIES[0]);
  const [description, setDescription] = useState("");
  const [amount, setAmount] = useState("");
  // v8.1: بند المصروف المالي الموحد + رقم وصل الصرف (اختياري — يولد تلقائياً إذا ترك فارغاً)
  const [expKind, setExpKind] = useState("OTHER");
  const [expVoucher, setExpVoucher] = useState("");
  const [invoice, setInvoice] = useState<{ name: string; data: string } | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const fileRef = useRef<HTMLInputElement>(null);

  const [invoiceView, setInvoiceView] = useState<null | { name: string; data: string }>(null);
  // طباعة وصل من الإيرادات المسجلة
  const [receiptPrint, setReceiptPrint] = useState<PaymentDTO | null>(null);

  // تعديل مصروف (مدير فقط)
  const [editExpense, setEditExpense] = useState<ExpenseRow | null>(null);
  const [editExpCategory, setEditExpCategory] = useState("");
  const [editExpDesc, setEditExpDesc] = useState("");
  const [editExpAmount, setEditExpAmount] = useState("");
  const [editExpDate, setEditExpDate] = useState("");
  const [savingExp, setSavingExp] = useState(false);

  // حذف إيراد مسجل — قسط طالب (مدير فقط)
  const [deletePayment, setDeletePayment] = useState<PaymentDTO | null>(null);
  const [deletingPay, setDeletingPay] = useState(false);

  /* ───── بحث الإيرادات (رقم الوصل / اسم الطالب / الكود) ───── */
  const [paymentQuery, setPaymentQuery] = useState("");
  const [filteredPayments, setFilteredPayments] = useState<PaymentDTO[]>([]);
  const [searching, setSearching] = useState(false);

  /* ───── تعديل قسط مسجل (مدير فقط) ───── */
  const [editPayment, setEditPayment] = useState<PaymentDTO | null>(null);
  const [editPayReceiptNumber, setEditPayReceiptNumber] = useState("");
  const [editPayAmount, setEditPayAmount] = useState("");
  const [editPayInstallmentType, setEditPayInstallmentType] = useState("");
  const [editPayMethod, setEditPayMethod] = useState("CASH");
  const [editPayTransactionRef, setEditPayTransactionRef] = useState("");
  const [editPayNotes, setEditPayNotes] = useState("");
  const [savingPay, setSavingPay] = useState(false);

  /* ───── إيرادات أخرى (غير أقساط الطلبة) ───── */
  const [otherIncomes, setOtherIncomes] = useState<OtherIncomeDTO[]>([]);
  const [otherIncomeTotal, setOtherIncomeTotal] = useState(0);
  const [oiDialogOpen, setOiDialogOpen] = useState(false);
  const [editOi, setEditOi] = useState<OtherIncomeDTO | null>(null);
  const [oiSource, setOiSource] = useState("");
  const [oiReason, setOiReason] = useState("");
  // v8.1: بند الإيراد — واردات مدارس أخرى / تسديد سلف منتسبين / تسديد سلف نشاطات / مناقلة / إيرادات خارجية
  const [oiKind, setOiKind] = useState("OTHER");
  const [oiAmount, setOiAmount] = useState("");
  const [oiDate, setOiDate] = useState("");
  const [oiNotes, setOiNotes] = useState("");
  const [savingOi, setSavingOi] = useState(false);
  const [deleteOi, setDeleteOi] = useState<OtherIncomeDTO | null>(null);

  const loadData = useCallback(async () => {
    setLoading(true);
    try {
      const [expData, payData, oiData] = await Promise.all([
        apiFetch<{ expenses: ExpenseRow[]; summary: typeof summary }>("/api/expenses?limit=100"),
        apiFetch<{ payments: PaymentDTO[] }>("/api/payments?limit=200"),
        apiFetch<{ incomes: OtherIncomeDTO[]; total: number }>("/api/other-income?limit=200"),
      ]);
      setExpenses(expData.expenses);
      setSummary(expData.summary);
      setPayments(payData.payments);
      setFilteredPayments(payData.payments);
      setOtherIncomes(oiData.incomes);
      setOtherIncomeTotal(oiData.total);
    } catch (err) {
      toast({ title: "تعذر تحميل البيانات", description: err instanceof Error ? err.message : "", variant: "destructive" });
    } finally {
      setLoading(false);
    }
  }, [toast]);

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

  function handleFileChange(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    if (file.size > 2 * 1024 * 1024) {
      toast({ title: "الملف كبير", description: "الحد الأقصى لحجم الفاتورة 2 ميجابايت", variant: "destructive" });
      return;
    }
    const reader = new FileReader();
    reader.onload = () => {
      setInvoice({ name: file.name, data: reader.result as string });
    };
    reader.readAsDataURL(file);
  }

  async function addExpense(e: React.FormEvent) {
    e.preventDefault();
    if (description.trim().length < 2) {
      toast({ title: "وصف المصروف مطلوب", variant: "destructive" });
      return;
    }
    const amt = Number(amount);
    if (!amt || amt <= 0) {
      toast({ title: "المبلغ غير صالح", variant: "destructive" });
      return;
    }
    setSubmitting(true);
    try {
      await apiFetch("/api/expenses", {
        method: "POST",
        body: JSON.stringify({
          category,
          description: description.trim(),
          amount: amt,
          kind: expKind,
          voucherNumber: expVoucher.trim() || undefined,
          invoiceName: invoice?.name,
          invoiceData: invoice?.data,
        }),
      });
      toast({ title: "تم تسجيل المصروف", description: `${description.trim()} — ${formatMoney(amt, currency)}` });
      setDescription("");
      setAmount("");
      setExpVoucher("");
      setExpKind("OTHER");
      setInvoice(null);
      if (fileRef.current) fileRef.current.value = "";
      onFinanceChanged();
      loadData();
    } catch (err) {
      toast({ title: "فشل تسجيل المصروف", description: err instanceof Error ? err.message : "", variant: "destructive" });
    } finally {
      setSubmitting(false);
    }
  }

  async function deleteExpense(id: string) {
    try {
      await apiFetch(`/api/expenses/${id}`, { method: "DELETE" });
      toast({ title: "تم حذف المصروف" });
      onFinanceChanged();
      loadData();
    } catch (err) {
      toast({ title: "فشل الحذف", description: err instanceof Error ? err.message : "", variant: "destructive" });
    }
  }

  function openEditExpense(ex: ExpenseRow) {
    setEditExpCategory(ex.category);
    setEditExpDesc(ex.description);
    setEditExpAmount(String(ex.amount));
    setEditExpDate(toLocalDateInput(new Date(ex.spentAt)));
    setEditExpense(ex);
  }

  async function saveExpenseEdit(e: React.FormEvent) {
    e.preventDefault();
    if (!editExpense) return;
    if (editExpDesc.trim().length < 2) {
      toast({ title: "وصف المصروف مطلوب", variant: "destructive" });
      return;
    }
    const amt = Number(editExpAmount);
    if (!amt || amt <= 0) {
      toast({ title: "المبلغ غير صالح", variant: "destructive" });
      return;
    }
    setSavingExp(true);
    try {
      await apiFetch(`/api/expenses/${editExpense.id}`, {
        method: "PATCH",
        body: JSON.stringify({ category: editExpCategory, description: editExpDesc.trim(), amount: amt, spentAt: editExpDate }),
      });
      toast({ title: "تم تعديل المصروف" });
      setEditExpense(null);
      onFinanceChanged();
      loadData();
    } catch (err) {
      toast({ title: "فشل التعديل", description: err instanceof Error ? err.message : "", variant: "destructive" });
    } finally {
      setSavingExp(false);
    }
  }

  /* بحث الإيرادات الفوري مع تهدئة — يعمل حتى بعد التحديثات */
  useEffect(() => {
    const q = paymentQuery.trim();
    if (!q) { setFilteredPayments(payments); setSearching(false); return; }
    setSearching(true);
    const t = setTimeout(async () => {
      try {
        const d = await apiFetch<{ payments: PaymentDTO[] }>(`/api/payments?q=${encodeURIComponent(q)}&limit=50`);
        setFilteredPayments(d.payments);
      } catch {
        // عند فشل البحث نفلتر محلياً حتى لا تتعطل الواجهة
        const ql = q.toLowerCase();
        setFilteredPayments(payments.filter((p) =>
          p.receiptNumber.includes(q) ||
          (p.student?.nameAr ?? "").includes(q) ||
          (p.student?.nameEn ?? "").toLowerCase().includes(ql) ||
          (p.student?.studentCode ?? "").includes(q)
        ));
      } finally {
        setSearching(false);
      }
    }, 350);
    return () => clearTimeout(t);
  }, [paymentQuery, payments]);

  function openEditPayment(p: PaymentDTO) {
    setEditPayReceiptNumber(p.receiptNumber);
    setEditPayAmount(String(p.amount));
    setEditPayInstallmentType(p.installmentType);
    setEditPayMethod(p.method);
    setEditPayTransactionRef(p.transactionRef ?? "");
    setEditPayNotes(p.notes ?? "");
    setEditPayment(p);
  }

  async function savePaymentEdit(e: React.FormEvent) {
    e.preventDefault();
    if (!editPayment) return;
    const amt = Number(editPayAmount);
    if (!editPayReceiptNumber.trim()) {
      toast({ title: "رقم الوصل مطلوب", variant: "destructive" });
      return;
    }
    if (!amt || amt <= 0) {
      toast({ title: "المبلغ غير صالح", variant: "destructive" });
      return;
    }
    if (editPayMethod === "ELECTRONIC" && editPayTransactionRef.trim().length < 4) {
      toast({ title: "أدخل مرجع العملية الإلكترونية (4 خانات على الأقل)", variant: "destructive" });
      return;
    }
    setSavingPay(true);
    try {
      await apiFetch(`/api/payments/${editPayment.id}`, {
        method: "PATCH",
        body: JSON.stringify({
          receiptNumber: editPayReceiptNumber.trim(),
          amount: amt,
          installmentType: editPayInstallmentType,
          method: editPayMethod,
          transactionRef: editPayMethod === "ELECTRONIC" ? editPayTransactionRef.trim() : null,
          notes: editPayNotes.trim() || null,
        }),
      });
      toast({ title: "تم تعديل القسط", description: "أُعيد حساب رصيد الطالب تلقائياً" });
      setEditPayment(null);
      onFinanceChanged();
      loadData();
    } catch (err) {
      toast({ title: "فشل تعديل القسط", description: err instanceof Error ? err.message : "", variant: "destructive" });
    } finally {
      setSavingPay(false);
    }
  }

  /* ───── إيرادات أخرى ───── */
  function openOiDialog() {
    setEditOi(null);
    setOiSource("");
    setOiReason("");
    setOiKind("OTHER");
    setOiAmount("");
    setOiDate(toLocalDateInput(new Date()));
    setOiNotes("");
    setOiDialogOpen(true);
  }

  function openOiEdit(oi: OtherIncomeDTO) {
    setEditOi(oi);
    setOiSource(oi.source);
    setOiReason(oi.reason);
    setOiKind((oi as OtherIncomeDTO & { kind?: string }).kind ?? "OTHER");
    setOiAmount(String(oi.amount));
    setOiDate(toLocalDateInput(new Date(oi.receivedAt)));
    setOiNotes(oi.notes ?? "");
    setOiDialogOpen(true);
  }

  async function saveOi(e: React.FormEvent) {
    e.preventDefault();
    if (oiSource.trim().length < 2) {
      toast({ title: "جهة الإيراد مطلوبة", description: "مثال: مجلس القرية، كافتيريا المدرسة، راعٍ كرم", variant: "destructive" });
      return;
    }
    if (oiReason.trim().length < 2) {
      toast({ title: "سبب الإيراد مطلوب", description: "عن ماذا استلمت هذا المبلغ؟", variant: "destructive" });
      return;
    }
    const amt = Number(oiAmount);
    if (!amt || amt <= 0) {
      toast({ title: "المبلغ غير صالح", variant: "destructive" });
      return;
    }
    setSavingOi(true);
    try {
      const payload = JSON.stringify({
        source: oiSource.trim(),
        reason: oiReason.trim(),
        amount: amt,
        kind: oiKind,
        receivedAt: oiDate ? new Date(oiDate).toISOString() : undefined,
        notes: oiNotes.trim() || null,
      });
      if (editOi) {
        await apiFetch(`/api/other-income/${editOi.id}`, { method: "PATCH", body: payload });
        toast({ title: "تم تعديل الإيراد" });
      } else {
        await apiFetch("/api/other-income", { method: "POST", body: payload });
        toast({ title: "تم تسجيل الإيراد", description: `${oiSource.trim()} — ${formatMoney(amt, currency)}` });
      }
      setOiDialogOpen(false);
      onFinanceChanged();
      loadData();
    } catch (err) {
      toast({ title: editOi ? "فشل التعديل" : "فشل التسجيل", description: err instanceof Error ? err.message : "", variant: "destructive" });
    } finally {
      setSavingOi(false);
    }
  }

  async function confirmDeleteOi() {
    if (!deleteOi) return;
    try {
      await apiFetch(`/api/other-income/${deleteOi.id}`, { method: "DELETE" });
      toast({ title: "تم حذف الإيراد" });
      setDeleteOi(null);
      onFinanceChanged();
      loadData();
    } catch (err) {
      toast({ title: "فشل الحذف", description: err instanceof Error ? err.message : "", variant: "destructive" });
    }
  }

  async function confirmDeletePayment() {
    if (!deletePayment) return;
    setDeletingPay(true);
    try {
      await apiFetch(`/api/payments/${deletePayment.id}`, { method: "DELETE" });
      toast({ title: "تم حذف القسط", description: "أُعيد حساب رصيد الطالب تلقائياً" });
      setDeletePayment(null);
      onFinanceChanged();
      loadData();
    } catch (err) {
      toast({ title: "فشل الحذف", description: err instanceof Error ? err.message : "", variant: "destructive" });
    } finally {
      setDeletingPay(false);
    }
  }

  const net = summary.netBalance;

  return (
    <div className="space-y-5">
      {/* حساب الميزانية الفوري */}
      <div className="grid gap-3 sm:grid-cols-3">
        <Card className="border-r-4 border-r-emerald-600">
          <CardContent className="pt-5">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">إجمالي الإيرادات</p>
                <p className="text-2xl font-extrabold text-emerald-700 mt-1">{formatMoney(summary.totalIncome, currency)}</p>
                <p className="text-[11px] text-muted-foreground mt-1">
                  أقساط الطلبة {formatMoney(summary.studentIncome ?? 0, currency)} · إيرادات أخرى {formatMoney(summary.otherIncome ?? 0, currency)}
                </p>
              </div>
              <div className="w-12 h-12 rounded-xl bg-emerald-100 text-emerald-700 flex items-center justify-center">
                <TrendingUp className="w-6 h-6" />
              </div>
            </div>
          </CardContent>
        </Card>
        <Card className="border-r-4 border-r-red-500">
          <CardContent className="pt-5">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">إجمالي المصروفات</p>
                <p className="text-2xl font-extrabold text-red-600 mt-1">{formatMoney(summary.totalExpenses, currency)}</p>
                <p className="text-[11px] text-muted-foreground mt-1">رواتب وأنشطة ومصاريف يومية</p>
              </div>
              <div className="w-12 h-12 rounded-xl bg-red-100 text-red-600 flex items-center justify-center">
                <TrendingDown className="w-6 h-6" />
              </div>
            </div>
          </CardContent>
        </Card>
        <Card className="border-r-4 border-r-amber-500">
          <CardContent className="pt-5">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">الربح الصافي / المتبقي</p>
                <p className={`text-2xl font-extrabold mt-1 ${net >= 0 ? "text-emerald-700" : "text-red-600"}`}>
                  {formatMoney(net, currency)}
                </p>
                <p className="text-[11px] text-muted-foreground mt-1">الإيرادات − المصروفات (تلقائي)</p>
              </div>
              <div className="w-12 h-12 rounded-xl bg-amber-100 text-amber-600 flex items-center justify-center">
                <Scale className="w-6 h-6" />
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      <Tabs value={tab} onValueChange={setTab}>
        <TabsList className="grid w-full grid-cols-2 lg:grid-cols-5">
          <TabsTrigger value="expenses">المصروفات</TabsTrigger>
          <TabsTrigger value="income">الإيرادات المسجلة</TabsTrigger>
          <TabsTrigger value="activity-loans">سلف النشاط</TabsTrigger>
          <TabsTrigger value="payroll">رواتب الموظفين</TabsTrigger>
          <TabsTrigger value="suppliers">الشركات</TabsTrigger>
        </TabsList>

        {/* المصروفات */}
        <TabsContent value="expenses" className="mt-4 space-y-4">
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-lg flex items-center gap-2">
                <Plus className="w-5 h-5 text-primary" />
                إضافة مصروف جديد
              </CardTitle>
              <CardDescription>رواتب، أنشطة، مصاريف يومية — مع إمكانية إرفاق الفاتورة</CardDescription>
            </CardHeader>
            <CardContent>
              <form onSubmit={addExpense} className="grid gap-3 sm:grid-cols-2">
                <div className="space-y-2">
                  <Label>فئة المصروف</Label>
                  <Select value={category} onValueChange={setCategory}>
                    <SelectTrigger><SelectValue /></SelectTrigger>
                    <SelectContent>
                      {EXPENSE_CATEGORIES.map((c) => (
                        <SelectItem key={c} value={c}>{c}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-2">
                  <Label>البند المالي (للتقارير والميزانية)</Label>
                  <Select value={expKind} onValueChange={setExpKind}>
                    <SelectTrigger><SelectValue /></SelectTrigger>
                    <SelectContent>
                      {EXPENSE_KINDS.map((k) => (
                        <SelectItem key={k} value={k}>{EXPENSE_KIND_AR[k]}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-2">
                  <Label htmlFor="exp-amount">المبلغ ({currency})</Label>
                  <Input id="exp-amount" type="number" min={0} value={amount} onChange={(e) => setAmount(e.target.value)} className="font-bold" required />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="exp-voucher">رقم وصل الصرف</Label>
                  <Input
                    id="exp-voucher"
                    value={expVoucher}
                    onChange={(e) => setExpVoucher(e.target.value)}
                    placeholder="اختياري — يُولد تلقائياً SO-XXXX إذا تُرك فارغاً"
                  />
                </div>
                <div className="space-y-2 sm:col-span-2">
                  <Label htmlFor="exp-desc">الوصف</Label>
                  <Input id="exp-desc" value={description} onChange={(e) => setDescription(e.target.value)} placeholder="مثال: رواتب شهر أيلول للهيئة التدريسية" required />
                </div>
                <div className="space-y-2 sm:col-span-2">
                  <Label className="flex items-center gap-1">
                    <Paperclip className="w-3.5 h-3.5" />
                    إرفاق الفاتورة (اختياري - حتى 2MB)
                  </Label>
                  <Input ref={fileRef} type="file" accept="image/*,application/pdf" onChange={handleFileChange} className="file:ml-2" />
                  {invoice && (
                    <p className="text-xs text-emerald-700 flex items-center gap-1">
                      <FileText className="w-3.5 h-3.5" />
                      {invoice.name}
                      <button type="button" className="text-destructive mr-2" onClick={() => { setInvoice(null); if (fileRef.current) fileRef.current.value = ""; }}>
                        إزالة
                      </button>
                    </p>
                  )}
                </div>
                <div className="sm:col-span-2">
                  <Button type="submit" className="w-full sm:w-44 h-11 font-bold" disabled={submitting}>
                    {submitting ? <Loader2 className="w-4 h-4 ml-2 animate-spin" /> : <Plus className="w-4 h-4 ml-2" />}
                    تسجيل المصروف
                  </Button>
                </div>
              </form>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-base">سجل المصروفات ({expenses.length})</CardTitle>
            </CardHeader>
            <CardContent>
              {loading ? (
                <div className="flex justify-center py-8"><Loader2 className="w-7 h-7 animate-spin text-primary" /></div>
              ) : expenses.length === 0 ? (
                <p className="text-sm text-muted-foreground text-center py-8">لا توجد مصروفات مسجلة بعد</p>
              ) : (
                <div className="space-y-2 max-h-96 overflow-y-auto">
                  {expenses.map((ex) => (
                    <div key={ex.id} className="flex items-center justify-between gap-3 rounded-xl border p-3">
                      <div className="min-w-0">
                        <div className="flex items-center gap-2 flex-wrap">
                          <Badge variant="outline">{ex.category}</Badge>
                          <Badge variant="secondary" className="text-[10px]">
                            {ex.kindLabel ?? EXPENSE_KIND_AR[inferExpenseKind(ex.category)]}
                          </Badge>
                          {ex.voucherNumber && (
                            <Badge variant="outline" dir="ltr" className="text-[10px] bg-amber-50">وصل صرف: {ex.voucherNumber}</Badge>
                          )}
                          <span className="text-[11px] text-muted-foreground">{formatDateTime(ex.spentAt)}</span>
                        </div>
                        <p className="font-medium text-sm mt-1 truncate">{ex.description}</p>
                        <p className="text-[11px] text-muted-foreground">بواسطة {ex.creator?.fullName ?? "-"}</p>
                      </div>
                      <div className="flex items-center gap-2 shrink-0">
                        <span className="font-bold text-red-600">-{formatMoney(ex.amount, currency)}</span>
                        {ex.invoiceData && (
                          <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => setInvoiceView({ name: ex.invoiceName || "فاتورة", data: ex.invoiceData! })} aria-label="عرض الفاتورة">
                            <Eye className="w-4 h-4" />
                          </Button>
                        )}
                        {isAdmin && (
                          <Button variant="ghost" size="icon" className="h-8 w-8 text-amber-600" onClick={() => openEditExpense(ex)} aria-label="تعديل المصروف">
                            <Pencil className="w-4 h-4" />
                          </Button>
                        )}
                        {isAdmin && (
                          <Button variant="ghost" size="icon" className="h-8 w-8 text-destructive" onClick={() => deleteExpense(ex.id)} aria-label="حذف المصروف">
                            <Trash2 className="w-4 h-4" />
                          </Button>
                        )}
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        {/* الإيرادات المسجلة تلقائياً */}
        <TabsContent value="income" className="mt-4 space-y-4">
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-base flex items-center gap-2">
                <ReceiptText className="w-5 h-5 text-emerald-700" />
                الإيرادات (أقساط مسجلة تلقائياً)
              </CardTitle>
              <CardDescription>ابحث برقم الوصل أو اسم الطالب للوصول السريع — التعديل والحذف للإدارة</CardDescription>
            </CardHeader>
            <CardContent className="space-y-3">
              {/* بحث برقم الوصل / اسم الطالب / الكود */}
              <div className="relative">
                <Search className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                <Input
                  value={paymentQuery}
                  onChange={(e) => setPaymentQuery(e.target.value)}
                  placeholder="ابحث برقم الوصل أو اسم الطالب أو كوده — مثال: 12547 أو أحمد"
                  className="pr-9"
                  aria-label="بحث في الإيرادات المسجلة"
                />
                {searching && <Loader2 className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 animate-spin text-primary" />}
              </div>
              {loading ? (
                <div className="flex justify-center py-8"><Loader2 className="w-7 h-7 animate-spin text-primary" /></div>
              ) : filteredPayments.length === 0 ? (
                <p className="text-sm text-muted-foreground text-center py-8">
                  {paymentQuery.trim() ? "لا توجد نتائج مطابقة للبحث" : "لا توجد إيرادات بعد — سجل أول قسط من صفحة الدفع المباشر"}
                </p>
              ) : (
                <div className="space-y-2 max-h-[480px] overflow-y-auto">
                  {filteredPayments.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.notes ? ` · ${p.notes}` : ""}
                        </p>
                        <div className="flex items-center gap-1 shrink-0">
                          <Button
                            variant="outline"
                            size="sm"
                            className="h-8"
                            onClick={() => setReceiptPrint(p)}
                            aria-label={`طباعة وصل ${p.receiptNumber}`}
                          >
                            <Printer className="w-4 h-4 ml-1" />
                            طباعة الوصل
                          </Button>
                          {canManageReceipts && (
                            <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => openEditPayment(p)} aria-label={`تعديل قسط ${p.receiptNumber}`}>
                              <Pencil className="w-4 h-4" />
                            </Button>
                          )}
                          {canManageReceipts && (
                            <Button variant="ghost" size="icon" className="h-8 w-8 text-destructive" onClick={() => setDeletePayment(p)} aria-label={`حذف قسط ${p.receiptNumber}`}>
                              <Trash2 className="w-4 h-4" />
                            </Button>
                          )}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>

          {/* إيرادات أخرى (غير أقساط الطلبة) */}
          <Card>
            <CardHeader className="pb-3 flex-row items-start justify-between space-y-0">
              <div className="space-y-1.5">
                <CardTitle className="text-base flex items-center gap-2">
                  <Coins className="w-5 h-5 text-amber-600" />
                  إيرادات أخرى (غير أقساط الطلبة)
                </CardTitle>
                <CardDescription>
                  تبرعات، أنشطة، كافتيريا، إيجارات — الإجمالي: {formatMoney(otherIncomeTotal, currency)}
                </CardDescription>
              </div>
              <Button size="sm" onClick={openOiDialog} className="shrink-0">
                <PlusCircle className="w-4 h-4 ml-1" />
                تسجيل إيراد آخر
              </Button>
            </CardHeader>
            <CardContent>
              {loading ? (
                <div className="flex justify-center py-6"><Loader2 className="w-6 h-6 animate-spin text-primary" /></div>
              ) : otherIncomes.length === 0 ? (
                <p className="text-sm text-muted-foreground text-center py-6">لا توجد إيرادات أخرى مسجلة — اضغط "تسجيل إيراد آخر" لإضافة تبرع أو نشاط</p>
              ) : (
                <div className="space-y-2 max-h-[360px] overflow-y-auto">
                  {otherIncomes.map((oi) => (
                    <div key={oi.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">{oi.source}</span>
                          <Badge variant="secondary" className="text-[10px]">
                            {(oi as OtherIncomeDTO & { kindLabel?: string }).kindLabel ?? OTHER_INCOME_KIND_AR[(oi as OtherIncomeDTO & { kind?: string }).kind ?? "OTHER"]}
                          </Badge>
                          <Badge variant="outline" className="max-w-[220px] truncate">{oi.reason}</Badge>
                        </div>
                        <span className="font-bold text-emerald-700">+{formatMoney(oi.amount, currency)}</span>
                      </div>
                      <div className="flex items-center justify-between gap-2 flex-wrap">
                        <p className="text-[11px] text-muted-foreground">
                          {formatDateTime(oi.receivedAt)} · بواسطة {oi.creator?.fullName ?? "-"}
                          {oi.notes ? ` · ${oi.notes}` : ""}
                        </p>
                        <div className="flex items-center gap-1 shrink-0">
                          {(isAdmin || userRole === "ACCOUNTANT") && (
                            <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => openOiEdit(oi)} aria-label="تعديل الإيراد">
                              <Pencil className="w-4 h-4" />
                            </Button>
                          )}
                          {isAdmin && (
                            <Button variant="ghost" size="icon" className="h-8 w-8 text-destructive" onClick={() => setDeleteOi(oi)} aria-label="حذف الإيراد">
                              <Trash2 className="w-4 h-4" />
                            </Button>
                          )}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        {/* سلف النشاط (v8.1) */}
        <TabsContent value="activity-loans" className="mt-4">
          <ActivityLoansView currency={currency} isAdmin={isAdmin} refreshKey={refreshKey} onChanged={onFinanceChanged} />
        </TabsContent>

        {/* رواتب الموظفين */}
        <TabsContent value="payroll" className="mt-4">
          <PayrollView currency={currency} isAdmin={isAdmin} refreshKey={refreshKey} onFinanceChanged={onFinanceChanged} />
        </TabsContent>

        {/* الشركات */}
        <TabsContent value="suppliers" className="mt-4">
          <SuppliersView currency={currency} isAdmin={isAdmin} refreshKey={refreshKey} onFinanceChanged={onFinanceChanged} />
        </TabsContent>
      </Tabs>

      {/* حوار طباعة وصل الدفع من الإيرادات */}
      <Dialog open={!!receiptPrint} onOpenChange={(o) => !o && setReceiptPrint(null)}>
        <DialogContent className="sm:max-w-lg">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2 text-primary">
              <Printer className="w-5 h-5" />
              وصل رقم {receiptPrint?.receiptNumber}
            </DialogTitle>
            <DialogDescription>إعادة طباعة وصل قسط مسجل — يمكنك الطباعة الآن أو حفظه كـ PDF</DialogDescription>
          </DialogHeader>
          {receiptPrint && (
            <>
              <div className="max-h-[40vh] 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">{receiptPrint.student?.nameAr}</span></div>
                <div className="flex justify-between"><span className="text-muted-foreground">كود الطالب</span><span dir="ltr">{receiptPrint.student?.studentCode}</span></div>
                <div className="flex justify-between"><span className="text-muted-foreground">نوع القسط</span><span>{receiptPrint.installmentType}</span></div>
                <div className="flex justify-between"><span className="text-muted-foreground">المبلغ المدفوع</span><span className="font-bold text-primary">{formatMoney(receiptPrint.amount, currency)}</span></div>
                <div className="flex justify-between"><span className="text-muted-foreground">المتبقي حالياً</span><span className="font-bold">{formatMoney(receiptPrint.remaining ?? 0, currency)}</span></div>
                <div className="flex justify-between"><span className="text-muted-foreground">تاريخ الدفع</span><span>{formatDateTime(receiptPrint.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={() => setReceiptPrint(null)}>إغلاق</Button>
              </div>
            </>
          )}
        </DialogContent>
      </Dialog>

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

      {/* عرض الفاتورة المرفقة */}
      <Dialog open={!!invoiceView} onOpenChange={(o) => !o && setInvoiceView(null)}>
        <DialogContent className="sm:max-w-2xl max-h-[85vh]">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Paperclip className="w-5 h-5" />
              {invoiceView?.name}
            </DialogTitle>
            <DialogDescription>الفاتورة المرفقة مع المصروف</DialogDescription>
          </DialogHeader>
          {invoiceView && invoiceView.data.startsWith("data:image") ? (
            <img src={invoiceView.data} alt={invoiceView.name} className="max-h-[60vh] w-auto mx-auto rounded-lg border" />
          ) : (
            <div className="text-center py-6">
              <a href={invoiceView?.data} download={invoiceView?.name} className="inline-flex items-center gap-2 text-primary hover:underline">
                <Download className="w-4 h-4" />
                تنزيل الملف المرفق
              </a>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* حوار تعديل مصروف */}
      <Dialog open={!!editExpense} onOpenChange={(o) => !o && setEditExpense(null)}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle className="text-primary">تعديل المصروف</DialogTitle>
            <DialogDescription>
              المصروفات المرتبطة بدفعات الرواتب أو الشركات تُعدّل من صفحاتها — المصروف الحر يمكن تعديله هنا
            </DialogDescription>
          </DialogHeader>
          <form onSubmit={saveExpenseEdit} className="grid gap-3">
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-2">
                <Label>الفئة</Label>
                <Select value={editExpCategory} onValueChange={setEditExpCategory}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    {EXPENSE_CATEGORIES.map((c) => (
                      <SelectItem key={c} value={c}>{c}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label htmlFor="edit-exp-amount">المبلغ ({currency})</Label>
                <Input id="edit-exp-amount" type="number" min={0} value={editExpAmount} onChange={(e) => setEditExpAmount(e.target.value)} className="font-bold" required />
              </div>
            </div>
            <div className="space-y-2">
              <Label htmlFor="edit-exp-desc">الوصف</Label>
              <Input id="edit-exp-desc" value={editExpDesc} onChange={(e) => setEditExpDesc(e.target.value)} required />
            </div>
            <div className="space-y-2">
              <Label htmlFor="edit-exp-date">التاريخ</Label>
              <Input id="edit-exp-date" type="date" value={editExpDate} onChange={(e) => setEditExpDate(e.target.value)} required />
            </div>
            <div className="flex gap-2 pt-1">
              <Button type="submit" className="flex-1 font-bold" disabled={savingExp}>
                {savingExp && <Loader2 className="w-4 h-4 ml-2 animate-spin" />}
                حفظ التعديل
              </Button>
              <Button type="button" variant="outline" onClick={() => setEditExpense(null)}>إلغاء</Button>
            </div>
          </form>
        </DialogContent>
      </Dialog>

      {/* تأكيد حذف قسط طالب مسجل */}
      <AlertDialog open={!!deletePayment} onOpenChange={(o) => !o && setDeletePayment(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>حذف القسط المسجل؟</AlertDialogTitle>
            <AlertDialogDescription>
              سيتم حذف قسط الطالب {deletePayment?.student?.nameAr} (وصل رقم {deletePayment?.receiptNumber}) بمبلغ{" "}
              {deletePayment ? formatMoney(deletePayment.amount, currency) : ""}، وسيُعاد حساب رصيد الطالب تلقائياً.
              الوصول المطبوع سابقاً لن يُلغى تلقائياً — تأكد من استرجاعه. هل أنت متأكد؟
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>إلغاء</AlertDialogCancel>
            <AlertDialogAction
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
              onClick={(e) => { e.preventDefault(); confirmDeletePayment(); }}
              disabled={deletingPay}
            >
              {deletingPay && <Loader2 className="w-4 h-4 ml-2 animate-spin" />}
              نعم، حذف القسط
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* تعديل قسط مسجل */}
      <Dialog open={!!editPayment} onOpenChange={(o) => !o && setEditPayment(null)}>
        <DialogContent className="sm:max-w-lg max-h-[90dvh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="text-primary">تعديل وصل قسط طالب</DialogTitle>
            <DialogDescription>
              {editPayment?.student?.nameAr} — تعديل الوصل يعيد حساب رصيد الطالب وجدول الأقساط تلقائياً.
            </DialogDescription>
          </DialogHeader>
          <form onSubmit={savePaymentEdit} className="grid gap-3 sm:grid-cols-2">
            <div className="space-y-2">
              <Label htmlFor="edit-pay-receipt">رقم الوصل</Label>
              <Input id="edit-pay-receipt" value={editPayReceiptNumber} onChange={(e) => setEditPayReceiptNumber(e.target.value)} maxLength={80} required />
            </div>
            <div className="space-y-2">
              <Label htmlFor="edit-pay-amount">المبلغ ({currency})</Label>
              <Input id="edit-pay-amount" type="number" min={0.01} step="0.01" value={editPayAmount} onChange={(e) => setEditPayAmount(e.target.value)} className="font-bold" required />
            </div>
            <div className="space-y-2">
              <Label>نوع القسط</Label>
              <Select value={editPayInstallmentType} onValueChange={setEditPayInstallmentType}>
                <SelectTrigger><SelectValue placeholder="اختر نوع القسط" /></SelectTrigger>
                <SelectContent>{INSTALLMENT_TYPES.map((type) => <SelectItem key={type} value={type}>{type}</SelectItem>)}</SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label>طريقة الدفع</Label>
              <Select value={editPayMethod} onValueChange={setEditPayMethod}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="CASH">نقدي</SelectItem>
                  <SelectItem value="ELECTRONIC">إلكتروني</SelectItem>
                </SelectContent>
              </Select>
            </div>
            {editPayMethod === "ELECTRONIC" && (
              <div className="space-y-2 sm:col-span-2">
                <Label htmlFor="edit-pay-ref">مرجع العملية الإلكترونية</Label>
                <Input id="edit-pay-ref" value={editPayTransactionRef} onChange={(e) => setEditPayTransactionRef(e.target.value)} minLength={4} required />
              </div>
            )}
            <div className="space-y-2 sm:col-span-2">
              <Label htmlFor="edit-pay-notes">ملاحظات</Label>
              <Input id="edit-pay-notes" value={editPayNotes} onChange={(e) => setEditPayNotes(e.target.value)} placeholder="ملاحظات الوصل" />
            </div>
            {editPayment && (
              <p className="text-[11px] text-muted-foreground sm:col-span-2">
                قبل التعديل: {formatMoney(editPayment.amount, currency)} · مسدد للطالب: {formatMoney(editPayment.paidTotal ?? 0, currency)} · المتبقي: {formatMoney(editPayment.remaining ?? 0, currency)}
              </p>
            )}
            <div className="flex gap-2 pt-1 sm:col-span-2">
              <Button type="submit" className="flex-1 font-bold" disabled={savingPay || !editPayInstallmentType}>
                {savingPay && <Loader2 className="w-4 h-4 ml-2 animate-spin" />}
                حفظ تعديل الوصل
              </Button>
              <Button type="button" variant="outline" onClick={() => setEditPayment(null)}>إلغاء</Button>
            </div>
          </form>
        </DialogContent>
      </Dialog>

      {/* تسجيل / تعديل إيراد آخر */}
      <Dialog open={oiDialogOpen} onOpenChange={setOiDialogOpen}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle className="text-primary flex items-center gap-2">
              <Coins className="w-5 h-5" />
              {editOi ? "تعديل إيراد آخر" : "تسجيل إيراد آخر"}
            </DialogTitle>
            <DialogDescription>
              أي إيراد لا يخص أقساط الطلبة: تبرعات، أنشطة، كافتيريا، إيجار مقطع... يُضاف تلقائياً لإجمالي الإيرادات
            </DialogDescription>
          </DialogHeader>
          <form onSubmit={saveOi} className="grid gap-3">
            <div className="space-y-2">
              <Label>بند الإيراد (للميزانية والتقارير)</Label>
              <Select value={oiKind} onValueChange={setOiKind}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  {OTHER_INCOME_KINDS.map((k) => (
                    <SelectItem key={k} value={k}>{OTHER_INCOME_KIND_AR[k]}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label htmlFor="oi-source">جهة الإيراد *</Label>
              <Input
                id="oi-source"
                value={oiSource}
                onChange={(e) => setOiSource(e.target.value)}
                placeholder="من أين جاء المال — مثال: مدرسة أخرى، لجنة نشاط، مناقلة"
                required
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="oi-reason">سبب الإيراد *</Label>
              <Input
                id="oi-reason"
                value={oiReason}
                onChange={(e) => setOiReason(e.target.value)}
                placeholder="عن ماذا — مثال: تبرع لمشروع المختبر"
                required
              />
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-2">
                <Label htmlFor="oi-amount">المبلغ ({currency}) *</Label>
                <Input id="oi-amount" type="number" min={0} step="any" value={oiAmount} onChange={(e) => setOiAmount(e.target.value)} className="font-bold" required />
              </div>
              <div className="space-y-2">
                <Label htmlFor="oi-date">التاريخ *</Label>
                <Input id="oi-date" type="date" value={oiDate} onChange={(e) => setOiDate(e.target.value)} required />
              </div>
            </div>
            <div className="space-y-2">
              <Label htmlFor="oi-notes">ملاحظات</Label>
              <Input id="oi-notes" value={oiNotes} onChange={(e) => setOiNotes(e.target.value)} placeholder="اختياري" />
            </div>
            <div className="flex gap-2 pt-1">
              <Button type="submit" className="flex-1 font-bold" disabled={savingOi}>
                {savingOi && <Loader2 className="w-4 h-4 ml-2 animate-spin" />}
                {editOi ? "حفظ التعديل" : "تسجيل الإيراد"}
              </Button>
              <Button type="button" variant="outline" onClick={() => setOiDialogOpen(false)}>إلغاء</Button>
            </div>
          </form>
        </DialogContent>
      </Dialog>

      {/* تأكيد حذف إيراد آخر */}
      <AlertDialog open={!!deleteOi} onOpenChange={(o) => !o && setDeleteOi(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>حذف الإيراد؟</AlertDialogTitle>
            <AlertDialogDescription>
              سيتم حذف الإيراد من جهة «{deleteOi?.source}» بمبلغ {deleteOi ? formatMoney(deleteOi.amount, currency) : ""} وسيُخصم من إجمالي الإيرادات. هل أنت متأكد؟
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>إلغاء</AlertDialogCancel>
            <AlertDialogAction
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
              onClick={(e) => { e.preventDefault(); confirmDeleteOi(); }}
            >
              نعم، حذف الإيراد
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
