import { useState, useEffect } from 'react';
import api from '../../store/auth';
import {
  LineChart, Line, XAxis, YAxis, Tooltip, ResponsiveContainer,
  AreaChart, Area, Cell, CartesianGrid, BarChart, Bar
} from 'recharts';
import {
  Share2, TrendingUp, TrendingDown, Users, BookOpen,
  RefreshCw, ChevronDown, ArrowLeft, GraduationCap,
  Activity, BarChart3, Clock, UserCircle,
  FileText, ArrowUpRight, ArrowDownRight, Info,
  ChevronRight, Sparkles, Target, Award, ShieldCheck,
  Heart, Download, Printer, Filter, X
} from 'lucide-react';
import { Link } from 'react-router-dom';

interface Student {
  id: number;
  first_name: string;
  last_name: string;
  class: string;
  grade: string;
  avatar?: string;
}

interface GradeEntry {
  period: string;
  avg: number;
  math?: number;
  english?: number;
  science?: number;
}

interface SubjectPerformance {
  subject: string;
  currentGrade: number;
  previousGrade: number;
  trend: 'up' | 'down' | 'stable';
  rank: number;
  totalStudents: number;
}

// Custom Tooltip Component (Supabase-like)
const CustomTooltip = ({ active, payload, label, prefix = "" }: any) => {
  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: any, index: number) => (
            <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-secondary capitalize">{entry.name.replace(/([A-Z])/g, ' $1')}</span>
              </div>
              <span className="text-[0.85rem] font-black text-text">{prefix}{entry.value.toLocaleString()}%</span>
            </div>
          ))}
        </div>
      </div>
    );
  }
  return null;
};

