import { useState, useEffect, useCallback } from 'react';
import api, { useAuthStore } from '../../store/auth';
import {
  Plus, DollarSign, TrendingUp, CheckCircle2,
  AlertCircle, School, BookText,
  Microscope, Receipt, Filter, Download,
  ChevronRight, MoreVertical, CreditCard,
  ChevronDown, Activity, Info, BarChart3,
  Heart, ShieldCheck, Clock, Wallet,
  Calendar, ArrowUpRight, ArrowDownRight,
  Sparkles, GraduationCap, Users, Tag, Bus,
} from 'lucide-react';
import { PayFeesModal, PaymentHistory } from '../../components/PaynowPayment';

interface Child {
  id: number;
  uid?: string;
  first_name: string;
  last_name: string;
  grade?: string;
  class_name?: string;
}

interface FeeRecord {
  id: number;
  student_id: number;
  amount: number;
  paid_amount: number;
  discount_amount?: number;
  status: 'paid' | 'partial' | 'pending' | 'overdue' | 'cancelled';
  fee_name: string;
  fee_type?: string;
  plan_name?: string;
  due_date: string;
  created_at: string;
  discounts?: Array<{ discount_name: string; amount_applied: number }>;
}

export default function ParentFees() {
  const { user } = useAuthStore();
  const [children, setChildren] = useState<Child[]>([]);
  const [selectedChild, setSelectedChild] = useState<number | null>(null);
  const [studentFees, setStudentFees] = useState<FeeRecord[]>([]);
  const [loading, setLoading] = useState(true);
  const [showChildPicker, setShowChildPicker] = useState(false);
  const [showPayModal, setShowPayModal] = useState(false);

  const fetchFees = useCallback(async (studentUid: string) => {
    setLoading(true);
    try {
      // §10c — pull the enriched profile from /api/students/:uid/fees which
      // returns student_fees joined to fee_groups and student_fee_discounts.
      // Fallback to the legacy /api/fees/students endpoint if the new endpoint
      // hasn't shipped yet (defence-in-depth during §10c rollout).
      let rows: FeeRecord[] = [];
      try {
        const res = await api.get(`/students/${studentUid}/fees`);
        rows = (res.data?.fees || []).map((f: any) => ({
          id: f.id,
          student_id: f.student_id,
          amount: f.amount,
          paid_amount: f.paid_amount,
          discount_amount: f.discount_amount || 0,
          status: f.status,
          fee_name: f.fee_name,
          fee_type: f.fee_type,
          plan_name: f.plan_name,
          due_date: f.due_date,
          created_at: f.created_at,
          discounts: (f.discounts || []).map((d: any) => ({
            discount_name: d.discount_name, amount_applied: d.amount_applied,
          })),
        }));
      } catch {
        const res = await api.get('/fees/students', { params: { student_id: Number(studentUid) || undefined } });
        rows = res.data || [];
      }
      setStudentFees(rows);
    } catch (error) {
      setStudentFees([]);
    } finally {
      setLoading(false);
    }
  }, []);

  // Load children
  useEffect(() => {
    api.get('/users/children').then(res => {
      const students = res.data.map((s: any) => ({
          ...s,
          grade: s.grade || 'Grade 10',
          class_name: s.class_name || 'Section 10-A'
      }));
      setChildren(students);
      if (students.length > 0) {
        setSelectedChild(students[0].id);
      } else {
        setLoading(false);
      }
    }).catch(() => {
        setLoading(false);
    });
  }, []);

  // Load fees for selected child
  useEffect(() => {
    const child = children.find((c) => c.id === selectedChild);
    if (selectedChild && child?.uid) {
      fetchFees(child.uid);
    } else if (!selectedChild) {
      setLoading(false);
    }
  }, [selectedChild, children, fetchFees]);

  const totalOutstanding = studentFees.reduce((sum, f) => sum + Math.max(0, (f.amount || 0) - (f.discount_amount || 0) - (f.paid_amount || 0)), 0);

  const totalPaid = studentFees.reduce((sum, f) => sum + f.paid_amount, 0);
  const nextDeadline = studentFees.find(f => f.status !== 'paid')?.due_date || 'None';

  const selectedChildData = children.find(c => c.id === selectedChild) || children[0];

  const stats = [
    { label: 'Balance Due', value: `$${totalOutstanding.toLocaleString()}`, icon: Wallet, color: 'blue', trend: 'Current' },
    { label: 'Total Settled', value: `$${totalPaid.toLocaleString()}`, icon: CheckCircle2, color: 'emerald', trend: 'Verified' },
    { label: 'Next Deadline', value: nextDeadline !== 'None' ? new Date(nextDeadline).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }) : 'Clear', icon: Clock, color: 'orange', trend: 'Registry' },
    { label: 'Payment Pulse', value: 'Healthy', icon: ShieldCheck, color: 'purple', trend: 'Secure' },
  ];

  const getStatusStyles = (status: FeeRecord['status']) => {
    switch (status) {
        case 'paid': return { bg: 'bg-emerald-50', text: 'text-emerald-600', border: 'border-emerald-100', fill: '#10b981', label: 'Paid' };
        case 'partial': return { bg: 'bg-orange-50', text: 'text-orange-600', border: 'border-orange-100', fill: '#f59e0b', label: 'Partial' };
        case 'overdue': return { bg: 'bg-rose-50 dark:bg-rose-950/30', text: 'text-rose-600 dark:text-rose-400', border: 'border-rose-100 dark:border-rose-900/30', fill: '#ef4444', label: 'Overdue' };
        default: return { bg: 'bg-muted/50', text: 'text-text-muted', border: 'border-border', icon: Info, label: 'Pending' };
    }
  };

  if (loading && !children.length) return (
    <div className="flex flex-col justify-center items-center h-[60vh] gap-4 text-text-muted">
      <div className="w-10 h-10 border-4 border-primary border-t-transparent rounded-full animate-spin"></div>
      <p className="font-black uppercase tracking-[3px] text-[0.6rem]">Syncing Financial Records...</p>
    </div>
  );

  return (
    <div className="space-y-10 animate-in fade-in duration-700 pb-10">
      {/* Premium Header */}
      <div className="flex flex-col xl:flex-row justify-between items-start xl:items-end gap-6 no-print">
        <div className="space-y-1">
          <div className="flex items-center gap-3 mb-2">
            <div className="p-2 bg-primary/10 rounded-xl text-primary">
              <DollarSign size={20} />
            </div>
            <span className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted">Guardian Portal</span>
          </div>
          <h1 className="text-4xl font-black text-text tracking-tighter">Finance & Payments</h1>
          <p className="text-text-muted text-lg font-medium">Manage tuition, activity fees, and digital receipts securely.</p>
        </div>
        
        <div className="flex flex-wrap items-center gap-3">
          {/* Child Picker */}
          <div className="relative">
            <button 
                onClick={() => setShowChildPicker(!showChildPicker)}
                className="flex items-center gap-3 px-5 py-2.5 bg-card border border-border text-text rounded-xl font-bold text-sm hover:bg-muted transition-all shadow-sm active:scale-95"
            >
                <div className="w-8 h-8 rounded-lg bg-primary flex items-center justify-center text-white text-xs font-black shadow-inner">
                    {selectedChildData?.first_name?.[0] || 'L'}{selectedChildData?.last_name?.[0] || 'R'}
                </div>
                <span className="hidden sm:inline">{selectedChildData?.first_name} {selectedChildData?.last_name}</span>
                <ChevronDown size={16} className={`text-text-muted/30 transition-transform ${showChildPicker ? 'rotate-180' : ''}`} />
            </button>
            
            {showChildPicker && (
                <div className="absolute right-0 top-full mt-3 w-64 bg-card border border-border rounded-2xl shadow-2xl z-[100] p-2 animate-in zoom-in-95 duration-200">
                    <p className="text-[0.6rem] font-black uppercase tracking-widest text-text-muted px-4 py-2 border-b border-border/50 mb-1">Select Learner Registry</p>
                    {children.map(c => (
                        <button
                            key={c.id}
                            onClick={() => { setSelectedChild(c.id); setShowChildPicker(false); }}
                            className={`w-full flex items-center gap-3 p-3 rounded-xl transition-all ${selectedChild === c.id ? 'bg-primary/10' : 'hover:bg-muted'}`}
                        >
                            <div className="w-10 h-10 rounded-xl bg-card border border-border flex items-center justify-center text-primary text-xs font-black shadow-sm">
                                {c.first_name[0]}{c.last_name[0]}
                            </div>
                            <div className="text-left">
                                <p className="text-sm font-bold text-text">{c.first_name} {c.last_name}</p>
                                <p className="text-[0.6rem] text-text-muted font-bold uppercase">{c.grade || 'Grade 10'}</p>
                            </div>
                        </button>
                    ))}
                </div>
            )}
          </div>

          <button className="flex items-center gap-2 px-6 py-2.5 bg-[#0047AB] text-white rounded-xl font-bold text-sm hover:bg-[#003080] transition-all shadow-lg shadow-blue-900/10 active:scale-95" onClick={() => setShowPayModal(true)}>
            <Plus size={18} />
            Make Payment
          </button>
        </div>
      </div>

      {/* Bento Stats Grid */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {stats.map((stat) => (
          <div key={stat.label} className="bg-card border border-border p-6 rounded-[2rem] shadow-sm relative overflow-hidden group hover:shadow-md transition-all">
            <div className="relative z-10 flex justify-between items-start mb-4">
              <div className={`p-3 rounded-2xl bg-${stat.color}-50 dark:bg-${stat.color}-950/30 text-${stat.color}-600 dark:text-${stat.color}-400 border border-${stat.color}-100 dark:border-${stat.color}-900/30 group-hover:scale-110 transition-transform`}>
                <stat.icon size={24} />
              </div>
              <div className="text-[0.65rem] font-black px-3 py-1 bg-muted/50 text-text-muted rounded-full border border-border uppercase tracking-widest">
                {stat.trend}
              </div>
            </div>
            <p className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted mb-1">{stat.label}</p>
            <h3 className={`text-3xl font-black tracking-tighter ${stat.color === 'rose' ? 'text-rose-600' : 'text-text'}`}>{stat.value}</h3>
          </div>
        ))}
      </div>

      {/* Main Financial Section */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
        
        {/* Active Invoices (8/12) */}
        <div className="lg:col-span-8 space-y-6">
            <div className="flex items-center justify-between px-2">
                <div className="flex items-center gap-3">
                    <div className="p-2 bg-primary/10 rounded-xl text-primary">
                        <Receipt size={18} />
                    </div>
                    <h3 className="text-xl font-black text-text tracking-tight uppercase">Invoices</h3>
                </div>
                <span className="text-[0.65rem] font-bold text-text-muted uppercase tracking-widest">{studentFees.filter(f => f.status !== 'paid').length} Pending Requirements</span>
            </div>

            <div className="space-y-4">
                {studentFees.length === 0 ? (
                    <div className="py-24 text-center bg-card border-2 border-dashed border-border rounded-[3rem] opacity-60">
                        <DollarSign size={64} className="mx-auto text-text-muted/10 mb-6" />
                        <p className="text-text-muted font-bold uppercase tracking-widest text-xs italic">No billings recorded</p>
                    </div>
                ) : studentFees.map((fee) => {
                    const styles = getStatusStyles(fee.status);
                    const remaining = fee.amount - fee.paid_amount;
                    return (
                        <div key={fee.id} className={`bg-card border border-border rounded-[2.5rem] p-8 hover:shadow-xl hover:shadow-blue-900/5 transition-all group relative overflow-hidden flex flex-col md:flex-row justify-between items-start md:items-center gap-6`}>
                            <div className="absolute top-0 right-0 w-32 h-32 bg-muted/50 rounded-bl-[4rem] -mr-16 -mt-16 group-hover:bg-primary/10 transition-colors"></div>
                            
                            <div className="flex items-start gap-6 relative z-10">
                                <div className={`w-14 h-14 rounded-2xl ${styles.bg} ${styles.text} border ${styles.border} flex items-center justify-center group-hover:rotate-6 transition-transform shadow-sm`}>
                                    <BookText size={24} />
                                </div>
                                <div>
                                    <div className="flex items-center gap-3 mb-1">
                                        <h4 className="text-xl font-black text-text group-hover:text-primary transition-colors">{fee.fee_name}</h4>
                                        <span className={`px-2 py-0.5 rounded-lg text-[0.55rem] font-black uppercase tracking-widest border ${styles.bg} ${styles.text} ${styles.border}`}>
                                            {fee.status}
                                        </span>
                                    </div>
                                    <p className="text-[0.85rem] text-text-muted font-medium leading-relaxed max-w-md line-clamp-1">Academic Year 2024-25 • Term 2 Institutional Fees</p>
                                    
                                    <div className="flex flex-wrap items-center gap-6 mt-4">
                                        <div className="flex items-center gap-2 text-[0.7rem] font-bold text-text-muted uppercase tracking-widest">
                                            <Calendar size={14} className="text-text-muted/30" />
                                            Due: {new Date(fee.due_date).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}
                                        </div>
                                        <div className="flex items-center gap-2 text-[0.7rem] font-bold text-text-muted uppercase tracking-widest">
                                            <DollarSign size={14} className="text-text-muted/30" />
                                            Total: ${fee.amount.toLocaleString()}
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div className="flex flex-col items-end gap-3 relative z-10 w-full md:w-auto">
                                <div className="text-right">
                                    <p className="text-[0.6rem] font-black text-text-muted uppercase tracking-widest">Balance Required</p>
                                    <p className="text-2xl font-black text-text tracking-tighter">${remaining.toLocaleString()}</p>
                                </div>
                                {fee.status !== 'paid' && (
                                    <button 
                                        onClick={() => setShowPayModal(true)}
                                        className="flex items-center gap-2 bg-primary hover:bg-primary/90 text-white px-8 py-3 rounded-2xl font-black text-[0.65rem] uppercase tracking-widest transition-all shadow-lg shadow-blue-900/10 active:scale-95 group/btn"
                                    >
                                        Settle Invoice
                                        <ChevronRight size={16} className="group-hover/btn:translate-x-1 transition-transform" />
                                    </button>
                                )}
                            </div>
                        </div>
                    );
                })}
            </div>
        </div>

        {/* Right Sidebar (4/12) */}
        <div className="lg:col-span-4 space-y-8">
            
            {/* Payment History Component */}
            <div className="bg-card border border-border rounded-[2.5rem] p-8 shadow-sm">
                <div className="flex items-center justify-between mb-8">
                    <h4 className="text-[0.7rem] font-black uppercase tracking-[3px] text-text">Registry Archive</h4>
                    <button className="text-primary text-[0.6rem] font-black hover:underline uppercase tracking-widest">All Records</button>
                </div>
                <PaymentHistory studentId={selectedChild || 0} />
            </div>

            {/* NextGen Pay AI Card */}
            <div className="bg-slate-950 dark:bg-card-elevated rounded-[2.5rem] p-10 text-white shadow-2xl relative overflow-hidden group">
                <div className="absolute right-[-40px] bottom-[-40px] opacity-10 group-hover:rotate-12 transition-transform duration-700">
                    <Sparkles size={200} strokeWidth={1} />
                </div>
                <div className="relative z-10">
                    <div className="flex items-center gap-3 mb-6">
                        <div className="p-2.5 bg-white/10 rounded-xl backdrop-blur-md text-accent">
                            <Plus size={20} />
                        </div>
                        <span className="text-[0.65rem] font-black uppercase tracking-[3px] text-white/40">NextGen Pay</span>
                    </div>
                    <h4 className="text-xl font-black mb-3 leading-tight tracking-tight">Seamless Digital Settlement.</h4>
                    <p className="text-sm font-medium text-blue-50/70 leading-relaxed mb-8">
                        Use our secure integrated gateway to settle any outstanding academic balance instantly using <span className="text-white font-black">Paynow</span>.
                    </p>
                    <button className="w-full py-4 bg-accent hover:bg-accent/90 text-text rounded-xl text-[0.7rem] font-black uppercase tracking-widest transition-all shadow-xl shadow-orange-500/10 active:scale-95">
                        Configure Fast-Pay
                    </button>
                </div>
            </div>

            {/* Trust/Verification Card */}
            <div className="bg-success/10 border border-success/20 rounded-[2rem] p-8 flex items-center gap-6 relative overflow-hidden">
                <div className="absolute -right-6 -bottom-6 opacity-10">
                    <ShieldCheck size={120} className="text-success" />
                </div>
                <div className="w-14 h-14 rounded-2xl bg-card flex items-center justify-center text-success shadow-sm border border-success/20 shrink-0">
                    <ShieldCheck size={28} />
                </div>
                <div>
                    <p className="text-sm font-black text-success">Secure Protocol</p>
                    <p className="text-[0.7rem] font-medium text-success/80 leading-snug mt-1">Institutional payment encryption is active and verified by system auditors.</p>
                </div>
            </div>
        </div>
      </div>

      {/* Pay Modal */}
      {showPayModal && selectedChild && (
        <PayFeesModal studentId={selectedChild} onClose={() => { setShowPayModal(false); fetchFees(selectedChild); }} />
      )}

      <style>{`
        .custom-scrollbar::-webkit-scrollbar { width: 4px; }
        .custom-scrollbar::-webkit-scrollbar-track { background: transparent; }
        .custom-scrollbar::-webkit-scrollbar-thumb { background: rgba(0, 71, 171, 0.1); border-radius: 10px; }
      `}</style>
    </div>
  );
}

