import { useState, useEffect } from 'react';
import api, { useAuthStore } from '../../store/auth';
import { GradeBadge } from '../../components/GradeBadge';
import { useEducationTerms } from '../../utils/educationTerms';
import {
  BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer,
  Cell, CartesianGrid
} from 'recharts';
import {
  TrendingUp, Award, Target,
  RefreshCw, ChevronRight,
  FileText, GraduationCap,
  BarChart3, BookOpen
} from 'lucide-react';

interface GradeEntry {
  id: number;
  subject: string;
  type: 'assignment' | 'quiz' | 'test' | 'exam' | 'project';
  title: string;
  score: number;
  maxScore: number;
  percentage: number;
  date: string;
  teacher: string;
}

interface SubjectGrade {
  subject: string;
  grades: GradeEntry[];
  average: number;
  letterGrade: string;
  trend: 'up' | 'down' | 'stable';
}

interface PerformanceMetrics {
  overallAverage: number;
  totalCredits: number;
  rank: number;
  totalStudents: number;
  improvement: 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 }} />
                <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 Grades() {
  const { user } = useAuthStore();
  const terms = useEducationTerms();
  const [subjectGrades, setSubjectGrades] = useState<SubjectGrade[]>([]);
  const [recentGrades, setRecentGrades] = useState<GradeEntry[]>([]);
  const [metrics, setMetrics] = useState<PerformanceMetrics | null>(null);
  const [loading, setLoading] = useState(true);
  const [selectedSubject, setSelectedSubject] = useState<string>('all');
  const [filterType, setFilterType] = useState<string>('all');

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

  const loadGradeData = async () => {
    setLoading(true);
    try {
      const [gradesRes, metricsRes] = await Promise.all([
        api.get('/students/grades').catch(() => ({ data: { subjects: [], recent: [] } })),
        api.get('/students/grades/metrics').catch(() => ({ data: null }))
      ]);

      const subjects = gradesRes.data?.subjects ?? [];
      const recent = gradesRes.data?.recent ?? [];
      setSubjectGrades(subjects);
      setRecentGrades(recent);
      setMetrics(metricsRes.data ?? null);
    } catch (error) {
      setSubjectGrades([]);
      setRecentGrades([]);
      setMetrics(null);
    } finally {
      setLoading(false);
    }
  };

  const getGradeColor = (percentage: number) => {
    if (percentage >= 90) return { text: 'text-emerald-600 dark:text-emerald-400', bg: 'bg-emerald-50 dark:bg-emerald-900/20', border: 'border-emerald-100 dark:border-emerald-800', fill: '#10b981' };
    if (percentage >= 80) return { text: 'text-blue-600 dark:text-blue-400', bg: 'bg-blue-50 dark:bg-blue-900/20', border: 'border-blue-100 dark:border-blue-800', fill: '#3b82f6' };
    if (percentage >= 70) return { text: 'text-amber-600 dark:text-amber-400', bg: 'bg-amber-50 dark:bg-amber-900/20', border: 'border-amber-100 dark:border-amber-800', fill: '#f59e0b' };
    return { text: 'text-rose-600 dark:text-rose-400', bg: 'bg-rose-50 dark:bg-rose-900/20', border: 'border-rose-100 dark:border-rose-800', fill: '#ef4444' };
  };

  const getStatColors = (color: string) => {
    switch (color) {
      case 'blue': return 'bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 border-blue-100 dark:border-blue-800';
      case 'emerald': return 'bg-emerald-50 dark:bg-emerald-900/20 text-emerald-600 dark:text-emerald-400 border-emerald-100 dark:border-emerald-800';
      case 'purple': return 'bg-purple-50 dark:bg-purple-900/20 text-purple-600 dark:text-purple-400 border-purple-100 dark:border-purple-800';
      case 'rose': return 'bg-rose-50 dark:bg-rose-900/20 text-rose-600 dark:text-rose-400 border-rose-100 dark:border-rose-800';
      default: return 'bg-muted text-text-muted border-border';
    }
  };

  const filteredGrades = recentGrades.filter(grade => {
    if (selectedSubject !== 'all' && grade.subject !== selectedSubject) return false;
    if (filterType !== 'all' && grade.type !== filterType) return false;
    return true;
  });

  const chartData = subjectGrades.map(sg => ({
    name: sg.subject.length > 12 ? sg.subject.substring(0, 10) + '...' : sg.subject,
    fullName: sg.subject,
    average: Math.round(sg.average),
    letterGrade: sg.letterGrade,
  }));

  const uniqueSubjects = [...new Set(recentGrades.map(g => g.subject))];

  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]">Loading marks...</p>
    </div>
  );

  const hasGrades = subjectGrades.length > 0;

  const formatMetric = (format: (m: PerformanceMetrics) => string): string =>
    metrics ? format(metrics) : '—';

  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">
              <Target size={20} />
            </div>
            <span className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted">Academic Record</span>
          </div>
          <h1 className="text-4xl font-black text-text tracking-tighter">My Marks & Results</h1>
          <p className="text-text-muted text-lg font-medium">
            Term marks, continuous assessment, and exam results for the current term.
          </p>
        </div>

        <div className="flex flex-wrap items-center gap-3">
          <button
            className="flex items-center gap-2 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"
            onClick={() => window.open('/student/report-card', 'ReportCard', 'width=900,height=1100,menubar=no,toolbar=no,location=no,status=no')}
          >
            <FileText size={18} />
            Open Report Card
          </button>
          <button className="flex items-center gap-2 px-6 py-2.5 bg-primary text-white rounded-xl font-bold text-sm hover:bg-primary/90 transition-all shadow-lg shadow-blue-900/10 active:scale-95" onClick={loadGradeData}>
            <RefreshCw size={18} />
            Sync Marks
          </button>
        </div>
      </div>

      <div className="space-y-10 animate-in slide-in-from-bottom-4 duration-500">
        {/* Term Summary Stats */}
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
          {[
            { label: 'Term Average', value: formatMetric(m => `${m.overallAverage.toFixed(1)}%`), icon: BarChart3, color: 'blue', trend: 'All subjects' },
            { label: 'Class Position', value: formatMetric(m => m.rank != null ? `${m.rank}` : '—'), icon: GraduationCap, color: 'emerald', trend: metrics ? `of ${metrics.totalStudents}` : '—' },
            { label: 'Total Marks', value: formatMetric(m => `${m.totalCredits}`), icon: Award, color: 'purple', trend: 'this term' },
            { label: 'Term-on-Term Change', value: formatMetric(m => `${m.improvement >= 0 ? '+' : ''}${m.improvement}%`), icon: TrendingUp, color: (metrics?.improvement ?? 0) >= 0 ? 'emerald' : 'rose', trend: 'since last term' },
          ].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 ${getStatColors(stat.color)} group-hover:scale-110 transition-transform`}>
                  <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>

        {!hasGrades ? (
          <div className="bg-card border border-border rounded-[2.5rem] p-16 shadow-sm flex flex-col items-center justify-center text-center gap-4">
            <div className="p-5 bg-primary/10 rounded-3xl text-primary">
              <BookOpen size={40} />
            </div>
            <h3 className="text-2xl font-black text-text tracking-tight">No marks entered yet</h3>
            <p className="text-text-muted text-sm font-medium max-w-md">
              Once your teachers publish grades for this term, they will appear here in real time.
            </p>
          </div>
        ) : (
          <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
            {/* Performance Bar Chart (Supabase-like) */}
            <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">{terms.subject} Averages</h4>
                            <h2 className="text-2xl font-black text-text tracking-tight">Marks by {terms.subject}</h2>
                        </div>
                    </div>

                    <div className="h-[400px] w-full relative z-10">
                        <ResponsiveContainer width="100%" height="100%">
                            <BarChart data={chartData} margin={{ top: 10, right: 10, left: -20, bottom: 0 }}>
                                <CartesianGrid vertical={false} strokeDasharray="3 3" stroke="currentColor" className="text-border/30" />
                                <XAxis dataKey="name" 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={{ fill: 'currentColor', className: 'text-muted/20' }} />
                                <Bar dataKey="average" radius={[8, 8, 0, 0]} barSize={40} animationDuration={1500} name="Average mark">
                                    {chartData.map((entry, index) => (
                                        <Cell key={`cell-${index}`} fill={getGradeColor(entry.average).fill} />
                                    ))}
                                </Bar>
                            </BarChart>
                        </ResponsiveContainer>
                    </div>
                </div>

                {/* Mark Book */}
                <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 flex-col md:flex-row justify-between items-start md:items-center gap-4">
                        <div>
                            <h3 className="text-[0.7rem] font-black uppercase tracking-[3px] text-text">Mark Book</h3>
                            <p className="text-[0.6rem] font-bold text-text-muted uppercase mt-1">Class tests, assignments, and exam marks</p>
                        </div>
                        <div className="flex gap-2">
                            <select className="bg-card border border-border rounded-xl px-4 py-2 text-[0.65rem] font-black uppercase tracking-widest text-primary outline-none cursor-pointer" value={selectedSubject} onChange={e => setSelectedSubject(e.target.value)}>
                                <option value="all">All {terms.subjects}</option>
                                {uniqueSubjects.map(s => <option key={s} value={s}>{s}</option>)}
                            </select>
                        </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-8 py-5 text-[0.6rem] font-black text-text-muted uppercase tracking-widest">Assessment</th>
                                    <th className="px-8 py-5 text-[0.6rem] font-black text-text-muted uppercase tracking-widest text-center">Mark</th>
                                    <th className="px-8 py-5 text-[0.6rem] font-black text-text-muted uppercase tracking-widest text-right">Score</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-border">
                                {filteredGrades.map((grade) => {
                                    const styles = getGradeColor(grade.percentage);
                                    return (
                                        <tr key={`${grade.type}-${grade.id}`} className="hover:bg-muted/30 transition-colors">
                                            <td className="px-8 py-5">
                                                <p className="text-[0.9rem] font-bold text-text">{grade.title}</p>
                                                <p className="text-[0.65rem] font-black text-text-muted uppercase tracking-widest mt-0.5">{grade.subject}</p>
                                            </td>
                                            <td className="px-8 py-5 text-center">
                                                <GradeBadge
                                                  percentage={grade.percentage}
                                                  scaleKey={(grade as any).grading_scale ?? (grade as any).gradeScale ?? null}
                                                  overrideLetter={(grade as any).letter ?? (grade as any).grade_letter ?? null}
                                                  size="sm"
                                                />
                                            </td>
                                            <td className="px-8 py-5 text-right font-mono text-[0.8rem] font-bold text-text-muted">
                                                {grade.score} / {grade.maxScore}
                                            </td>
                                        </tr>
                                    );
                                })}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            {/* Subject Breakdown cards here */}
            <div className="lg:col-span-4 space-y-8">
              {subjectGrades.map(sg => {
                const styles = getGradeColor(sg.average);
                return (
                  <div key={sg.subject} className="bg-card border border-border rounded-[2.5rem] p-8 shadow-sm group hover:shadow-xl hover:shadow-blue-900/5 transition-all relative overflow-hidden">
                    <div className="absolute top-0 right-0 w-32 h-32 bg-muted rounded-bl-[4rem] -mr-16 -mt-16 group-hover:bg-blue-50/10 dark:group-hover:bg-blue-900/10 transition-colors"></div>
                    <div className="relative z-10 flex justify-between items-start mb-8">
                      <div className="space-y-1">
                        <h4 className="text-xl font-black text-text tracking-tight truncate max-w-[180px] group-hover:text-primary transition-colors">{sg.subject}</h4>
                        <p className="text-[0.65rem] font-black text-text-muted uppercase tracking-widest">{(sg.grades || []).length} assessments</p>
                      </div>
                      <div className="group-hover:scale-110 transition-transform">
                        <GradeBadge
                          percentage={sg.average}
                          scaleKey={(sg as any).gradeScale ?? (sg as any).grading_scale ?? null}
                          overrideLetter={sg.letterGrade}
                          overrideDescriptor={(sg as any).gradeDescriptor ?? null}
                        />
                      </div>
                    </div>
                    <div className="relative z-10 space-y-6">
                        <div className="flex justify-between items-end">
                            <h5 className={`text-3xl font-black ${styles.text} tracking-tighter`}>{sg.average.toFixed(1)}%</h5>
                            <div className={`flex items-center gap-1.5 px-3 py-1 rounded-full text-[0.6rem] font-black uppercase tracking-widest border ${sg.trend === 'up' ? 'bg-emerald-50 dark:bg-emerald-900/20 text-emerald-600 dark:text-emerald-400 border-emerald-100 dark:border-emerald-800' : 'bg-muted text-text-muted border-border'}`}>
                                {sg.trend === 'up' ? 'Improving' : 'No change'}
                            </div>
                        </div>
                        <div className="w-full h-2 bg-muted rounded-full overflow-hidden p-0.5 shadow-inner">
                            <div className={`h-full rounded-full transition-all duration-1000 ${styles.bg.replace('50', '500')}`} style={{ width: `${sg.average}%` }} />
                        </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        )}
      </div>

      <style>{`
        @media print {
            body { background: white !important; color: black !important; }
            .no-print { display: none !important; }
            .flex-1 { overflow: visible !important; }
            .lg\\:pl-64 { padding-left: 0 !important; }
            main { padding: 0 !important; }
            .bg-card, .bg-muted, .bg-white { background: white !important; border: 1px solid #eee !important; box-shadow: none !important; color: black !important; }
            .text-white, .text-slate-300, .text-slate-400 { color: #333 !important; }
            .rounded-[3rem], .rounded-[2.5rem] { border-radius: 0 !important; }
        }
        .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; }
        .dark .custom-scrollbar::-webkit-scrollbar-thumb { background: rgba(255, 255, 255, 0.1); }
      `}</style>
    </div>
  );
}
