import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import api, { useAuthStore } from '../../store/auth';
import { useExamStore } from '../../store/exams';
import { GradeBadge } from '../../components/GradeBadge';
import {
  RefreshCw, ChevronRight,
  Clock, FileText,
  Calendar, MapPin, Printer, ShieldCheck,
  ClipboardList, Download,
} from 'lucide-react';

interface SubjectGrade {
  subject: string;
  average: number;
  letterGrade: string;
}

interface AvailableExam {
  id: number | string;
  exam_name: string;
  subject_name?: string;
  duration_minutes: number;
  attempts_taken: number;
  max_attempts: number;
  start_time?: string;
  venue?: string;
}

export default function Exams() {
  const navigate = useNavigate();
  const { user } = useAuthStore();
  const [subjectGrades, setSubjectGrades] = useState<SubjectGrade[]>([]);
  const [loading, setLoading] = useState(true);

  const { availableExams, fetchAvailableExams } = useExamStore();

  useEffect(() => {
    loadExamData();
    // fetchAvailableExams is a Zustand action that triggers its own axios call;
    // swallow the rejection so a flaky offline boot doesn't surface an unhandled
    // promise error alongside the rest of the page's resilience.
    fetchAvailableExams().catch(() => {});
  }, []);

  const loadExamData = async () => {
    setLoading(true);
    try {
      const gradesRes = await api.get('/students/grades').catch(() => ({ data: { subjects: [] } }));
      const subjects = gradesRes?.data?.subjects;
      setSubjectGrades(Array.isArray(subjects) ? subjects : []);
    } catch (error) {
      setSubjectGrades([]);
    } finally {
      setLoading(false);
    }
  };

  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]">Accessing Exam Registry...</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">
              <ClipboardList size={20} />
            </div>
            <span className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted">Examination Control</span>
          </div>
          <h1 className="text-4xl font-black text-text tracking-tighter">Exam Portal</h1>
          <p className="text-text-muted text-lg font-medium">Access your official examinations and certified transcripts.</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.print()}>
            <Printer size={18} />
            Print Schedule
          </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={loadExamData}>
            <RefreshCw size={18} />
            Sync Portal
          </button>
        </div>
      </div>

      <div className="space-y-10 animate-in slide-in-from-bottom-4 duration-500">
          {/* Exam Portal Content */}
          <div className="grid grid-cols-1 lg:grid-cols-12 gap-10">

              {/* Exam Timetable (7/12) */}
              <div className="lg:col-span-7 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">
                              <Calendar size={20} />
                          </div>
                          <h3 className="text-xl font-black text-text tracking-tight uppercase">Exam Timetable</h3>
                      </div>
                      <span className="text-[0.65rem] font-bold text-text-muted uppercase tracking-widest">{availableExams.length} Scheduled Sessions</span>
                  </div>

                  <div className="space-y-4">
                      {availableExams.length === 0 ? (
                          <div className="py-24 text-center bg-card border-2 border-dashed border-border rounded-[3rem]">
                              <ClipboardList size={64} className="mx-auto text-text-muted/20 mb-6" />
                              <h4 className="text-xl font-black text-text mb-2">No Active Exam Sessions</h4>
                              <p className="text-text-muted font-medium max-w-xs mx-auto text-sm">You have no upcoming examinations scheduled in the registry for this period.</p>
                          </div>
                      ) : (availableExams as AvailableExam[]).map((exam) => (
                          <div key={exam.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">
                              <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="flex flex-col md:flex-row justify-between items-start md:items-center gap-6 relative z-10">
                                  <div className="flex items-start gap-6">
                                      <div className="w-16 h-16 rounded-[1.5rem] bg-slate-900 border border-slate-800 flex flex-col items-center justify-center text-white shadow-xl group-hover:scale-105 transition-transform">
                                          <span className="text-sm font-black text-blue-400">{exam.duration_minutes}</span>
                                          <span className="text-[0.55rem] font-black uppercase tracking-tighter opacity-60">MINS</span>
                                      </div>
                                      <div>
                                          <h4 className="text-xl font-black text-text group-hover:text-primary transition-colors">{exam.exam_name}</h4>
                                          <p className="text-[0.65rem] font-black text-primary uppercase tracking-[3px] mt-1">{exam.subject_name || 'General Curriculum'}</p>
                                          <div className="flex items-center gap-6 mt-4">
                                              <div className="flex items-center gap-2 text-[0.7rem] font-bold text-text-muted uppercase tracking-widest">
                                                  <Clock size={14} className="text-text-muted/50" /> {exam.start_time?.trim() ? exam.start_time : '—'}
                                              </div>
                                              <div className="flex items-center gap-2 text-[0.7rem] font-bold text-text-muted uppercase tracking-widest">
                                                  <MapPin size={14} className="text-text-muted/50" /> {exam.venue?.trim() ? exam.venue : '—'}
                                              </div>
                                          </div>
                                      </div>
                                  </div>
                                  <div className="w-full md:w-auto flex flex-col items-end gap-2">
                                      <span className={`px-3 py-1 rounded-lg border text-[0.6rem] font-black uppercase tracking-widest ${
                                        exam.attempts_taken >= exam.max_attempts
                                        ? 'bg-emerald-50 dark:bg-emerald-900/20 text-emerald-600 dark:text-emerald-400 border-emerald-100 dark:border-emerald-800'
                                        : 'bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 border-blue-100 dark:border-blue-800'
                                      }`}>
                                          {exam.attempts_taken >= exam.max_attempts ? 'Completed' : 'Upcoming'}
                                      </span>
                                      <button onClick={() => navigate('/exams')} className="flex items-center gap-2 bg-primary hover:bg-primary-dark text-white px-6 py-3 rounded-2xl font-black text-[0.65rem] uppercase tracking-widest transition-all shadow-lg active:scale-95 group/btn">
                                          Session Details <ChevronRight size={16} className="group-hover/btn:translate-x-1 transition-transform" />
                                      </button>
                                  </div>
                              </div>
                          </div>
                      ))}
                  </div>
              </div>

              {/* School Report Card — links out to the same /student/report-card
                  page used by Grades.tsx so the report card has a single
                  source of truth (the dynamic school branding, the typed
                  per-subject splits, and the print/PDF flow all live in
                  one component). The card body carries a per-subject
                  summary of the term's results so the student can scan
                  their standing without opening the full report.
                  GPA removed — Zim grading is percentage + letter symbol. */}
              <div className="lg:col-span-5 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">
                              <FileText size={20} />
                          </div>
                          <h3 className="text-xl font-black text-text tracking-tight uppercase">School Report</h3>
                      </div>
                  </div>

                  <div className="bg-card border border-border rounded-[3rem] p-10 shadow-2xl relative overflow-hidden flex flex-col group min-h-[600px]">
                      <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-30"></div>
                      <div className="text-center space-y-3 mb-10">
                          <div className="w-20 h-20 bg-slate-900 rounded-[1.5rem] flex items-center justify-center text-white mx-auto shadow-xl">
                              <ShieldCheck size={40} />
                          </div>
                          <h4 className="text-xl font-black text-text tracking-tighter">Compiled Report Card</h4>
                          <p className="text-[0.6rem] font-black uppercase tracking-[3px] text-text-muted">Term Marks · Continuous Assessment · Exam</p>
                      </div>
                      <div className="bg-muted/50 border border-border rounded-3xl p-6 mb-8 grid grid-cols-2 gap-4">
                          <div>
                              <p className="text-[0.55rem] font-black text-text-muted uppercase tracking-widest">Student Name</p>
                              <p className="text-[0.85rem] font-bold text-text uppercase truncate">{user?.first_name} {user?.last_name}</p>
                          </div>
                          <div className="text-right">
                              <p className="text-[0.55rem] font-black text-text-muted uppercase tracking-widest">Academic Year</p>
                              <p className="text-[0.85rem] font-bold text-text">2024-2025</p>
                          </div>
                      </div>
                      <div className="flex-1 space-y-1 min-h-0">
                          <div className="flex items-center px-4 py-2 border-b border-border text-[0.55rem] font-black uppercase tracking-[2px] text-text-muted">
                              <span className="flex-1 text-left">Subject</span>
                              <span className="w-16 text-center">Average</span>
                              <span className="w-12 text-right">Grade</span>
                          </div>
                          {subjectGrades.length === 0 ? (
                              <div className="py-16 px-4 text-center">
                                  <FileText size={40} className="mx-auto text-text-muted/20 mb-3" />
                                  <p className="text-[0.75rem] font-black uppercase tracking-[2px] text-text-muted">No grades recorded yet</p>
                                  <p className="text-[0.65rem] font-bold text-text-muted/70 mt-1">Your verified entries will appear here once published.</p>
                              </div>
                          ) : (
                              <div className="divide-y divide-border max-h-[300px] overflow-y-auto custom-scrollbar pr-2">
                                  {subjectGrades.map(sg => (
                                      <div key={sg.subject} className="flex items-center px-4 py-4 hover:bg-muted/30 transition-colors">
                                          <div className="flex-1 min-w-0">
                                              <p className="text-[0.8rem] font-black text-text truncate">{sg.subject}</p>
                                              <p className="text-[0.55rem] font-bold text-text-muted uppercase tracking-tighter">Verified Entry</p>
                                          </div>
                                          <span className="w-16 text-center text-[0.85rem] font-black text-text-secondary">{Math.round(sg.average)}%</span>
                                          <span className="ml-2">
                                            <GradeBadge
                                              percentage={sg.average}
                                              gradingScale={(sg as any).grading_scale ?? null}
                                              band={(sg as any).resolved_scale ? {
                                                letter: sg.letterGrade,
                                                scale: { key: (sg as any).resolved_scale, label: '' },
                                              } : null}
                                              size="sm"
                                              hidePercentage
                                            />
                                          </span>
                                      </div>
                                  ))}
                              </div>
                          )}
                      </div>
                      <div className="mt-8 pt-8 border-t-2 border-dashed border-border">
                          <button
                              onClick={() => window.open('/student/report-card', 'ReportCard', 'width=900,height=1100,menubar=no,toolbar=no,location=no,status=no')}
                              className="w-full py-4 bg-primary hover:bg-primary-dark text-white rounded-2xl font-black text-[0.65rem] uppercase tracking-[3px] transition-all shadow-xl active:scale-95 flex items-center justify-center gap-3"
                          >
                              <Download size={16} /> Open Report Card
                          </button>
                      </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>
  );
}
