import { useState, useEffect, useRef, useMemo } from 'react';
import { createPortal } from 'react-dom';
import api from '../store/auth';
import { Modal, ModalBody } from '../components/ui/Modal';
import {
  Plus, DollarSign, TrendingUp, CheckCircle,
  AlertCircle, School, BookText,
  Microscope, Receipt, Download,
  MoreVertical, CreditCard,
  Edit2, Copy, Trash2
} from 'lucide-react';

export default function Fees() {
  const [students, setStudents] = useState<any[]>([]);
  const [feeGroups, setFeeGroups] = useState<any[]>([]);
  const [studentFees, setStudentFees] = useState<any[]>([]);
  const [showGroupModal, setShowGroupModal] = useState(false);
  const [showAssignModal, setShowAssignModal] = useState(false);
  const [showPayModal, setShowPayModal] = useState(false);
  const [groupForm, setGroupForm] = useState({ name: '', description: '', amount: 0, due_date: '' });
  const [assignForm, setAssignForm] = useState({ student_id: '', fee_group_id: '', due_date: '' });
  const [payForm, setPayForm] = useState({ student_fee_id: '', amount: 0, payment_method: 'cash', reference_number: '' });
  const [feeStatusFilter, setFeeStatusFilter] = useState<'all' | 'paid' | 'partial' | 'unpaid'>('all');
  const [feeGroupMenuId, setFeeGroupMenuId] = useState<number | null>(null);
  const [feeGroupMenuPosition, setFeeGroupMenuPosition] = useState<{ top: number; right: number } | null>(null);
  const [editingFeeGroupId, setEditingFeeGroupId] = useState<number | null>(null);
  const [editGroupForm, setEditGroupForm] = useState({ name: '', description: '', amount: 0, due_date: '' });
  const feeGroupButtonRefs = useRef<Record<number, HTMLButtonElement | null>>({});

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

  const loadData = () => {
    api.get('/users?role=student').then(res => setStudents(res.data));
    api.get('/fees/groups').then(res => setFeeGroups(res.data));
    api.get('/fees/students').then(res => setStudentFees(res.data));
  };

  const handleGroupSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    await api.post('/fees/groups', groupForm);
    setShowGroupModal(false);
    setGroupForm({ name: '', description: '', amount: 0, due_date: '' });
    loadData();
  };

  const handleAssignSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    await api.post('/fees/students', assignForm);
    setShowAssignModal(false);
    setAssignForm({ student_id: '', fee_group_id: '', due_date: '' });
    loadData();
  };

  const handlePaySubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    await api.post('/fees/pay', payForm);
    setShowPayModal(false);
    setPayForm({ student_fee_id: '', amount: 0, payment_method: 'cash', reference_number: '' });
    loadData();
  };

  const totalOutstanding = studentFees.reduce((sum, f) => sum + (f.amount - f.paid_amount), 0);
  const totalCollected = studentFees.reduce((sum, f) => sum + f.paid_amount, 0);
  const partialCases = studentFees.filter(f => f.status === 'partial').length;
  const isPaid = (f: any) => f.status === 'paid' || (f.amount > 0 && f.paid_amount >= f.amount);
  const normalizedStudentFees = studentFees.map(f => ({ ...f, status: f.status === 'paid' || isPaid(f) ? 'paid' : f.status }));
  const filteredStudentFees = useMemo(
    () => feeStatusFilter === 'all' ? normalizedStudentFees : normalizedStudentFees.filter(f => f.status === feeStatusFilter),
    [normalizedStudentFees, feeStatusFilter]
  );

  const collectionTarget = totalCollected + totalOutstanding;
  const targetPct = collectionTarget > 0 ? Math.round((totalCollected / collectionTarget) * 100) : 0;

  const now = new Date();
  const prevMonthStart = new Date(now.getFullYear(), now.getMonth() - 1, 1);
  const prevMonthEnd = new Date(now.getFullYear(), now.getMonth(), 0, 23, 59, 59, 999);
  const prevMonthCollected = normalizedStudentFees.reduce((sum, f) => {
    const ref = f.due_date || f.updated_at;
    if (!ref) return sum;
    const d = new Date(ref);
    if (Number.isNaN(d.getTime())) return sum;
    if (d >= prevMonthStart && d <= prevMonthEnd) return sum + (f.paid_amount || 0);
    return sum;
  }, 0);
  let momLabel: string;
  if (totalCollected === 0 && prevMonthCollected === 0) {
    momLabel = 'No revenue yet';
  } else if (prevMonthCollected === 0) {
    momLabel = 'New this month';
  } else {
    const delta = ((totalCollected - prevMonthCollected) / prevMonthCollected) * 100;
    const rounded = Math.round(delta);
    const signed = rounded > 0 ? `+${rounded}%` : `${rounded}%`;
    momLabel = `${signed} vs last month`;
  }
  const momIsDown = prevMonthCollected > 0 && totalCollected < prevMonthCollected;

  const toggleFeeGroupMenu = (groupId: number) => {
    if (feeGroupMenuId === groupId) {
      setFeeGroupMenuId(null);
      setFeeGroupMenuPosition(null);
      return;
    }
    const button = feeGroupButtonRefs.current[groupId];
    if (!button) {
      setFeeGroupMenuId(groupId);
      return;
    }
    const rect = button.getBoundingClientRect();
    setFeeGroupMenuPosition({
      top: rect.bottom + 8,
      right: Math.max(8, window.innerWidth - rect.right),
    });
    setFeeGroupMenuId(groupId);
  };

  const closeFeeGroupMenu = () => {
    setFeeGroupMenuId(null);
    setFeeGroupMenuPosition(null);
  };

  const openEditFeeGroup = (fg: any) => {
    setEditGroupForm({
      name: fg.name || '',
      description: fg.description || '',
      amount: Number(fg.amount) || 0,
      due_date: fg.due_date || '',
    });
    setEditingFeeGroupId(fg.id);
    closeFeeGroupMenu();
  };

  const closeEditFeeGroup = () => {
    setEditingFeeGroupId(null);
    setEditGroupForm({ name: '', description: '', amount: 0, due_date: '' });
  };

  const handleEditGroupSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!editingFeeGroupId) return;
    await api.patch(`/fees/groups/${editingFeeGroupId}`, editGroupForm);
    closeEditFeeGroup();
    loadData();
  };

  const archiveFeeGroup = async (fg: any) => {
    if (!window.confirm('Archive this fee group? Existing assignments will be preserved.')) {
      closeFeeGroupMenu();
      return;
    }
    await api.delete(`/fees/groups/${fg.id}`);
    closeFeeGroupMenu();
    loadData();
  };

  const duplicateFeeGroup = async (fg: any) => {
    await api.post('/fees/groups', {
      name: `${fg.name} (copy)`,
      description: fg.description || '',
      amount: fg.amount,
      type: fg.type,
      frequency: fg.frequency,
      academic_year: fg.academic_year,
      due_date: fg.due_date,
    });
    closeFeeGroupMenu();
    loadData();
  };

  useEffect(() => {
    if (feeGroupMenuId === null) return;
    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as HTMLElement;
      if (
        !target.closest('[data-fee-group-menu]') &&
        !target.closest('[data-fee-group-dropdown]')
      ) {
        closeFeeGroupMenu();
      }
    };
    const handleKey = (event: KeyboardEvent) => {
      if (event.key === 'Escape') closeFeeGroupMenu();
    };
    document.addEventListener('mousedown', handleClickOutside);
    document.addEventListener('keydown', handleKey);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
      document.removeEventListener('keydown', handleKey);
    };
  }, [feeGroupMenuId]);

  return (
    <div className="space-y-8 animate-in fade-in duration-500 pb-10">
      {/* Module Header */}
      <div className="flex flex-col xl:flex-row justify-between items-start xl:items-center gap-6">
        <div>
          <h2 className="text-3xl font-black text-text tracking-tight capitalize">Fees Management</h2>
          <p className="text-text-muted mt-1 text-[0.95rem] font-medium max-w-2xl">
            Oversee school finances, manage fee structures, and track student payments with precision.
          </p>
        </div>
        <div className="flex flex-wrap gap-3">
          <button className="flex items-center gap-2 px-5 py-2.5 bg-card border border-border text-primary font-bold text-sm rounded-xl hover:bg-background-alt transition-all shadow-sm active:scale-95" onClick={() => setShowGroupModal(true)}>
            <Plus size={18} />
            Create Fee Group
          </button>
          <button className="flex items-center gap-2 px-5 py-2.5 bg-accent text-slate-900 dark:text-slate-950 font-black text-sm rounded-xl hover:opacity-90 transition-all shadow-lg shadow-accent/10 active:scale-95" onClick={() => setShowAssignModal(true)}>
            <CreditCard size={18} />
            Assign Fees
          </button>
          <button className="flex items-center gap-2 px-6 py-2.5 bg-primary text-white font-bold text-sm rounded-xl hover:bg-primary-dark transition-all shadow-lg shadow-primary/10 active:scale-95" onClick={() => setShowPayModal(true)}>
            <DollarSign size={18} />
            Record Payment
          </button>
        </div>
      </div>

      {/* Dashboard Bento Grid */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
        {/* Revenue Stats Grid */}
        <div className="lg:col-span-8 grid grid-cols-1 md:grid-cols-3 gap-4">
          <div className="bg-card border border-border p-6 rounded-3xl shadow-sm overflow-hidden relative group hover:shadow-md transition-all">
            <div className="absolute -right-4 -top-4 w-24 h-24 bg-background-alt rounded-full opacity-50 group-hover:scale-110 transition-transform"></div>
            <p className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted mb-2">Total Outstanding</p>
            <h3 className="text-2xl font-black text-text tracking-tighter">${totalOutstanding.toLocaleString()}</h3>
            <div className={`mt-4 flex items-center gap-2 text-[0.7rem] font-bold ${momIsDown ? 'text-rose-500' : 'text-rose-500'}`}>
              <TrendingUp size={14} className={momIsDown ? '' : 'rotate-180'} />
              <span>{momLabel}</span>
            </div>
          </div>

          <div className="bg-card border border-border p-6 rounded-3xl shadow-sm overflow-hidden relative group hover:shadow-md transition-all">
            <div className="absolute -right-4 -top-4 w-24 h-24 bg-primary/5 rounded-full opacity-50 group-hover:scale-110 transition-transform"></div>
            <p className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted mb-2">Revenue Collected</p>
            <h3 className="text-2xl font-black text-primary tracking-tighter">${totalCollected.toLocaleString()}</h3>
            <div className="mt-4 flex items-center gap-2 text-emerald-500 text-[0.7rem] font-bold">
              <CheckCircle size={14} />
              <span>{collectionTarget > 0 ? `${targetPct}% Target achieved` : 'No revenue yet'}</span>
            </div>
          </div>

          <div className="bg-card border border-border p-6 rounded-3xl shadow-sm overflow-hidden relative group hover:shadow-md transition-all">
            <div className="absolute -right-4 -top-4 w-24 h-24 bg-accent/5 rounded-full opacity-50 group-hover:scale-110 transition-transform"></div>
            <p className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted mb-2">Partial Payments</p>
            <h3 className="text-2xl font-black text-accent tracking-tighter">{partialCases} Cases</h3>
            <div className="mt-4 flex items-center gap-2 text-text-muted text-[0.7rem] font-bold">
              <AlertCircle size={14} />
              <span>{partialCases === 0 ? 'No partial cases' : `${partialCases} ${partialCases === 1 ? 'case' : 'cases'} awaiting review`}</span>
            </div>
          </div>
        </div>

        {/* Active Fee Groups */}
        <div className="lg:col-span-4 bg-card border border-border rounded-3xl shadow-sm flex flex-col overflow-hidden">
          <div className="px-6 py-4 border-b border-border flex justify-between items-center bg-background-alt/50">
            <h4 className="text-[0.65rem] font-black uppercase tracking-[2px] text-text">Active Fee Groups</h4>
          </div>
          <div className="p-3 space-y-1">
            {feeGroups.map((fg, idx) => (
              <div key={fg.id} className="flex items-center justify-between p-3 rounded-2xl hover:bg-background-alt/50 transition-colors group cursor-pointer">
                <div className="flex items-center gap-3">
                  <div className={`w-10 h-10 rounded-xl flex items-center justify-center ${idx % 3 === 0 ? 'bg-primary/10 text-primary' : idx % 3 === 1 ? 'bg-accent/10 text-accent' : 'bg-emerald-500/10 text-emerald-500'}`}>
                    {idx % 3 === 0 ? <School size={20} /> : idx % 3 === 1 ? <BookText size={20} /> : <Microscope size={20} />}
                  </div>
                  <div>
                    <p className="text-[0.85rem] font-bold text-text">{fg.name}</p>
                    <p className="text-[0.65rem] text-text-muted font-black uppercase tracking-tight">Annual Cycle</p>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <span className="text-[0.95rem] font-black text-primary tracking-tighter">${fg.amount}</span>
                  <button
                    ref={(el) => { feeGroupButtonRefs.current[fg.id] = el; }}
                    onClick={(e) => { e.stopPropagation(); toggleFeeGroupMenu(fg.id); }}
                    data-fee-group-dropdown
                    title="More actions"
                    className="p-1 rounded-lg hover:bg-background-alt transition-colors opacity-0 group-hover:opacity-100"
                  >
                    <MoreVertical size={16} className="text-text-muted cursor-pointer hover:text-primary" />
                  </button>
                </div>
              </div>
            ))}
            {feeGroups.length === 0 && (
              <div className="py-8 text-center text-text-muted/30 italic text-xs">No fee groups defined</div>
            )}
          </div>
          <button onClick={() => {
            if (feeGroups.length === 0) return;
            const headers = ['ID', 'Name', 'Amount', 'Description'];
            const rows = feeGroups.map((fg: any) => [fg.id, fg.name, fg.amount, fg.description || '']);
            const csv = [headers, ...rows].map(r => r.map(c => `"${String(c).replace(/"/g, '""')}"`).join(',')).join('\n');
            const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'fee_groups.csv';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
          }} className="mt-auto p-4 text-[0.7rem] text-primary font-black uppercase tracking-widest text-center hover:bg-background-alt/50 border-t border-border transition-colors">
            View All Fee Types
          </button>
        </div>
      </div>

      {/* Student Fees Table */}
      <div className="bg-card border border-border rounded-3xl shadow-sm overflow-hidden">
        <div className="px-6 py-5 border-b border-border bg-background-alt/50 flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
          <div className="flex items-center gap-4">
            <h4 className="text-xl font-black text-text tracking-tight">Student Fee Records</h4>
            <div className="flex gap-2">
              <span className="px-2.5 py-1 bg-card text-text-muted border border-border rounded-lg text-[0.6rem] font-black uppercase tracking-tight">All Students</span>
              <span className="px-2.5 py-1 bg-primary/10 text-primary border border-primary/20 rounded-lg text-[0.6rem] font-black uppercase tracking-tight">Academic Year 2024</span>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <select
              value={feeStatusFilter}
              onChange={e => setFeeStatusFilter(e.target.value as 'all' | 'paid' | 'partial' | 'unpaid')}
              className={`px-2.5 py-1 border rounded-lg text-[0.6rem] font-black uppercase tracking-tight transition-colors ${feeStatusFilter === 'all' ? 'bg-card text-text-muted border-border' : 'bg-primary/10 text-primary border-primary/20'}`}
              title="Filter fee records by status"
            >
              <option value="all">All Statuses</option>
              <option value="paid">Paid</option>
              <option value="partial">Partial</option>
              <option value="unpaid">Unpaid</option>
            </select>
            <button 
              onClick={() => {
                if (studentFees.length === 0) return;
                const headers = ['ID', 'Student', 'Fee Type', 'Amount', 'Paid', 'Status'];
                const rows = studentFees.map(sf => [sf.id, sf.student_name, sf.fee_group_name, sf.amount, sf.paid_amount, sf.status]);
                const csv = [headers, ...rows].map(r => r.map(c => `"${String(c).replace(/"/g, '""')}"`).join(',')).join('\n');
                const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = 'fees_export.csv';
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
              }}
              className="p-2 hover:bg-background-alt rounded-xl transition-all text-text-muted border border-transparent hover:border-border"
              title="Download fees export"
            >
              <Download size={18} />
            </button>
          </div>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-left">
            <thead>
              <tr className="bg-background-alt/80 border-b border-border">
                <th className="px-6 py-4 text-[0.65rem] font-black text-text uppercase tracking-widest">Student</th>
                <th className="px-6 py-4 text-[0.65rem] font-black text-text uppercase tracking-widest">Fee Type</th>
                <th className="px-6 py-4 text-[0.65rem] font-black text-text uppercase tracking-widest">Amount</th>
                <th className="px-6 py-4 text-[0.65rem] font-black text-text uppercase tracking-widest">Paid</th>
                <th className="px-6 py-4 text-[0.65rem] font-black text-text uppercase tracking-widest">Status</th>
                <th className="px-6 py-4 text-[0.65rem] font-black text-text uppercase tracking-widest text-right">Action</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border/50">
              {filteredStudentFees.map((sf) => (
                <tr key={sf.id} className="hover:bg-background-alt/40 transition-colors group">
                  <td className="px-6 py-4">
                    <div className="flex items-center gap-3">
                      <div className={`w-9 h-9 rounded-xl flex items-center justify-center text-[0.7rem] font-black shadow-sm group-hover:scale-105 transition-transform ${sf.status === 'paid' ? 'bg-emerald-500/10 text-emerald-500' : sf.status === 'partial' ? 'bg-accent/10 text-accent' : 'bg-rose-500/10 text-rose-500'}`}>
                        {sf.first_name?.[0]}{sf.last_name?.[0]}
                      </div>
                      <div>
                        <p className="text-[0.85rem] font-bold text-text">{sf.first_name} {sf.last_name}</p>
                        <p className="text-[0.65rem] text-text-muted font-medium">{sf.class_name ? `${sf.class_name}${sf.class_section ? ` ${sf.class_section}` : ''}` : '—'}</p>
                      </div>
                    </div>
                  </td>
                  <td className="px-6 py-4 text-sm font-medium text-text-secondary">{sf.fee_name}</td>
                  <td className="px-6 py-4 text-sm font-black text-text">${sf.amount.toLocaleString()}</td>
                  <td className="px-6 py-4 text-sm font-bold text-primary">${sf.paid_amount.toLocaleString()}</td>
                  <td className="px-6 py-4">
                    <span className={`px-3 py-1 rounded-full text-[0.6rem] font-black uppercase tracking-widest border ${
                      sf.status === 'paid' ? 'bg-emerald-500/10 text-emerald-500 border-emerald-500/20' : 
                      sf.status === 'partial' ? 'bg-accent/10 text-accent border-accent/20' : 
                      'bg-rose-500/10 text-rose-500 border-rose-500/20'
                    }`}>
                      {sf.status}
                    </span>
                  </td>
                  <td className="px-6 py-4 text-right">
                    <button
                      onClick={() => {
                        if (sf.id) {
                          setShowPayModal(true);
                          setPayForm({
                            student_fee_id: String(sf.id),
                            amount: sf.amount - sf.paid_amount,
                            payment_method: 'cash',
                            reference_number: ''
                          });
                        }
                      }}
                      className="p-2 text-text-muted/30 hover:text-primary transition-all opacity-0 group-hover:opacity-100"
                      title="View / record payment receipt"
                    >
                      <Receipt size={18} />
                    </button>
                  </td>
                </tr>
              ))}
              {studentFees.length === 0 && (
                <tr>
                  <td colSpan={6} className="py-20 text-center">
                    <DollarSign size={40} className="mx-auto text-text-muted/20 mb-4" />
                    <p className="text-text-muted font-bold uppercase tracking-widest text-xs">No fee records available</p>
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Modals */}
      {showGroupModal && (
        <Modal
          open={true}
          onClose={() => setShowGroupModal(false)}
          title="Create Fee Group"
          maxWidth="max-w-md"
          footer={
            <button type="submit" form="fees-create-group-form" className="w-full py-4 bg-primary hover:bg-primary-dark text-white font-bold rounded-2xl transition-all shadow-lg active:scale-95">
              Create Group
            </button>
          }
        >
          <ModalBody>
            <form id="fees-create-group-form" onSubmit={handleGroupSubmit} className="space-y-6">
              <div className="space-y-1.5">
                <label className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted">Name</label>
                <input className="form-input" value={groupForm.name} onChange={e => setGroupForm({...groupForm, name: e.target.value})} required />
              </div>
              <div className="space-y-1.5">
                <label className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted">Amount</label>
                <div className="relative">
                  <span className="absolute left-4 top-1/2 -translate-y-1/2 text-text-muted font-bold">$</span>
                  <input className="form-input pl-8" type="number" step="0.01" value={groupForm.amount} onChange={e => setGroupForm({...groupForm, amount: parseFloat(e.target.value)})} required />
                </div>
              </div>
            </form>
          </ModalBody>
        </Modal>
      )}

      {showAssignModal && (
        <Modal
          open={true}
          onClose={() => setShowAssignModal(false)}
          title="Assign Fees"
          maxWidth="max-w-md"
          footer={
            <button type="submit" form="fees-assign-form" className="w-full py-4 bg-accent text-slate-900 dark:text-slate-950 font-black rounded-2xl transition-all shadow-lg shadow-accent/10 active:scale-95">
              Assign to Student
            </button>
          }
        >
          <ModalBody>
            <form id="fees-assign-form" onSubmit={handleAssignSubmit} className="space-y-6">
              <div className="space-y-1.5">
                <label className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted">Student</label>
                <select className="form-input" value={assignForm.student_id} onChange={e => setAssignForm({...assignForm, student_id: e.target.value})} required>
                  <option value="">Select student...</option>
                  {students.map(s => <option key={s.id} value={s.id}>{s.first_name} {s.last_name}</option>)}
                </select>
              </div>
              <div className="space-y-1.5">
                <label className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted">Fee Group</label>
                <select className="form-input" value={assignForm.fee_group_id} onChange={e => setAssignForm({...assignForm, fee_group_id: e.target.value})} required>
                  <option value="">Select fee...</option>
                  {feeGroups.map(fg => <option key={fg.id} value={fg.id}>{fg.name} - ${fg.amount}</option>)}
                </select>
              </div>
            </form>
          </ModalBody>
        </Modal>
      )}

      {showPayModal && (
        <Modal
          open={true}
          onClose={() => setShowPayModal(false)}
          title="Record Payment"
          maxWidth="max-w-md"
          footer={
            <button type="submit" form="fees-record-pay-form" className="w-full py-4 bg-primary text-white font-bold rounded-2xl transition-all shadow-lg active:scale-95">
              Process Payment
            </button>
          }
        >
          <ModalBody>
            <form id="fees-record-pay-form" onSubmit={handlePaySubmit} className="space-y-6">
              <div className="space-y-1.5">
                <label className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted">Select Invoice</label>
                <select className="form-input text-sm" value={payForm.student_fee_id} onChange={e => setPayForm({...payForm, student_fee_id: e.target.value})} required>
                  <option value="">Select pending fee...</option>
                  {studentFees.filter(sf => sf.status !== 'paid').map(sf => (
                    <option key={sf.id} value={sf.id}>{sf.first_name} {sf.last_name} - {sf.fee_name}</option>
                  ))}
                </select>
              </div>
              <div className="space-y-1.5">
                <label className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted">Amount Paid</label>
                <div className="relative">
                  <span className="absolute left-4 top-1/2 -translate-y-1/2 text-text-muted font-bold">$</span>
                  <input className="form-input pl-8" type="number" step="0.01" value={payForm.amount} onChange={e => setPayForm({...payForm, amount: parseFloat(e.target.value)})} required />
                </div>
              </div>
            </form>
          </ModalBody>
        </Modal>
      )}

      {feeGroupMenuId !== null && feeGroupMenuPosition && createPortal(
        <div
          data-fee-group-menu
          className="fixed z-[200] w-44 bg-card border border-border rounded-xl shadow-2xl py-1.5 animate-in fade-in slide-in-from-top-1 duration-150"
          style={{ top: feeGroupMenuPosition.top, right: feeGroupMenuPosition.right }}
        >
          {(() => {
            const fg = feeGroups.find(g => g.id === feeGroupMenuId);
            if (!fg) return null;
            return (
              <>
                <button
                  type="button"
                  onClick={() => openEditFeeGroup(fg)}
                  className="w-full text-left px-4 py-2 hover:bg-muted text-sm font-bold text-text rounded-lg transition-colors flex items-center gap-2"
                >
                  <Edit2 size={16} className="text-text-muted" />
                  Edit
                </button>
                <button
                  type="button"
                  onClick={() => duplicateFeeGroup(fg)}
                  className="w-full text-left px-4 py-2 hover:bg-muted text-sm font-bold text-text rounded-lg transition-colors flex items-center gap-2"
                >
                  <Copy size={16} className="text-text-muted" />
                  Duplicate
                </button>
                <button
                  type="button"
                  onClick={() => archiveFeeGroup(fg)}
                  className="w-full text-left px-4 py-2 hover:bg-rose-50 dark:hover:bg-rose-950/30 text-sm font-bold text-rose-600 rounded-lg transition-colors flex items-center gap-2"
                >
                  <Trash2 size={16} className="text-rose-600" />
                  Archive
                </button>
              </>
            );
          })()}
        </div>,
        document.body
      )}

      {editingFeeGroupId !== null && (
        <Modal
          open={true}
          onClose={closeEditFeeGroup}
          title="Edit Fee Group"
          maxWidth="max-w-md"
          footer={
            <button type="submit" form="fees-edit-group-form" className="w-full py-4 bg-primary hover:bg-primary-dark text-white font-bold rounded-2xl transition-all shadow-lg active:scale-95">
              Save Changes
            </button>
          }
        >
          <ModalBody>
            <form id="fees-edit-group-form" onSubmit={handleEditGroupSubmit} className="space-y-6">
              <div className="space-y-1.5">
                <label className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted">Name</label>
                <input className="form-input" value={editGroupForm.name} onChange={e => setEditGroupForm({...editGroupForm, name: e.target.value})} required />
              </div>
              <div className="space-y-1.5">
                <label className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted">Description</label>
                <textarea className="form-input min-h-[5rem]" value={editGroupForm.description} onChange={e => setEditGroupForm({...editGroupForm, description: e.target.value})} />
              </div>
              <div className="space-y-1.5">
                <label className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted">Amount</label>
                <div className="relative">
                  <span className="absolute left-4 top-1/2 -translate-y-1/2 text-text-muted font-bold">$</span>
                  <input className="form-input pl-8" type="number" step="0.01" value={editGroupForm.amount} onChange={e => setEditGroupForm({...editGroupForm, amount: parseFloat(e.target.value)})} required />
                </div>
              </div>
              <div className="space-y-1.5">
                <label className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted">Due Date</label>
                <input className="form-input" type="date" value={editGroupForm.due_date || ''} onChange={e => setEditGroupForm({...editGroupForm, due_date: e.target.value})} />
              </div>
            </form>
          </ModalBody>
        </Modal>
      )}
    </div>
  );
}