import { useState, useEffect } from 'react';
import api from '../store/auth';
import { 
  Plus, DollarSign, TrendingUp, CheckCircle, 
  AlertCircle, School, BookText, 
  Microscope, Receipt, Filter, Download, 
  ChevronRight, MoreVertical, CreditCard
} 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: '' });

  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;

  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-muted/50 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-[#FFA500] text-[#002147] font-black text-sm rounded-xl hover:bg-[#FF8C00] transition-all shadow-lg shadow-orange-500/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/90 transition-all shadow-lg shadow-blue-900/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-muted 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-rose-500 text-[0.7rem] font-bold">
              <TrendingUp size={14} className="rotate-180" />
              <span>+12% from last month</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-blue-50 dark:bg-blue-900/20/10 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-600 text-[0.7rem] font-bold">
              <CheckCircle size={14} />
              <span>82% Target achieved</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-orange-50 dark:bg-orange-900/20/10 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>Review required</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-muted/50">
            <h4 className="text-[0.65rem] font-black uppercase tracking-[2px] text-text">Active Fee Groups</h4>
            <MoreVertical size={16} className="text-text-muted cursor-pointer hover:text-primary" />
          </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-muted/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-blue-50 dark:bg-blue-900/20 text-blue-600' : idx % 3 === 1 ? 'bg-orange-50 dark:bg-orange-900/20 text-orange-600' : 'bg-emerald-50 text-emerald-600'}`}>
                    {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>
                <span className="text-[0.95rem] font-black text-primary tracking-tighter">${fg.amount}</span>
              </div>
            ))}
            {feeGroups.length === 0 && (
              <div className="py-8 text-center text-text-muted/30 italic text-xs">No fee groups defined</div>
            )}
          </div>
          <button className="mt-auto p-4 text-[0.7rem] text-primary font-black uppercase tracking-widest text-center hover:bg-muted/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-muted/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 Ledger</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-blue-50 dark:bg-blue-900/20 text-blue-600 border border-blue-100 rounded-lg text-[0.6rem] font-black uppercase tracking-tight">Academic Year 2024</span>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <button className="p-2 hover:bg-muted rounded-xl transition-all text-text-muted border border-transparent hover:border-border"><Filter size={18} /></button>
            <button className="p-2 hover:bg-muted rounded-xl transition-all text-text-muted border border-transparent hover:border-border"><Download size={18} /></button>
          </div>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-left">
            <thead>
              <tr className="bg-muted/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">
              {studentFees.map((sf) => (
                <tr key={sf.id} className="hover:bg-muted/30 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-100 dark:bg-emerald-900/30 text-emerald-700 dark:text-emerald-400' : sf.status === 'partial' ? 'bg-orange-100 text-orange-700' : 'bg-rose-100 text-rose-700'}`}>
                        {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">Grade 10-B</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-50 text-emerald-600 border-emerald-100' : 
                      sf.status === 'partial' ? 'bg-orange-50 dark:bg-orange-900/20 text-orange-600 border-orange-100' : 
                      'bg-rose-50 text-rose-600 border-rose-100'
                    }`}>
                      {sf.status}
                    </span>
                  </td>
                  <td className="px-6 py-4 text-right">
                    <button className="p-2 text-text-muted/30 hover:text-primary transition-all opacity-0 group-hover:opacity-100">
                      <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-muted 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 && (
        <div className="fixed inset-0 bg-black/60 backdrop-blur-sm z-[150] flex items-center justify-center p-4">
          <div className="bg-card rounded-3xl w-full max-w-md shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200 border border-border">
            <div className="px-8 py-6 bg-muted/50 border-b border-border flex justify-between items-center">
              <h2 className="text-xl font-black text-text tracking-tight">Create Fee Group</h2>
              <button className="text-text-muted hover:text-rose-500 transition-colors text-2xl font-light" onClick={() => setShowGroupModal(false)}>×</button>
            </div>
            <form onSubmit={handleGroupSubmit} className="p-8 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>
              <button type="submit" 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>
            </form>
          </div>
        </div>
      )}

      {showAssignModal && (
        <div className="fixed inset-0 bg-black/60 backdrop-blur-sm z-[150] flex items-center justify-center p-4">
          <div className="bg-card rounded-3xl w-full max-w-md shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200 border border-border">
            <div className="px-8 py-6 bg-muted/50 border-b border-border flex justify-between items-center">
              <h2 className="text-xl font-black text-text tracking-tight">Assign Fees</h2>
              <button className="text-text-muted hover:text-rose-500 transition-colors text-2xl font-light" onClick={() => setShowAssignModal(false)}>×</button>
            </div>
            <form onSubmit={handleAssignSubmit} className="p-8 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>
              <button type="submit" className="w-full py-4 bg-[#FFA500] text-[#002147] font-black rounded-2xl transition-all shadow-lg shadow-orange-500/10 active:scale-95">
                Assign to Student
              </button>
            </form>
          </div>
        </div>
      )}

      {showPayModal && (
        <div className="fixed inset-0 bg-black/60 backdrop-blur-sm z-[150] flex items-center justify-center p-4">
          <div className="bg-card rounded-3xl w-full max-w-md shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200 border border-border">
            <div className="px-8 py-6 bg-muted/50 border-b border-border flex justify-between items-center">
              <h2 className="text-xl font-black text-text tracking-tight">Record Payment</h2>
              <button className="text-text-muted hover:text-rose-500 transition-colors text-2xl font-light" onClick={() => setShowPayModal(false)}>×</button>
            </div>
            <form onSubmit={handlePaySubmit} className="p-8 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>
              <button type="submit" className="w-full py-4 bg-primary text-white font-bold rounded-2xl transition-all shadow-lg active:scale-95">
                Process Payment
              </button>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}