'use client';

import { useCallback, useEffect, useState } from 'react';
import Link from 'next/link';
import { apiFetchJson } from '@/lib/auth';
import { PageHeader } from '@/components/school/page-header';
import {
  ListDataCard,
  ListDataCardBody,
  ListDataCardHeader,
  ListDataCardTitleBlock,
  ListDataCardToolbar,
  ListStatusBadge,
  TableSegment,
  TableSegmentGroup,
} from '@/components/school/list-data-card';
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { SelectNative } from '@/components/ui/select-native';
import { useToast } from '@/components/school/toast-context';
import {
  Banknote,
  CreditCard,
  ArrowRightLeft,
  Settings2,
  CirclePlus,
  FileText,
  ChevronLeft,
  ChevronRight,
  Zap,
  AlertCircle,
  CheckCircle2,
  Clock,
} from 'lucide-react';

// ─── Types ────────────────────────────────────────────────────

type FeeType = 'MONTHLY_TUITION' | 'TRANSPORT' | 'FOOD' | 'STATIONERY' | 'TRIP' | 'OTHER';

type FeeItem = {
  id: string;
  feeType: FeeType;
  label: string;
  amount: number;
};

type TuitionRow = {
  studentId: string;
  studentName: string;
  classroom: { id: string; name: string } | null;
  expectedMonthlyFee: number;
  hasSettings: boolean;
  invoice: {
    id: string;
    status: string;
    totalAmount: number;
    paidAmount: number;
    remaining: number;
    dueDate: string;
    feeItems: FeeItem[];
  } | null;
};

type OverviewData = {
  billingPeriod: string;
  rows: TuitionRow[];
  summary: {
    total: number;
    invoiced: number;
    notInvoiced: number;
    paid: number;
    pending: number;
    overdue: number;
    totalExpected: number;
    totalCollected: number;
  };
};

type StudentSettings = {
  monthlyFee: number;
  transportFee: number;
  foodFee: number;
  discountType: string | null;
  discountValue: number;
  discountReason: string | null;
  billingDay: number;
  notes: string | null;
  effectiveMonthlyTotal: number;
};

// ─── Helpers ─────────────────────────────────────────────────

