import { useState, useEffect, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import api, { useAuthStore } from '../../store/auth';
import { useEducationTerms } from '../../utils/educationTerms';
import {
  BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip,
  ResponsiveContainer, PieChart, Pie, Cell
} from 'recharts';
import {
  Users, TrendingUp, AlertCircle, CheckCircle2, Clock,
  XCircle, ChevronRight, Search, X, Download, Filter,
  Sparkles, School, GraduationCap, Building2,
  ChevronDown, Activity, Info, BarChart3, Heart, ShieldCheck
} from 'lucide-react';

// Extended attendance status types
type AttendanceStatus = 'present' | 'absent' | 'late' | 'excused';

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

interface ApiChild extends Child {
  [key: string]: unknown;
}

interface AttendanceRecord {
  id: number;
  student_id: number;
  date: string;
  status: AttendanceStatus;
  subject?: string;
  remarks?: string;
}

interface SubjectAggregate {
  subject: string;
  present: number;
  absent: number;
  late: number;
  excused: number;
}

const STATUS_COLORS: Record<AttendanceStatus, { text: string; bg: string; border: string; fill: string; label: string }> = {
  present: { text: 'text-emerald-600 dark:text-emerald-400', bg: 'bg-emerald-50 dark:bg-emerald-950/30', border: 'border-emerald-100 dark:border-emerald-900/30', fill: '#10b981', label: 'Present' },
  absent: { text: 'text-rose-600 dark:text-rose-400', bg: 'bg-rose-50 dark:bg-rose-950/30', border: 'border-rose-100 dark:border-rose-900/30', fill: '#ef4444', label: 'Absent' },
  late: { text: 'text-amber-600 dark:text-amber-400', bg: 'bg-amber-50 dark:bg-amber-950/30', border: 'border-amber-100 dark:border-amber-900/30', fill: '#f59e0b', label: 'Late' },
  excused: { text: 'text-blue-600 dark:text-blue-400', bg: 'bg-blue-50 dark:bg-blue-950/30', border: 'border-blue-100 dark:border-blue-900/30', fill: '#3b82f6', label: 'Excused' },
};

// Literal lookup for the bento-stats tile colors. Tailwind's JIT cannot
// scan template-built class names like `bg-${color}-50`, so we resolve them
// at module load. Add a color here when introducing new stat tiles.
type TileColor = 'emerald' | 'blue' | 'orange' | 'rose';
const TILE_THEME: Record<TileColor, { bg: string; text: string; border: string }> = {
  emerald: { bg: 'bg-emerald-50 dark:bg-emerald-950/30', text: 'text-emerald-600 dark:text-emerald-400', border: 'border-emerald-100 dark:border-emerald-900/30' },
  blue:    { bg: 'bg-blue-50 dark:bg-blue-950/30',       text: 'text-blue-600 dark:text-blue-400',       border: 'border-blue-100 dark:border-blue-900/30' },
  orange:  { bg: 'bg-orange-50 dark:bg-orange-950/30',   text: 'text-orange-600 dark:text-orange-400',   border: 'border-orange-100 dark:border-orange-900/30' },
  rose:    { 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' },
};

// Custom Tooltip Component (Supabase-like)
interface ChartTooltipProps {
  active?: boolean;
  payload?: Array<{ name?: string; value?: number | string; color?: string; fill?: string }>;
  label?: string | number;
  prefix?: string;
}

const CustomTooltip = ({ active, payload, label, prefix = "" }: ChartTooltipProps) => {
  if (active && payload && payload.length) {
    return (
      <div className="bg-card border border-border p-4 rounded-xl shadow-2xl backdrop-blur-md">
        <p className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted mb-2">{label}</p>
        <div className="space-y-1.5">
          {payload.map((entry, index) => (
            <div key={index} className="flex items-center justify-between gap-6">
              <div className="flex items-center gap-2">
                <div className="w-2 h-2 rounded-full" style={{ backgroundColor: entry.color || entry.fill || "#3b82f6" }} />
                <span className="text-[0.75rem] font-bold text-text-muted capitalize">{String(entry.name ?? '').replace(/([A-Z])/g, ' $1')}</span>
              </div>
              <span className="text-[0.85rem] font-black text-text">{prefix}{Number(entry.value ?? 0).toLocaleString()}</span>
            </div>
          ))}
        </div>
      </div>
    );
  }
  return null;
};

export default function ParentAttendance() {
  const navigate = useNavigate();
  const { user } = useAuthStore();
  const terms = useEducationTerms();
  const [children, setChildren] = useState<Child[]>([]);
  const [selectedChild, setSelectedChild] = useState<number | null>(null);
  const [attendance, setAttendance] = useState<AttendanceRecord[]>([]);
  const [loading, setLoading] = useState(true);
  const [showChildPicker, setShowChildPicker] = useState(false);

  // Load children
  useEffect(() => {
    let cancelled = false;
    api.get('/users/children').then(res => {
      if (cancelled) return;
      const students = (Array.isArray(res.data) ? res.data : []).map((s: ApiChild) => ({
          ...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(() => {
        if (cancelled) return;
        setLoading(false);
    });
    return () => { cancelled = true; };
  }, []);

  // Load attendance for selected child
  useEffect(() => {
    if (!selectedChild) return;
    let cancelled = false;
    setLoading(true);
    api.get('/attendance', { params: { student_id: selectedChild } })
      .then(res => {
        if (cancelled) return;
        setAttendance(res.data);
      })
      .catch((err) => {
        if (cancelled) return;
        console.error('Error fetching attendance:', err);
        setAttendance([]);
      })
      .finally(() => {
        if (cancelled) return;
        setLoading(false);
      });
    return () => { cancelled = true; };
  }, [selectedChild]);

  // Data transformations
  const statsSummary = useMemo(() => ({
    total: attendance.length,
    present: attendance.filter(a => a.status === 'present').length,
    absent: attendance.filter(a => a.status === 'absent').length,
    late: attendance.filter(a => a.status === 'late').length,
    excused: attendance.filter(a => a.status === 'excused').length,
  }), [attendance]);

  const attendanceRate = useMemo(() => statsSummary.total > 0
    ? Math.round(((statsSummary.present + statsSummary.late) / statsSummary.total) * 100)
    : 0, [statsSummary]);

  const pieData = useMemo(() => [
    { name: 'Present', value: statsSummary.present, fill: STATUS_COLORS.present.fill },
    { name: 'Absent', value: statsSummary.absent, fill: STATUS_COLORS.absent.fill },
    { name: 'Late', value: statsSummary.late, fill: STATUS_COLORS.late.fill },
    { name: 'Excused', value: statsSummary.excused, fill: STATUS_COLORS.excused.fill },
  ].filter(d => d.value > 0), [statsSummary]);

  // Subject-grouped attendance aggregated from real data
  const subjectData = useMemo<SubjectAggregate[]>(() => {
    const groups = new Map<string, SubjectAggregate>();
    for (const record of attendance) {
      const subject = record.subject?.trim() || 'Institutional';
      const bucket = groups.get(subject) ?? {
        subject,
        present: 0,
        absent: 0,
        late: 0,
        excused: 0,
      };
      bucket[record.status] += 1;
      groups.set(subject, bucket);
    }
    return Array.from(groups.values()).sort((a, b) =>
      a.subject.localeCompare(b.subject)
    );
  }, [attendance]);

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

  const stats = [
    { label: 'Attendance Rate', value: `${attendanceRate}%`, icon: TrendingUp, color: 'emerald', trend: 'Optimal' },
    { label: 'System Presence', value: statsSummary.present, icon: CheckCircle2, color: 'blue', trend: 'Logged' },
    { label: 'Punctuality', value: statsSummary.late, icon: Clock, color: 'orange', trend: 'Delayed' },
    { label: 'Total Absences', value: statsSummary.absent, icon: XCircle, color: 'rose', trend: 'Unexcused' },
  ];

  // CSV export helper
  const handleExportCsv = () => {
    const rows = [
      ['Date', 'Subject', 'Status', 'Remarks'],
      ...attendance.map(r => [r.date, r.subject || 'Institutional', r.status, r.remarks || '']),
    ];
    const csv = 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 = `attendance-log-${selectedChildData?.first_name ?? 'child'}-${new Date().toISOString().split('T')[0]}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  };

  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]">Aggregating Attendance Intel...</p>
    </div>
  );

  if (!loading && children.length === 0) return (
    <div className="py-24 text-center bg-card border-2 border-dashed border-border rounded-[3rem] animate-in fade-in duration-500">
        <Users size={64} className="mx-auto text-text-muted/20 mb-6" />
        <h3 className="text-2xl font-black text-text mb-2 uppercase tracking-tighter">No Associated Learners</h3>
        <p className="text-text-muted font-medium max-w-xs mx-auto">You have no students linked to your guardian registry at this time.</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">
              <Users size={20} />
            </div>
            <span className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted">Guardian Oversight</span>
          </div>
          <h1 className="text-4xl font-black text-text tracking-tighter">Attendance Registry</h1>
          <p className="text-text-muted text-lg font-medium">Daily presence tracking and institutional punctuality records.</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 onClick={handleExportCsv} className="flex items-center gap-2 px-5 py-2.5 bg-[#002147] text-white rounded-xl font-bold text-sm hover:bg-black transition-all shadow-lg active:scale-95">
            <Download size={18} />
            Export Intel
          </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) => {
          const theme = TILE_THEME[stat.color as TileColor] ?? TILE_THEME.blue;
          return (
            <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 ${theme.bg} ${theme.text} ${theme.border} 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>

      {/* Analysis Row */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
        <div className="lg:col-span-4 bg-card border border-border rounded-[2.5rem] p-10 shadow-sm flex flex-col items-center">
            <h4 className="text-[0.7rem] font-black uppercase tracking-[3px] text-text mb-8 w-full">Presence Analysis</h4>
            <div className="h-[250px] w-full relative">
                <ResponsiveContainer width="100%" height="100%">
                    <PieChart>
                        <Pie
                            data={pieData}
                            cx="50%"
                            cy="50%"
                            innerRadius={60}
                            outerRadius={100}
                            paddingAngle={8}
                            dataKey="value"
                            stroke="none"
                        >
                            {pieData.map((entry, index) => (
                                <Cell key={`cell-${index}`} fill={entry.fill} />
                            ))}
                        </Pie>
                        <Tooltip content={<CustomTooltip />} />
                    </PieChart>
                </ResponsiveContainer>
                <div className="absolute inset-0 flex flex-col items-center justify-center pointer-events-none">
                    <p className="text-3xl font-black text-text tracking-tighter">{attendanceRate}%</p>
                    <p className="text-[0.55rem] font-black text-text-muted uppercase tracking-widest">Attendance</p>
                </div>
            </div>
            <div className="mt-8 grid grid-cols-2 gap-4 w-full">
                {pieData.map(d => (
                    <div key={d.name} className="flex items-center gap-3">
                        <div className="w-1.5 h-1.5 rounded-full" style={{ backgroundColor: d.fill }}></div>
                        <span className="text-[0.65rem] font-black uppercase text-text-muted tracking-widest">{d.name}</span>
                    </div>
                ))}
            </div>
        </div>

        <div className="lg:col-span-8 bg-slate-950 dark:bg-card-elevated rounded-[2.5rem] p-10 shadow-2xl relative overflow-hidden group">
            <div className="absolute top-0 left-0 w-full h-1 bg-gradient-to-r from-emerald-500/0 via-emerald-500 to-emerald-500/0 opacity-50"></div>
            <div className="flex justify-between items-start mb-10 relative z-10">
              <div>
                <h4 className="text-[0.65rem] font-black uppercase tracking-[3px] text-emerald-500/50 mb-2">{terms.subject} Analytics</h4>
                <h2 className="text-2xl font-black text-white tracking-tight">Academic Presence Variance</h2>
              </div>
            </div>
            <div className="h-[300px] w-full relative z-10">
              <ResponsiveContainer width="100%" height="100%">
                <BarChart data={subjectData} margin={{ top: 10, right: 10, left: -20, bottom: 0 }}>
                  <CartesianGrid strokeDasharray="3 3" stroke="#1e293b" vertical={false} />
                  <XAxis dataKey="subject" axisLine={false} tickLine={false} interval={0} angle={-25} textAnchor="end" height={60} tick={{ fill: '#475569', fontSize: 10, fontWeight: 900 }} />
                  <YAxis axisLine={false} tickLine={false} tick={{ fill: '#475569', fontSize: 10, fontWeight: 900 }} allowDecimals={false} />
                  <Tooltip content={<CustomTooltip />} cursor={{ fill: 'currentColor', className: 'text-muted/10' }} />
                  <Bar dataKey="present" fill="#10b981" radius={[6, 6, 0, 0]} barSize={14} name="Logged Presence" />
                  <Bar dataKey="absent" fill="#ef4444" radius={[6, 6, 0, 0]} barSize={14} name="Logged Absence" />
                  <Bar dataKey="late" fill="#f59e0b" radius={[6, 6, 0, 0]} barSize={14} name="Delayed" />
                  <Bar dataKey="excused" fill="#3b82f6" radius={[6, 6, 0, 0]} barSize={14} name="Excused" />
                </BarChart>
              </ResponsiveContainer>
            </div>
        </div>
      </div>

      {/* Insights & Ledger */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
        <div className="lg:col-span-5 space-y-6">
            <h3 className="text-[0.7rem] font-black uppercase tracking-[3px] text-text-muted px-2">Briefing</h3>
            <div className={`p-8 rounded-[2.5rem] border transition-all relative overflow-hidden group ${statsSummary.absent > 3 ? 'bg-rose-50 dark:bg-rose-950/30 border-rose-100 dark:border-rose-900/30' : 'bg-emerald-50 dark:bg-emerald-950/30 border-emerald-100 dark:border-emerald-900/30'}`}>
                <div className="absolute right-[-20px] bottom-[-20px] opacity-[0.05] group-hover:scale-110 transition-transform duration-700">
                    <AlertCircle size={160} />
                </div>
                <div className="relative z-10 flex items-center gap-6">
                    <div className={`w-14 h-14 rounded-2xl flex items-center justify-center shadow-lg ${statsSummary.absent > 3 ? 'bg-rose-500 text-white' : 'bg-emerald-500 text-white'}`}>
                        <AlertCircle size={28} />
                    </div>
                    <div>
                        <h4 className={`text-xl font-black tracking-tight ${statsSummary.absent > 3 ? 'text-rose-900 dark:text-rose-100' : 'text-emerald-900 dark:text-emerald-100'}`}>Unexcused Absence Alert</h4>
                        <p className={`text-sm font-medium mt-1 leading-relaxed ${statsSummary.absent > 3 ? 'text-rose-700/80 dark:text-rose-200/60' : 'text-emerald-700/80 dark:text-emerald-200/60'}`}>
                            {statsSummary.absent === 0 ? 'Learner has maintained perfect unexcused records this term.' : `Target student has ${statsSummary.absent} unexcused gaps in current term log.`}
                        </p>
                    </div>
                </div>
            </div>
            <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-blue-400">
                            <ShieldCheck size={20} />
                        </div>
                        <span className="text-[0.65rem] font-black uppercase tracking-[3px] text-white/40">NextGen Secure</span>
                    </div>
                    <h4 className="text-xl font-black mb-3 leading-tight tracking-tight">Verified Attendance Transmissions</h4>
                    <p className="text-sm font-medium text-blue-50/70 leading-relaxed mb-8">All حضور records are captured in real-time by faculty and authenticated by the academic registry for full transparency.</p>
                    <button onClick={() => navigate('/calendar')} className="w-full py-4 bg-white/10 hover:bg-white/20 text-white rounded-xl text-[0.65rem] font-black uppercase tracking-widest transition-all border border-white/10">View Log History</button>
                </div>
            </div>
        </div>

        <div className="lg:col-span-7 space-y-6">
            <div className="flex items-center justify-between px-2">
                <h3 className="text-[0.7rem] font-black uppercase tracking-[3px] text-text-muted">Attendance Log</h3>
                <button onClick={handleExportCsv} className="text-primary text-[0.65rem] font-black hover:underline uppercase tracking-widest">View 30 Day Log</button>
            </div>
            <div className="bg-card border border-border rounded-[2.5rem] shadow-sm overflow-hidden flex flex-col">
                <div className="overflow-x-auto">
                    <table className="w-full text-left">
                        <thead>
                            <tr className="bg-muted/50 border-b border-border">
                                <th className="px-8 py-5 text-[0.6rem] font-black text-primary uppercase tracking-widest">Entry Date</th>
                                <th className="px-8 py-5 text-[0.6rem] font-black text-primary uppercase tracking-widest">Academic Module</th>
                                <th className="px-8 py-5 text-[0.6rem] font-black text-primary uppercase tracking-widest text-right">Registry Status</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-border">
                            {attendance.length === 0 ? (
                                <tr>
                                    <td colSpan={3} className="py-20 text-center">
                                        <Clock size={40} className="mx-auto text-text-muted/10 mb-4" />
                                        <p className="text-text-muted font-bold uppercase tracking-widest text-xs">No attendance records found</p>
                                    </td>
                                </tr>
                            ) : attendance.slice(0, 10).map((record) => {
                                const styles = STATUS_COLORS[record.status];
                                return (
                                    <tr key={record.id} className="hover:bg-muted transition-colors group">
                                        <td className="px-8 py-5">
                                            <p className="text-[0.9rem] font-bold text-text">{new Date(record.date).toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric' })}</p>
                                            <p className="text-[0.6rem] font-black text-text-muted uppercase tracking-widest mt-0.5">Verified Timestamp</p>
                                        </td>
                                        <td className="px-8 py-5">
                                            <div className="flex items-center gap-3">
                                                <div className="w-10 h-10 rounded-xl bg-muted border border-border flex items-center justify-center text-text-muted group-hover:text-primary transition-colors"><Building2 size={18} /></div>
                                                <div>
                                                    <p className="text-sm font-bold text-text-secondary group-hover:text-text transition-colors">{record.subject || 'Institutional'}</p>
                                                    <p className="text-[0.6rem] font-black text-text-muted uppercase tracking-widest mt-0.5">{record.remarks || 'Standard Registry'}</p>
                                                </div>
                                            </div>
                                        </td>
                                        <td className="px-8 py-5 text-right">
                                            <span className={`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl text-[0.65rem] font-black uppercase tracking-widest border ${styles.bg} ${styles.text} ${styles.border} shadow-sm`}>
                                                {styles.label}
                                            </span>
                                        </td>
                                    </tr>
                                );
                            })}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
      </div>

      <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>
  );
}