export default function AcademicProgress() {
  const [selectedStudent, setSelectedStudent] = useState<Student | null>(null);
  const [students, setStudents] = useState<Student[]>([]);
  const [gradeData, setGradeData] = useState<GradeEntry[]>([]);
  const [subjectPerformance, setSubjectPerformance] = useState<SubjectPerformance[]>([]);
  const [loading, setLoading] = useState(true);
  const [showStudentPicker, setShowStudentPicker] = useState(false);

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

  const loadStudents = async () => {
    setLoading(true);
    try {
      const res = await api.get('/users?role=student');
      const studentList = res.data.slice(0, 4).map((s: any) => ({
        id: s.id,
        first_name: s.first_name,
        last_name: s.last_name,
        class: `Section 10-A`,
        grade: `Grade 10`,
      }));
      setStudents(studentList);
      
      if (studentList.length > 0) {
        setSelectedStudent(studentList[0]);
        loadStudentData(studentList[0].id);
      }
    } catch (error) {
      setStudents(mockStudents);
      setSelectedStudent(mockStudents[0]);
      loadMockData();
    } finally {
      setLoading(false);
    }
  };

  const loadStudentData = async (studentId: number) => {
    setLoading(true);
    try {
      const [gradesRes, performanceRes] = await Promise.all([
        api.get(`/students/${studentId}/grades`).catch(() => ({ data: [] })),
        api.get(`/students/${studentId}/performance`).catch(() => ({ data: [] })),
      ]);
      setGradeData(gradesRes.data.length ? gradesRes.data : mockGradeData);
      setSubjectPerformance(performanceRes.data.length ? performanceRes.data : mockSubjectPerformance);
    } catch (error) {
      setGradeData(mockGradeData);
      setSubjectPerformance(mockSubjectPerformance);
    } finally {
      setLoading(false);
    }
  };

  const loadMockData = () => {
    setGradeData(mockGradeData);
    setSubjectPerformance(mockSubjectPerformance);
  };

  const handleStudentSelect = (student: Student) => {
    setSelectedStudent(student);
    setShowStudentPicker(false);
    loadStudentData(student.id);
  };

  const getGradeStyles = (grade: number) => {
    if (grade >= 90) return { text: 'text-emerald-600 dark:text-emerald-400', bg: 'bg-emerald-50 dark:bg-emerald-900/30', border: 'border-emerald-100 dark:border-emerald-800', fill: '#10b981', label: 'Excellent' };
    if (grade >= 80) return { text: 'text-blue-600 dark:text-blue-400', bg: 'bg-blue-50 dark:bg-blue-900/30', border: 'border-blue-100 dark:border-blue-800', fill: '#3b82f6', label: 'Good' };
    if (grade >= 70) return { text: 'text-amber-600 dark:text-amber-400', bg: 'bg-amber-50 dark:bg-amber-900/30', border: 'border-amber-100 dark:border-amber-800', fill: '#f59e0b', label: 'Satisfactory' };
    return { text: 'text-rose-600 dark:text-rose-400', bg: 'bg-rose-50 dark:bg-rose-900/30', border: 'border-rose-100 dark:border-rose-800', fill: '#ef4444', label: 'Needs Support' };
  };

  if (loading) 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 Academic Intel...</p>
    </div>
  );

  const currentAvg = gradeData.length > 0 ? gradeData[gradeData.length - 1].avg : 0;
  const improvement = gradeData.length >= 2 ? (gradeData[gradeData.length - 1].avg - gradeData[0].avg) : 0;

  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-blue-50/10 rounded-xl text-primary">
              <Target 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 text-capitalize dark:text-white">Academic Progress</h1>
          <p className="text-text-muted text-lg font-medium">Real-time performance monitoring and mastery analysis.</p>
        </div>
        
        <div className="flex flex-wrap items-center gap-3">
          {/* Student Picker */}
          <div className="relative">
            <button 
                onClick={() => setShowStudentPicker(!showStudentPicker)}
                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/50 transition-all shadow-sm active:scale-95"
            >
                <div className="w-8 h-8 rounded-lg bg-blue-50 dark:bg-blue-900/30 flex items-center justify-center text-primary dark:text-blue-400 text-xs font-black shadow-inner border border-blue-100 dark:border-blue-800">
                    {selectedStudent?.first_name[0]}{selectedStudent?.last_name[0]}
                </div>
                <span className="hidden sm:inline">{selectedStudent?.first_name} {selectedStudent?.last_name}</span>
                <ChevronDown size={16} className={`text-text-muted/30 transition-transform ${showStudentPicker ? 'rotate-180' : ''}`} />
            </button>
            
            {showStudentPicker && (
                <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">Associated Learners</p>
                    {students.map(s => (
                        <button
                            key={s.id}
                            onClick={() => handleStudentSelect(s)}
                            className={`w-full flex items-center gap-3 p-3 rounded-xl transition-all ${selectedStudent?.id === s.id ? 'bg-primary/5' : 'hover:bg-muted/50'}`}
                        >
                            <div className="w-10 h-10 rounded-xl bg-muted dark:bg-muted/20 border border-border flex items-center justify-center text-primary dark:text-blue-400 text-xs font-black shadow-sm">
                                {s.first_name[0]}{s.last_name[0]}
                            </div>
                            <div className="text-left">
                                <p className="text-sm font-bold text-text">{s.first_name} {s.last_name}</p>
                                <p className="text-[0.6rem] text-text-muted font-bold uppercase">{s.grade}</p>
                            </div>
                        </button>
                    ))}
                </div>
            )}
          </div>

          <button className="flex items-center gap-2 px-5 py-2.5 bg-primary text-white rounded-xl font-bold text-sm hover:bg-primary/90 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">
        {[
          { label: 'Intelligence Quotient', value: `${currentAvg.toFixed(1)}%`, icon: BarChart3, color: 'blue', trend: 'Average' },
          { label: 'System Ranking', value: `#${subjectPerformance[0]?.rank || 5}`, icon: GraduationCap, color: 'emerald', trend: `of ${subjectPerformance[0]?.totalStudents || 45}` },
          { label: 'Learning Credits', value: '25', icon: Award, color: 'purple', trend: 'Mastered' },
          { label: 'Pulse Improvement', value: `${improvement >= 0 ? '+' : ''}${improvement.toFixed(1)}%`, icon: TrendingUp, color: improvement >= 0 ? 'emerald' : 'rose', trend: 'Velocity' },
        ].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 
                ${stat.color === 'blue' ? 'bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 border-blue-100 dark:border-blue-800' : 
                  stat.color === 'emerald' ? 'bg-emerald-50 dark:bg-emerald-900/20 text-emerald-600 dark:text-emerald-400 border-emerald-100 dark:border-emerald-800' : 
                  stat.color === 'purple' ? 'bg-purple-50 dark:bg-purple-900/20 text-purple-600 dark:text-purple-400 border-purple-100 dark:border-purple-800' :
                  'bg-rose-50 dark:bg-rose-900/20 text-rose-600 dark:text-rose-400 border-rose-100 dark:border-rose-800'} 
                group-hover:scale-110 transition-transform border`}>
                <stat.icon size={24} />
              </div>
              <div className="text-[0.65rem] font-black px-3 py-1 bg-muted 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 dark:text-rose-400' : 'text-text'}`}>{stat.value}</h3>
          </div>
        ))}
      </div>

      {/* Main Analysis Section */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
        
        {/* Progression Trend (Area Chart) */}
        <div className="lg:col-span-8 space-y-6">
          <div className="bg-card border border-border rounded-[2.5rem] p-10 shadow-sm relative overflow-hidden group">
            <div className="absolute top-0 left-0 w-full h-1 bg-gradient-to-r from-blue-500/0 via-blue-500 to-blue-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-primary/50 mb-2">Mastery Analysis</h4>
                <h2 className="text-2xl font-black text-text tracking-tight">Academic Progression Trend</h2>
              </div>
              <div className="flex gap-4">
                <div className="flex items-center gap-2">
                  <div className="w-2 h-2 rounded-full bg-primary"></div>
                  <span className="text-[0.65rem] font-black text-text-muted uppercase tracking-widest">Efficiency Average</span>
                </div>
              </div>
            </div>

            <div className="h-[350px] w-full relative z-10">
              <ResponsiveContainer width="100%" height="100%">
                <AreaChart data={gradeData} margin={{ top: 10, right: 10, left: -20, bottom: 0 }}>
                  <defs>
                    <linearGradient id="colorAvg" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="5%" stopColor="#3b82f6" stopOpacity={0.3}/>
                      <stop offset="95%" stopColor="#3b82f6" stopOpacity={0}/>
                    </linearGradient>
                  </defs>
                  <CartesianGrid vertical={false} strokeDasharray="3 3" stroke="currentColor" className="text-border/30" />
                  <XAxis dataKey="period" axisLine={false} tickLine={false} tick={{ fill: 'currentColor', fontSize: 10, fontWeight: 900 }} className="text-text-muted" dy={15} />
                  <YAxis domain={[0, 100]} axisLine={false} tickLine={false} tick={{ fill: 'currentColor', fontSize: 10, fontWeight: 900 }} className="text-text-muted" />
                  <Tooltip content={<CustomTooltip />} cursor={{ stroke: 'currentColor', className: 'text-border', strokeWidth: 2, strokeDasharray: '4 4' }} />
                  <Area type="monotone" dataKey="avg" stroke="#3b82f6" strokeWidth={4} fillOpacity={1} fill="url(#colorAvg)" animationDuration={1500} name="Proficiency" />
                </AreaChart>
              </ResponsiveContainer>
            </div>
          </div>

          {/* Subject Mastery Ledger */}
          <div className="bg-card border border-border rounded-[2.5rem] shadow-sm overflow-hidden flex flex-col">
            <div className="p-8 bg-muted/50 border-b border-border flex justify-between items-center">
              <div>
                <h3 className="text-[0.7rem] font-black uppercase tracking-[3px] text-text">Mastery Ledger</h3>
                <p className="text-[0.6rem] font-bold text-text-muted uppercase mt-1">Current subject standings and rankings</p>
              </div>
              <button className="text-primary text-[0.65rem] font-black hover:underline uppercase tracking-widest">Full Portfolio</button>
            </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-8 py-5 text-[0.6rem] font-black text-text-muted uppercase tracking-widest">Subject Division</th>
                    <th className="px-8 py-5 text-[0.6rem] font-black text-text-muted uppercase tracking-widest text-center">Mastery Pulse</th>
                    <th className="px-8 py-5 text-[0.6rem] font-black text-text-muted uppercase tracking-widest text-center">Peer Rank</th>
                    <th className="px-8 py-5 text-[0.6rem] font-black text-text-muted uppercase tracking-widest text-right">Trend</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-border">
                  {subjectPerformance.map((subject, idx) => {
                    const styles = getGradeStyles(subject.currentGrade);
                    return (
                      <tr key={idx} className="hover:bg-muted/30 transition-colors group">
                        <td className="px-8 py-5">
                          <div className="flex items-center gap-4">
                            <div className="w-12 h-12 rounded-2xl bg-muted dark:bg-muted/20 flex items-center justify-center text-[0.8rem] font-black text-blue-400 dark:text-blue-400 shadow-inner group-hover:scale-110 transition-transform border border-border">
                              {subject.subject[0]}
                            </div>
                            <div>
                              <p className="text-[0.9rem] font-bold text-text group-hover:text-primary transition-colors">{subject.subject}</p>
                              <p className="text-[0.6rem] font-black text-text-muted uppercase tracking-widest mt-0.5">Academic Record</p>
                            </div>
                          </div>
                        </td>
                        <td className="px-8 py-5 text-center">
                          <div className="inline-flex items-center gap-3">
                            <span className={`text-lg font-black ${styles.text}`}>{subject.currentGrade}%</span>
                            <div className={`px-2.5 py-0.5 rounded-lg font-black text-[0.6rem] uppercase tracking-widest ${styles.bg} ${styles.text} border ${styles.border} shadow-sm`}>
                              {styles.label}
                            </div>
                          </div>
                        </td>
                        <td className="px-8 py-5 text-center">
                           <div className="bg-muted/50 dark:bg-muted/20 inline-block px-3 py-1.5 rounded-xl border border-border">
                              <span className="text-[0.8rem] font-black text-text">#{subject.rank}</span>
                              <span className="text-[0.6rem] text-text-muted font-bold ml-1">/ {subject.totalStudents}</span>
                           </div>
                        </td>
                        <td className="px-8 py-5 text-right">
                           <div className={`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl text-[0.65rem] font-black uppercase tracking-widest border ${subject.trend === 'up' ? 'bg-emerald-50 dark:bg-emerald-900/30 text-emerald-600 dark:text-emerald-400 border-emerald-100 dark:border-emerald-800' : subject.trend === 'down' ? 'bg-rose-50 dark:bg-rose-900/30 text-rose-600 dark:text-rose-400 border-rose-100 dark:border-rose-800' : 'bg-muted text-text-muted border-border'}`}>
                             {subject.trend === 'up' ? <ArrowUpRight size={14} /> : subject.trend === 'down' ? <ArrowDownRight size={14} /> : <Activity size={14} />}
                             {subject.trend}
                           </div>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </div>
        </div>

        {/* Right Sidebar Analysis */}
        <div className="lg:col-span-4 space-y-8">
            
            {/* Subject Comparison (Bar Chart) */}
            <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">Peer Benchmarking</h4>
                    <BarChart3 size={18} className="text-text-muted/30" />
                </div>
                <div className="h-[250px] w-full">
                    <ResponsiveContainer width="100%" height="100%">
                        <BarChart data={subjectPerformance} layout="vertical" margin={{ left: -30, right: 10 }}>
                            <XAxis type="number" hide />
                            <YAxis type="category" dataKey="subject" tick={{ fill: 'currentColor', fontSize: 10, fontWeight: 800 }} axisLine={false} tickLine={false} width={80} className="text-text-muted" />
                            <Tooltip content={<CustomTooltip />} cursor={{ fill: 'currentColor', className: 'text-muted/10' }} />
                            <Bar dataKey="currentGrade" fill="#0047AB" radius={[0, 6, 6, 0]} barSize={20} name="Proficiency" />
                        </BarChart>
                    </ResponsiveContainer>
                </div>
                <p className="text-[0.65rem] text-text-muted font-medium text-center mt-6 italic">Visualizing subject-wise proficiency against system standards.</p>
            </div>

            {/* AI Assistant Card */}
            <div className="bg-[#002147] 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">
                            <GraduationCap size={20} />
                        </div>
                        <span className="text-[0.65rem] font-black uppercase tracking-[3px] text-white/40">Intelligence Assist</span>
                    </div>
                    <h4 className="text-xl font-black mb-3 leading-tight tracking-tight uppercase">{selectedStudent?.first_name}'s progress is accelerating.</h4>
                    <p className="text-sm font-medium text-blue-50/70 leading-relaxed mb-8">
                        Mastery in <span className="text-white font-black">Pure Sciences</span> has increased by 12% this term. Reviewing next cycle curriculum is recommended.
                    </p>
                    <button 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 Study Briefing
                    </button>
                </div>
            </div>

            {/* Security/Trust Card */}
            <div className="bg-emerald-50 border border-emerald-100 dark:bg-emerald-500/10 dark:border-emerald-500/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-emerald-600" />
                </div>
                <div className="w-14 h-14 rounded-2xl bg-card border border-border flex items-center justify-center text-emerald-600 shadow-sm shrink-0">
                    <ShieldCheck size={28} />
                </div>
                <div>
                    <p className="text-sm font-black text-emerald-800 dark:text-emerald-500">Verified Intelligence</p>
                    <p className="text-[0.7rem] font-medium text-emerald-600/80 leading-snug mt-1">All academic records are digitally signed and verified by the school administration.</p>
                </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; }
        .custom-scrollbar::-webkit-scrollbar-thumb:hover { background: rgba(0, 71, 171, 0.2); }
        @media print {
            .no-print { display: none !important; }
            .lg\\:pl-64 { padding-left: 0 !important; }
            main { padding: 0 !important; }
        }
      `}</style>
    </div>
  );
}

const mockStudents: Student[] = [
    { id: 1, first_name: 'Amara', last_name: 'Diallo', class: 'Section 10-A', grade: 'Grade 10' },
    { id: 2, first_name: 'Kofi', last_name: 'Mensah', class: 'Section 8-B', grade: 'Grade 8' },
    { id: 3, first_name: 'Zuri', last_name: 'Okafor', class: 'Section 12-C', grade: 'Grade 12' },
];

const mockGradeData: GradeEntry[] = [
    { period: 'Term 1', avg: 75 },
    { period: 'Term 2', avg: 78 },
    { period: 'Mid Year', avg: 80 },
    { period: 'Term 3', avg: 83 },
    { period: 'Term 4', avg: 85 },
];

const mockSubjectPerformance: SubjectPerformance[] = [
    { subject: 'Mathematics', currentGrade: 85, previousGrade: 82, trend: 'up', rank: 2, totalStudents: 45 },
    { subject: 'English', currentGrade: 88, previousGrade: 85, trend: 'up', rank: 1, totalStudents: 45 },
    { subject: 'Science', currentGrade: 80, previousGrade: 78, trend: 'up', rank: 5, totalStudents: 45 },
    { subject: 'History', currentGrade: 85, previousGrade: 80, trend: 'up', rank: 3, totalStudents: 45 },
    { subject: 'Geography', currentGrade: 82, previousGrade: 76, trend: 'up', rank: 4, totalStudents: 45 },
    { subject: 'Art', currentGrade: 90, previousGrade: 92, trend: 'down', rank: 1, totalStudents: 30 },
];