function fmt(v: number) {
  return v.toLocaleString('tr-TR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

const MONTHS = ['Ocak', 'Şubat', 'Mart', 'Nisan', 'Mayıs', 'Haziran', 'Temmuz', 'Ağustos', 'Eylül', 'Ekim', 'Kasım', 'Aralık'];

const FEE_LABELS: Record<string, string> = {
  MONTHLY_TUITION: 'Aylık Aidat',
  TRANSPORT: 'Servis',
  FOOD: 'Yemek',
  STATIONERY: 'Kırtasiye',
  TRIP: 'Gezi',
  OTHER: 'Diğer',
};

const PM_LABELS: Record<string, string> = {
  CASH: 'Nakit',
  BANK_TRANSFER: 'Banka Havalesi',
  CREDIT_CARD: 'Kredi Kartı',
  OTHER: 'Diğer',
};

function StatusBadge({ status }: { status: string }) {
  if (status === 'PAID') return <ListStatusBadge tone="success"><CheckCircle2 className="mr-1 size-3" />Ödendi</ListStatusBadge>;
  if (status === 'OVERDUE') return <ListStatusBadge tone="warning"><AlertCircle className="mr-1 size-3" />Vadesi Geçti</ListStatusBadge>;
  return <ListStatusBadge tone="primary"><Clock className="mr-1 size-3" />Bekliyor</ListStatusBadge>;
}

// ─── Payment Dialog ───────────────────────────────────────────

function PaymentDialog({
  invoiceId,
  studentName,
  remaining,
  open,
  onClose,
  onSuccess,
}: {
  invoiceId: string;
  studentName: string;
  remaining: number;
  open: boolean;
  onClose: () => void;
  onSuccess: () => void;
}) {
  const { toast } = useToast();
  const [saving, setSaving] = useState(false);
  const [form, setForm] = useState({ amount: String(remaining), paymentMethod: 'CASH', providerRef: '', notes: '' });

  useEffect(() => {
    if (open) setForm({ amount: String(remaining.toFixed(2)), paymentMethod: 'CASH', providerRef: '', notes: '' });
  }, [open, remaining]);

  const submit = async () => {
    setSaving(true);
    const res = await apiFetchJson(`/v1/admin/invoices/${invoiceId}/payments`, {
      method: 'POST',
      body: JSON.stringify({
        amount: parseFloat(form.amount),
        paymentMethod: form.paymentMethod,
        providerRef: form.providerRef || undefined,
        notes: form.notes || undefined,
      }),
    });
    setSaving(false);
    if (res.error) toast({ title: 'Hata', description: res.error, variant: 'destructive' });
    else {
      toast({ title: 'Ödeme kaydedildi' });
      onSuccess();
    }
  };

  return (
    <Dialog open={open} onOpenChange={(v) => !v && onClose()}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>Ödeme Kaydet</DialogTitle>
        </DialogHeader>
        <div className="space-y-1 rounded-xl bg-slate-50 p-3 text-sm dark:bg-zinc-800">
          <p className="font-medium text-slate-900 dark:text-white">{studentName}</p>
          <p className="text-slate-500 dark:text-zinc-400">Kalan bakiye: <span className="font-semibold text-amber-600">{fmt(remaining)} ₺</span></p>
        </div>
        <div className="space-y-4">
          <div className="space-y-1.5">
            <Label>Ödeme Tutarı (₺)</Label>
            <Input
              type="number"
              min={0.01}
              step="0.01"
              max={remaining}
              value={form.amount}
              onChange={(e) => setForm({ ...form, amount: e.target.value })}
            />
          </div>
          <div className="space-y-1.5">
            <Label>Ödeme Yöntemi</Label>
            <SelectNative value={form.paymentMethod} onChange={(e) => setForm({ ...form, paymentMethod: e.target.value })}>
              <option value="CASH">Nakit</option>
              <option value="BANK_TRANSFER">Banka Havalesi</option>
              <option value="CREDIT_CARD">Kredi Kartı</option>
              <option value="OTHER">Diğer</option>
            </SelectNative>
          </div>
          <div className="space-y-1.5">
            <Label>Referans No (opsiyonel)</Label>
            <Input
              placeholder="Makbuz no, dekont no…"
              value={form.providerRef}
              onChange={(e) => setForm({ ...form, providerRef: e.target.value })}
            />
          </div>
          <div className="space-y-1.5">
            <Label>Not (opsiyonel)</Label>
            <Input
              placeholder="Ödeme notu…"
              value={form.notes}
              onChange={(e) => setForm({ ...form, notes: e.target.value })}
            />
          </div>
        </div>
        <DialogFooter>
          <Button type="button" variant="secondary" onClick={onClose}>İptal</Button>
          <Button
            type="button"
            disabled={saving || !form.amount || parseFloat(form.amount) <= 0}
            onClick={submit}
          >
            {saving ? 'Kaydediliyor…' : 'Ödemeyi Kaydet'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

// ─── Student Settings Dialog ──────────────────────────────────

function SettingsDialog({
  studentId,
  studentName,
  open,
  onClose,
  onSuccess,
}: {
  studentId: string;
  studentName: string;
  open: boolean;
  onClose: () => void;
  onSuccess: () => void;
}) {
  const { toast } = useToast();
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [form, setForm] = useState<{
    monthlyFee: string;
    transportFee: string;
    foodFee: string;
    discountType: string;
    discountValue: string;
    discountReason: string;
    billingDay: string;
    notes: string;
  }>({
    monthlyFee: '0',
    transportFee: '0',
    foodFee: '0',
    discountType: '',
    discountValue: '0',
    discountReason: '',
    billingDay: '1',
    notes: '',
  });

  useEffect(() => {
    if (!open || !studentId) return;
    setLoading(true);
    apiFetchJson<StudentSettings>(`/v1/admin/students/${studentId}/finance-settings`).then((res) => {
      setLoading(false);
      if (res.data) {
        const d = res.data as StudentSettings;
        setForm({
          monthlyFee: String(d.monthlyFee ?? 0),
          transportFee: String(d.transportFee ?? 0),
          foodFee: String(d.foodFee ?? 0),
          discountType: d.discountType ?? '',
          discountValue: String(d.discountValue ?? 0),
          discountReason: d.discountReason ?? '',
          billingDay: String(d.billingDay ?? 1),
          notes: d.notes ?? '',
        });
      }
    });
  }, [open, studentId]);

  const subtotal = (parseFloat(form.monthlyFee) || 0) + (parseFloat(form.transportFee) || 0) + (parseFloat(form.foodFee) || 0);
  let discount = 0;
  if (form.discountType === 'PERCENTAGE') discount = subtotal * ((parseFloat(form.discountValue) || 0) / 100);
  else if (form.discountType === 'FIXED') discount = parseFloat(form.discountValue) || 0;
  const effectiveTotal = Math.max(0, subtotal - discount);

  const save = async () => {
    setSaving(true);
    const res = await apiFetchJson(`/v1/admin/students/${studentId}/finance-settings`, {
      method: 'PUT',
      body: JSON.stringify({
        monthlyFee: parseFloat(form.monthlyFee) || 0,
        transportFee: parseFloat(form.transportFee) || 0,
        foodFee: parseFloat(form.foodFee) || 0,
        discountType: form.discountType || null,
        discountValue: parseFloat(form.discountValue) || 0,
        discountReason: form.discountReason || null,
        billingDay: parseInt(form.billingDay) || 1,
        notes: form.notes || null,
      }),
    });
    setSaving(false);
    if (res.error) toast({ title: 'Hata', description: res.error, variant: 'destructive' });
    else { toast({ title: 'Ayarlar kaydedildi' }); onSuccess(); }
  };

  return (
    <Dialog open={open} onOpenChange={(v) => !v && onClose()}>
      <DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-lg">
        <DialogHeader>
          <DialogTitle>Finans Ayarları — {studentName}</DialogTitle>
        </DialogHeader>
        {loading ? (
          <div className="py-8 text-center text-sm text-slate-400">Yükleniyor…</div>
        ) : (
          <div className="space-y-5">
            <div className="rounded-xl bg-slate-50 p-4 dark:bg-zinc-800">
              <p className="text-xs font-semibold uppercase tracking-widest text-slate-500 dark:text-zinc-400 mb-3">Ücretler</p>
              <div className="grid gap-3 sm:grid-cols-3">
                <div className="space-y-1.5">
                  <Label>Aylık Aidat (₺)</Label>
                  <Input type="number" min={0} step="0.01" value={form.monthlyFee} onChange={(e) => setForm({ ...form, monthlyFee: e.target.value })} />
                </div>
                <div className="space-y-1.5">
                  <Label>Servis (₺)</Label>
                  <Input type="number" min={0} step="0.01" value={form.transportFee} onChange={(e) => setForm({ ...form, transportFee: e.target.value })} />
                </div>
                <div className="space-y-1.5">
                  <Label>Yemek (₺)</Label>
                  <Input type="number" min={0} step="0.01" value={form.foodFee} onChange={(e) => setForm({ ...form, foodFee: e.target.value })} />
                </div>
              </div>
            </div>

            <div className="rounded-xl bg-slate-50 p-4 dark:bg-zinc-800">
              <p className="text-xs font-semibold uppercase tracking-widest text-slate-500 dark:text-zinc-400 mb-3">İndirim</p>
              <div className="grid gap-3 sm:grid-cols-2">
                <div className="space-y-1.5">
                  <Label>İndirim Tipi</Label>
                  <SelectNative value={form.discountType} onChange={(e) => setForm({ ...form, discountType: e.target.value })}>
                    <option value="">İndirim yok</option>
                    <option value="PERCENTAGE">Yüzde (%)</option>
                    <option value="FIXED">Sabit (₺)</option>
                  </SelectNative>
                </div>
                <div className="space-y-1.5">
                  <Label>Değer {form.discountType === 'PERCENTAGE' ? '(%)' : form.discountType === 'FIXED' ? '(₺)' : ''}</Label>
                  <Input
                    type="number"
                    min={0}
                    step="0.01"
                    disabled={!form.discountType}
                    value={form.discountValue}
                    onChange={(e) => setForm({ ...form, discountValue: e.target.value })}
                  />
                </div>
                <div className="space-y-1.5 sm:col-span-2">
                  <Label>İndirim Nedeni (kardeş, personel, vb.)</Label>
                  <Input
                    placeholder="İndirim nedeni…"
                    disabled={!form.discountType}
                    value={form.discountReason}
                    onChange={(e) => setForm({ ...form, discountReason: e.target.value })}
                  />
                </div>
              </div>
            </div>

            <div className="grid gap-3 sm:grid-cols-2">
              <div className="space-y-1.5">
                <Label>Fatura Günü (her ayın kaçı)</Label>
                <Input
                  type="number"
                  min={1}
                  max={28}
                  value={form.billingDay}
                  onChange={(e) => setForm({ ...form, billingDay: e.target.value })}
                />
              </div>
              <div className="space-y-1.5">
                <Label>Notlar</Label>
                <Input
                  placeholder="Özel not…"
                  value={form.notes}
                  onChange={(e) => setForm({ ...form, notes: e.target.value })}
                />
              </div>
            </div>

            {/* Preview */}
            <div className="rounded-xl border-2 border-brand-500/20 bg-brand-50/50 p-4 dark:border-brand-500/30 dark:bg-brand-900/10">
              <p className="mb-2 text-xs font-semibold uppercase tracking-widest text-brand-600 dark:text-brand-400">Aylık Net Tutar</p>
              <div className="space-y-1 text-sm">
                <div className="flex justify-between text-slate-600 dark:text-zinc-300">
                  <span>Ara Toplam</span>
                  <span className="tabular-nums">{fmt(subtotal)} ₺</span>
                </div>
                {discount > 0 && (
                  <div className="flex justify-between text-emerald-600 dark:text-emerald-400">
                    <span>İndirim</span>
                    <span className="tabular-nums">−{fmt(discount)} ₺</span>
                  </div>
                )}
                <div className="flex justify-between border-t border-brand-500/20 pt-1 font-bold text-slate-900 dark:text-white">
                  <span>Net Ödenecek</span>
                  <span className="tabular-nums text-brand-600 dark:text-brand-400">{fmt(effectiveTotal)} ₺</span>
                </div>
              </div>
            </div>
          </div>
        )}
        <DialogFooter>
          <Button type="button" variant="secondary" onClick={onClose}>İptal</Button>
          <Button type="button" disabled={saving || loading} onClick={save}>
            {saving ? 'Kaydediliyor…' : 'Kaydet'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

// ─── Main Page ────────────────────────────────────────────────

export default function TuitionPage() {
  const { toast } = useToast();
  const now = new Date();
  const [year, setYear] = useState(now.getFullYear());
  const [month, setMonth] = useState(now.getMonth() + 1);
  const [filterStatus, setFilterStatus] = useState('');
  const [data, setData] = useState<OverviewData | null>(null);
  const [loading, setLoading] = useState(false);
  const [generating, setGenerating] = useState(false);

  const [paymentDialog, setPaymentDialog] = useState<{ open: boolean; invoiceId: string; studentName: string; remaining: number }>({
    open: false, invoiceId: '', studentName: '', remaining: 0,
  });
  const [settingsDialog, setSettingsDialog] = useState<{ open: boolean; studentId: string; studentName: string }>({
    open: false, studentId: '', studentName: '',
  });

  const load = useCallback(async () => {
    setLoading(true);
    const q = new URLSearchParams({ year: String(year), month: String(month) });
    if (filterStatus) q.set('status', filterStatus);
    const res = await apiFetchJson<OverviewData>(`/v1/admin/finance/monthly-overview?${q.toString()}`);
    setLoading(false);
    if (!res.error) setData(res.data as OverviewData);
  }, [year, month, filterStatus]);

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

  const prevMonth = () => { if (month === 1) { setYear(y => y - 1); setMonth(12); } else setMonth(m => m - 1); };
  const nextMonth = () => { if (month === 12) { setYear(y => y + 1); setMonth(1); } else setMonth(m => m + 1); };

  const generate = async () => {
    setGenerating(true);
    const res = await apiFetchJson<{ created: number; skipped: number }>('/v1/admin/finance/generate-monthly', {
      method: 'POST',
      body: JSON.stringify({ year, month }),
    });
    setGenerating(false);
    if (res.error) toast({ title: 'Hata', description: res.error, variant: 'destructive' });
    else {
      const d = res.data as { created: number; skipped: number };
      toast({ title: `${d.created} fatura oluşturuldu, ${d.skipped} atlandı` });
      load();
    }
  };

  const summary = data?.summary;

  return (
    <div className="space-y-8">
      <PageHeader
        eyebrow="Finans"
        title="Aylık Aidat Yönetimi"
        description="Öğrenci bazlı ücret ayarları, otomatik tahakkuk ve ödeme takibi."
        backHref="/school/finance"
      />

      {/* ─── Month Selector + Generate ──────────────────────── */}
      <div className="flex flex-wrap items-center justify-between gap-4">
        <div className="flex items-center gap-2">
          <button
            type="button"
            onClick={prevMonth}
            className="flex h-9 w-9 items-center justify-center rounded-full border border-slate-900/15 bg-white text-slate-700 hover:bg-gray-50 dark:border-white/15 dark:bg-zinc-900 dark:text-zinc-200 dark:hover:bg-zinc-800"
          >
            <ChevronLeft className="size-4" />
          </button>
          <div className="min-w-[160px] text-center">
            <p className="text-xl font-bold text-slate-900 dark:text-white">
              {MONTHS[month - 1]} {year}
            </p>
            <p className="text-xs text-slate-400 dark:text-zinc-500">{year}-{String(month).padStart(2, '0')}</p>
          </div>
          <button
            type="button"
            onClick={nextMonth}
            className="flex h-9 w-9 items-center justify-center rounded-full border border-slate-900/15 bg-white text-slate-700 hover:bg-gray-50 dark:border-white/15 dark:bg-zinc-900 dark:text-zinc-200 dark:hover:bg-zinc-800"
          >
            <ChevronRight className="size-4" />
          </button>
        </div>

        <button
          type="button"
          disabled={generating}
          onClick={generate}
          className="inline-flex h-10 items-center justify-center gap-2 rounded-full bg-brand-600 px-5 text-sm font-bold text-white shadow-sm transition-colors hover:bg-brand-700 active:bg-brand-800 disabled:cursor-not-allowed disabled:bg-slate-300 dark:disabled:bg-zinc-700"
        >
          <Zap className={`size-4 ${generating ? 'animate-pulse' : ''}`} />
          {generating ? 'Faturalar oluşturuluyor…' : `${MONTHS[month - 1]} Faturalarını Oluştur`}
        </button>
      </div>

      {/* ─── Summary Cards ───────────────────────────────────── */}
      {summary && (
        <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-6">
          {[
            { label: 'Toplam', value: summary.total, color: 'text-slate-900 dark:text-white', bg: 'bg-white dark:bg-zinc-900' },
            { label: 'Faturalı', value: summary.invoiced, color: 'text-brand-600 dark:text-brand-400', bg: 'bg-brand-50 dark:bg-brand-900/20' },
            { label: 'Faturasız', value: summary.notInvoiced, color: 'text-slate-600 dark:text-zinc-300', bg: 'bg-slate-50 dark:bg-zinc-800' },
            { label: 'Ödendi', value: summary.paid, color: 'text-emerald-600 dark:text-emerald-400', bg: 'bg-emerald-50 dark:bg-emerald-900/20' },
            { label: 'Bekliyor', value: summary.pending, color: 'text-amber-600 dark:text-amber-400', bg: 'bg-amber-50 dark:bg-amber-900/20' },
            { label: 'Vadesi Geçti', value: summary.overdue, color: 'text-red-600 dark:text-red-400', bg: 'bg-red-50 dark:bg-red-900/20' },
          ].map((c) => (
            <div key={c.label} className={`rounded-xl p-4 text-center ring-1 ring-slate-900/8 dark:ring-white/8 ${c.bg}`}>
              <p className="text-2xl font-bold tabular-nums leading-none ${c.color}">{c.value}</p>
              <p className="mt-1.5 text-xs font-medium text-slate-500 dark:text-zinc-400">{c.label}</p>
            </div>
          ))}
        </div>
      )}

      {/* Collection progress */}
      {summary && summary.totalExpected > 0 && (
        <div className="rounded-2xl bg-white p-5 shadow-[0_1px_2px_rgba(15,23,42,0.04)] ring-1 ring-slate-900/8 dark:bg-zinc-900 dark:ring-white/8">
          <div className="mb-3 flex items-center justify-between">
            <div>
              <p className="text-sm font-bold text-slate-900 dark:text-white">Tahsilat Durumu — {MONTHS[month - 1]} {year}</p>
              <p className="text-xs text-slate-400 dark:text-zinc-500">{fmt(summary.totalCollected)} / {fmt(summary.totalExpected)} ₺</p>
            </div>
            <span className="text-2xl font-bold tabular-nums text-emerald-600 dark:text-emerald-400">
              %{Math.round((summary.totalCollected / summary.totalExpected) * 100)}
            </span>
          </div>
          <div className="h-3 overflow-hidden rounded-full bg-slate-100 dark:bg-zinc-800">
            <div
              className="h-full rounded-full bg-emerald-500 transition-all duration-700"
              style={{ width: `${Math.min(100, (summary.totalCollected / summary.totalExpected) * 100)}%` }}
            />
          </div>
        </div>
      )}

      {/* ─── Student Table ───────────────────────────────────── */}
      <ListDataCard>
        <ListDataCardHeader>
          <ListDataCardTitleBlock
            title="Öğrenci Aidat Listesi"
            description={`${MONTHS[month - 1]} ${year} dönemi`}
          />
          <ListDataCardToolbar>
            <TableSegmentGroup>
              {[
                { value: '', label: 'Tümü' },
                { value: 'NO_INVOICE', label: 'Faturasız' },
                { value: 'PENDING', label: 'Bekliyor' },
                { value: 'PAID', label: 'Ödendi' },
                { value: 'OVERDUE', label: 'Vadesi Geçti' },
              ].map((s) => (
                <TableSegment key={s.value} active={filterStatus === s.value} onClick={() => setFilterStatus(s.value)}>
                  {s.label}
                </TableSegment>
              ))}
            </TableSegmentGroup>
          </ListDataCardToolbar>
        </ListDataCardHeader>
        <ListDataCardBody>
          {loading ? (
            <div className="py-16 text-center text-sm text-slate-400 dark:text-zinc-500">Yükleniyor…</div>
          ) : !data || data.rows.length === 0 ? (
            <div className="py-16 text-center text-sm text-slate-400 dark:text-zinc-500">Bu dönem için öğrenci bulunamadı.</div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b border-slate-100 dark:border-zinc-800">
                    {['Öğrenci', 'Sınıf', 'Ayarlı Tutar', 'Fatura Tutarı', 'Ödenen', 'Kalan', 'Durum', 'İşlemler'].map((h) => (
                      <th key={h} className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-[0.06em] text-slate-500 dark:text-zinc-400">
                        {h}
                      </th>
                    ))}
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-50 dark:divide-zinc-800/60">
                  {data.rows.map((row) => (
                    <tr key={row.studentId} className="group transition-colors hover:bg-slate-50/70 dark:hover:bg-zinc-800/30">
                      <td className="px-4 py-3">
                        <span className="font-medium text-slate-900 dark:text-white">{row.studentName}</span>
                      </td>
                      <td className="px-4 py-3 text-slate-500 dark:text-zinc-400">
                        {row.classroom?.name ?? <span className="text-slate-300 dark:text-zinc-600">—</span>}
                      </td>
                      <td className="px-4 py-3">
                        {row.hasSettings ? (
                          <span className="tabular-nums font-medium text-slate-700 dark:text-zinc-300">{fmt(row.expectedMonthlyFee)} ₺</span>
                        ) : (
                          <span className="text-xs italic text-slate-400 dark:text-zinc-500">Tanımsız</span>
                        )}
                      </td>
                      <td className="px-4 py-3 tabular-nums text-slate-700 dark:text-zinc-300">
                        {row.invoice ? fmt(row.invoice.totalAmount) + ' ₺' : <span className="text-slate-300 dark:text-zinc-600">—</span>}
                      </td>
                      <td className="px-4 py-3 tabular-nums text-emerald-600 dark:text-emerald-400">
                        {row.invoice && row.invoice.paidAmount > 0 ? fmt(row.invoice.paidAmount) + ' ₺' : <span className="text-slate-300 dark:text-zinc-600">—</span>}
                      </td>
                      <td className="px-4 py-3 tabular-nums">
                        {row.invoice && row.invoice.remaining > 0 ? (
                          <span className="font-semibold text-amber-600 dark:text-amber-400">{fmt(row.invoice.remaining)} ₺</span>
                        ) : row.invoice?.status === 'PAID' ? (
                          <span className="text-slate-300 dark:text-zinc-600">—</span>
                        ) : (
                          <span className="text-slate-300 dark:text-zinc-600">—</span>
                        )}
                      </td>
                      <td className="px-4 py-3">
                        {row.invoice ? (
                          <StatusBadge status={row.invoice.status} />
                        ) : (
                          <ListStatusBadge tone="neutral">Fatura Yok</ListStatusBadge>
                        )}
                      </td>
                      <td className="px-4 py-3">
                        <div className="flex items-center gap-1">
                          {/* Finans ayarları */}
                          <button
                            type="button"
                            title="Finans ayarları"
                            onClick={() => setSettingsDialog({ open: true, studentId: row.studentId, studentName: row.studentName })}
                            className="inline-flex h-8 w-8 items-center justify-center rounded-lg text-slate-500 transition-colors hover:bg-slate-100 hover:text-brand-600 dark:text-zinc-400 dark:hover:bg-zinc-800 dark:hover:text-brand-400"
                          >
                            <Settings2 className="size-4" />
                          </button>

                          {/* Fatura detayı */}
                          {row.invoice && (
                            <Link
                              href={`/school/finance/invoices/${row.invoice.id}`}
                              title="Fatura detayı"
                              className="inline-flex h-8 w-8 items-center justify-center rounded-lg text-slate-500 transition-colors hover:bg-slate-100 hover:text-brand-600 dark:text-zinc-400 dark:hover:bg-zinc-800 dark:hover:text-brand-400"
                            >
                              <FileText className="size-4" />
                            </Link>
                          )}

                          {/* Ödeme kaydet */}
                          {row.invoice && row.invoice.status !== 'PAID' && row.invoice.status !== 'CANCELLED' && (
                            <button
                              type="button"
                              title="Ödeme kaydet"
                              onClick={() =>
                                setPaymentDialog({
                                  open: true,
                                  invoiceId: row.invoice!.id,
                                  studentName: row.studentName,
                                  remaining: row.invoice!.remaining,
                                })
                              }
                              className="inline-flex h-8 w-8 items-center justify-center rounded-lg text-slate-500 transition-colors hover:bg-emerald-50 hover:text-emerald-600 dark:text-zinc-400 dark:hover:bg-emerald-900/20 dark:hover:text-emerald-400"
                            >
                              <CirclePlus className="size-4" />
                            </button>
                          )}
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </ListDataCardBody>
      </ListDataCard>

      {/* ─── Dialogs ─────────────────────────────────────────── */}
      <PaymentDialog
        invoiceId={paymentDialog.invoiceId}
        studentName={paymentDialog.studentName}
        remaining={paymentDialog.remaining}
        open={paymentDialog.open}
        onClose={() => setPaymentDialog((d) => ({ ...d, open: false }))}
        onSuccess={() => { setPaymentDialog((d) => ({ ...d, open: false })); load(); }}
      />

      <SettingsDialog
        studentId={settingsDialog.studentId}
        studentName={settingsDialog.studentName}
        open={settingsDialog.open}
        onClose={() => setSettingsDialog((d) => ({ ...d, open: false }))}
        onSuccess={() => { setSettingsDialog((d) => ({ ...d, open: false })); load(); }}
      />
    </div>
  );
}
