'use client';

import React, { useState, useEffect, useCallback, useRef } from 'react';
import { useParent } from '../ParentContext';
import { useTenant } from '../../providers/TenantContext';
import { api } from '@/lib/api';
import { PDFService } from '@/lib/pdf';
import { PDFLayout } from '@/components/PDFLayout';
import { formatDateDDMMYYYY } from '@/lib/date';
import {
  GraduationCap, Calendar, Download, Printer,
  Award, BarChart3, CheckCircle, XCircle, ChevronDown,
  Clock, Info, Trophy, TrendingUp, BookOpen,
} from 'lucide-react';

// ── Helpers ───────────────────────────────────────────────────────────────────
function inr(n: number) { return n.toLocaleString('en-IN'); }

function gradeColor(grade: string): string {
  switch (grade) {
    case 'A+': return 'text-emerald-700 bg-emerald-50 border-emerald-200';
    case 'A':  return 'text-blue-700 bg-blue-50 border-blue-200';
    case 'B+': return 'text-indigo-700 bg-indigo-50 border-indigo-200';
    case 'B':  return 'text-indigo-600 bg-indigo-50 border-indigo-100';
    case 'C':  return 'text-amber-700 bg-amber-50 border-amber-200';
    case 'D':  return 'text-orange-700 bg-orange-50 border-orange-200';
    default:   return 'text-rose-700 bg-rose-50 border-rose-200';
  }
}

// ── Types ─────────────────────────────────────────────────────────────────────
interface SubjectRow {
  id: string;
  subject: string;
  marksObtained: number;
  maxMarks: number;
  percentage: number;
  grade: string;
  gpa: number;
  result: 'PASS' | 'FAIL';
  remarks: string;
}

interface ExamCard {
  examName: string;
  examDate: string;
  rank: number;
  classSize: number;
  totalObtained: number;
  totalMax: number;
  percentage: number;
  overallGrade: string;
  overallGpa: number;
  overallResult: 'PASS' | 'FAIL';
  passingPercentage: number;
  configSource: string;
  subjects: SubjectRow[];
}

interface Schedule {
  id: string;
  examName: string;
  subject: string;
  examDate: string;
  startTime: string;
  endTime: string;
  duration: number;
  examHall: string;
}

// ── Printable Report Card ─────────────────────────────────────────────────────
function PrintableCard({
  card, child, schoolName, logoUrl, printRef,
}: {
  card: ExamCard;
  child: any;
  schoolName: string;
  logoUrl: string | null;
  printRef: React.RefObject<HTMLDivElement>;
}) {
  const gpa = card.overallGpa?.toFixed(1) ?? '—';

  return (
    <div ref={printRef} id={`report-print-${card.examName.replace(/\s+/g, '-')}`} className="w-full bg-white text-slate-800">
      <PDFLayout
        schoolLogo={logoUrl}
        schoolName={schoolName}
        schoolSubtitle="Student Progress Timetable Evaluation"
        reportTitle={`Examination Report Card - ${card.examName}`}
        documentType="report-card"
        metadata={[
          { label: 'Student Name', value: child.name },
          { label: 'Roll Number', value: child.rollNo },
          { label: 'Class & Section', value: `${child.class} – ${child.section}` },
          { label: 'Examination', value: card.examName }
        ]}
        footerText={`Official progress report card statement generated by ${schoolName}. Academic Year 2026–2027.`}
      >
        {/* Marks table */}
        <div className="px-1 py-2">
          <div className="overflow-x-auto rounded-xl border border-slate-200">
            <table className="w-full text-xs">
              <thead>
                <tr className="bg-[#1a2a6c] text-white">
                  {['Subject', 'Max Marks', 'Obtained', 'Grade', '%', 'Result'].map((col, i) => (
                    <th key={col} className={`px-3 py-2.5 font-bold text-[10px] uppercase tracking-wider ${i === 0 ? 'text-left' : 'text-center'} ${i === 0 ? 'rounded-tl-xl' : ''} ${i === 5 ? 'rounded-tr-xl' : ''}`}>
                      {col}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {card.subjects.map((s, idx) => (
                  <tr key={s.id} className={`border-t border-slate-100 hover:bg-blue-50/20 ${idx % 2 === 0 ? 'bg-white' : 'bg-slate-50/40'}`}>
                    <td className="px-3 py-2.5 font-semibold text-slate-700">{s.subject}</td>
                    <td className="px-3 py-2.5 text-center text-slate-500">{s.maxMarks}</td>
                    <td className="px-3 py-2.5 text-center font-black text-slate-800">{s.marksObtained}</td>
                    <td className="px-3 py-2.5 text-center">
                      <span className={`inline-block px-2 py-0.5 rounded-lg border text-[10px] font-bold ${gradeColor(s.grade)}`}>{s.grade}</span>
                    </td>
                    <td className="px-3 py-2.5 text-center text-slate-600 font-semibold">{s.percentage}%</td>
                    <td className="px-3 py-2.5 text-center">
                      <span className={`inline-block px-2 py-0.5 rounded-lg text-[9px] font-bold uppercase ${
                        s.result === 'PASS' ? 'bg-emerald-50 text-emerald-700 border border-emerald-200' : 'bg-rose-50 text-rose-700 border border-rose-200'
                      }`}>{s.result}</span>
                    </td>
                  </tr>
                ))}
              </tbody>
              <tfoot>
                <tr className="border-t-2 border-slate-300 bg-[#f0f4ff]">
                  <td className="px-3 py-2.5 font-black text-slate-800 text-[11px]">TOTAL</td>
                  <td className="px-3 py-2.5 text-center font-black text-slate-700">{card.totalMax}</td>
                  <td className="px-3 py-2.5 text-center font-black text-[#2E5BFF] text-base">{card.totalObtained}</td>
                  <td className="px-3 py-2.5 text-center">
                    <span className={`inline-block px-2 py-0.5 rounded-lg border text-[10px] font-bold ${gradeColor(card.overallGrade)}`}>{card.overallGrade}</span>
                  </td>
                  <td className="px-3 py-2.5 text-center font-black text-slate-800">{card.percentage}%</td>
                  <td className="px-3 py-2.5 text-center">
                    <span className={`inline-block px-2 py-0.5 rounded-lg text-[9px] font-bold uppercase ${
                      card.overallResult === 'PASS' ? 'bg-emerald-50 text-emerald-700 border border-emerald-200' : 'bg-rose-50 text-rose-700 border border-rose-200'
                    }`}>{card.overallResult}</span>
                  </td>
                </tr>
              </tfoot>
            </table>
          </div>
        </div>

        {/* Summary stats */}
        <div className="px-1 py-2 grid grid-cols-2 sm:grid-cols-4 gap-3 break-inside-avoid">
          {[
            { icon: BarChart3, label: 'Total Marks', value: `${card.totalObtained}/${card.totalMax}`, color: 'blue' },
            { icon: TrendingUp, label: 'Percentage', value: `${card.percentage}%`, color: 'indigo' },
            { icon: Trophy, label: 'Class Rank', value: card.classSize > 0 ? `${card.rank} / ${card.classSize}` : '—', color: 'amber' },
            { icon: card.overallResult === 'PASS' ? CheckCircle : XCircle, label: 'Result', value: card.overallResult, color: card.overallResult === 'PASS' ? 'emerald' : 'rose' },
          ].map(({ icon: Icon, label, value, color }) => (
            <div key={label} className={`bg-${color}-50 border border-${color}-200 rounded-2xl p-3 text-center`}>
              <Icon className={`w-4 h-4 text-${color}-600 mx-auto mb-1`} />
              <p className={`text-[9px] text-${color}-500 font-bold uppercase tracking-wider`}>{label}</p>
              <p className={`text-sm font-black text-${color}-800 mt-0.5`}>{value}</p>
            </div>
          ))}
        </div>

        {/* Remarks */}
        {card.subjects.some(s => s.remarks && s.remarks !== 'Good performance') && (
          <div className="px-1 py-2 break-inside-avoid">
            <div className="bg-amber-50 border border-amber-200 rounded-2xl p-3.5">
              <span className="text-[10px] font-bold uppercase tracking-widest text-amber-600 block mb-1.5">Teacher Remarks</span>
              {Array.from(new Set(card.subjects.map(s => s.remarks))).slice(0, 2).map((r, i) => (
                <p key={i} className="text-xs text-amber-800 font-medium italic">"{r}"</p>
              ))}
            </div>
          </div>
        )}

        {/* Signatures */}
        <div className="px-1 py-2 break-inside-avoid">
          <div className="border border-dashed border-slate-300 rounded-2xl p-3.5 grid grid-cols-3 gap-4 text-center">
            {['Class Teacher', 'Principal', 'Parent'].map(sig => (
              <div key={sig}>
                <div className="h-8 border-b border-slate-300" />
                <p className="text-[9px] text-slate-400 font-bold uppercase tracking-wider mt-1">{sig} Signature</p>
              </div>
            ))}
          </div>
        </div>
      </PDFLayout>
    </div>
  );
}

// ── Accordion Card ────────────────────────────────────────────────────────────
function ExamAccordionCard({
  card, child, schoolName, logoUrl, defaultOpen,
}: {
  card: ExamCard;
  child: any;
  schoolName: string;
  logoUrl: string | null;
  defaultOpen: boolean;
}) {
  const [open, setOpen] = useState(defaultOpen);
  const printRef = useRef<HTMLDivElement>(null!);

  const [isGeneratingPDF, setIsGeneratingPDF] = useState(false);

  const handleExportPDF = async () => {
    const content = document.getElementById(`report-print-${card.examName.replace(/\s+/g, '-')}`);
    if (!content) return;

    setIsGeneratingPDF(true);
    try {
      const dateStr = new Date().toISOString().split('T')[0];
      const safeChildName = child.name.replace(/[^a-zA-Z0-9]/g, '_');
      const safeExamName = card.examName.replace(/[^a-zA-Z0-9]/g, '_');
      const filename = `ReportCard_${safeChildName}_${safeExamName}_${dateStr}`;

      await PDFService.export({
        element: content,
        filename,
        documentType: 'report-card',
        metadata: {
          title: `Report Card - ${child.name} - ${card.examName}`,
          author: schoolName,
          subject: 'Progress Evaluation Report',
          keywords: 'Report Card, Grades, Parent Portal',
        },
      });
    } catch (err) {
      console.error('Failed to export parent progress report card:', err);
      alert('Failed to generate PDF. Please try again.');
    } finally {
      setIsGeneratingPDF(false);
    }
  };

  const passCount = card.subjects.filter(s => s.result === 'PASS').length;

  return (
    <div className={`bg-white border rounded-3xl overflow-hidden shadow-sm transition-all ${
      open ? 'border-[#2E5BFF]/30 shadow-blue-500/10' : 'border-slate-200 hover:border-slate-300'
    }`}>
      {/* Accordion Header */}
      <div
        onClick={() => setOpen(!open)}
        className="flex items-center justify-between px-5 py-4 cursor-pointer hover:bg-slate-50/60 transition-colors gap-3"
      >
        <div className="flex items-center gap-3.5 min-w-0 flex-1">
          <div className={`w-9 h-9 rounded-xl flex items-center justify-center shrink-0 ${
            card.overallResult === 'PASS' ? 'bg-emerald-50 border border-emerald-200' : 'bg-rose-50 border border-rose-200'
          }`}>
            {card.overallResult === 'PASS'
              ? <CheckCircle className="w-4.5 h-4.5 text-emerald-600" />
              : <XCircle className="w-4.5 h-4.5 text-rose-600" />}
          </div>

          <div className="min-w-0 flex-1">
            <div className="flex items-center gap-2 flex-wrap">
              <span className="text-sm font-bold text-slate-800">{card.examName}</span>
              <span className={`px-2 py-0.5 rounded-lg text-[9px] font-bold uppercase border ${gradeColor(card.overallGrade)}`}>
                {card.overallGrade}
              </span>
              <span className={`px-2 py-0.5 rounded-lg text-[9px] font-bold uppercase ${
                card.overallResult === 'PASS'
                  ? 'bg-emerald-50 text-emerald-700 border border-emerald-200'
                  : 'bg-rose-50 text-rose-700 border border-rose-200'
              }`}>{card.overallResult}</span>
            </div>
            <p className="text-[10px] text-slate-400 mt-0.5 font-medium">
              {card.percentage}% &nbsp;·&nbsp;
              {passCount}/{card.subjects.length} subjects passed &nbsp;·&nbsp;
              {card.classSize > 0 ? `Rank ${card.rank}/${card.classSize}` : 'Rank N/A'} &nbsp;·&nbsp;
              Pass: ≥{card.passingPercentage}%
            </p>
          </div>
        </div>

        <div className="flex items-center gap-2 shrink-0">
          <span className="text-xs font-black text-[#2E5BFF] hidden sm:block">{card.totalObtained}/{card.totalMax}</span>
          <ChevronDown className={`w-4 h-4 text-slate-400 transition-transform ${open ? 'rotate-180' : ''}`} />
        </div>
      </div>

      {/* Expanded Content */}
      {open && (
        <div className="border-t border-slate-100 bg-slate-50/20">
          {/* Action buttons */}
          <div className="flex items-center gap-2 px-5 pt-4 pb-2">
            <button
              onClick={handleExportPDF}
              disabled={isGeneratingPDF}
              className="px-3 py-1.5 bg-white border border-slate-200 hover:border-slate-350 disabled:opacity-50 text-slate-700 rounded-xl text-xs font-bold flex items-center gap-1.5 transition-all cursor-pointer shadow-sm"
            >
              <Printer className="w-3.5 h-3.5 text-slate-500" />
              <span>{isGeneratingPDF ? 'Generating...' : 'Print Report Card'}</span>
            </button>
            <button
              onClick={handleExportPDF}
              disabled={isGeneratingPDF}
              className="px-3 py-1.5 bg-[#1a2a6c] hover:bg-[#2E5BFF] disabled:opacity-50 text-white rounded-xl text-xs font-bold flex items-center gap-1.5 transition-all shadow-sm cursor-pointer"
            >
              <Download className="w-3.5 h-3.5" />
              <span>{isGeneratingPDF ? 'Downloading...' : 'Download PDF'}</span>
            </button>
          </div>

          {/* Report card content */}
          <div className="px-5 pb-5">
            <PrintableCard
              card={card}
              child={child}
              schoolName={schoolName}
              logoUrl={logoUrl}
              printRef={printRef}
            />
          </div>
        </div>
      )}
    </div>
  );
}

// ── Main Page ─────────────────────────────────────────────────────────────────
export default function ExamsPage() {
  const { selectedChild } = useParent();
  const { schoolName, logoUrl } = useTenant() as any;
  const [examData, setExamData] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState<'REPORT' | 'SCHEDULE'>('REPORT');

  const fetchExams = useCallback(async (childId: string) => {
    try {
      setLoading(true);
      const res = await api.get(`/parent-portal/children/${childId}/exams`);
      setExamData(res.data);
    } catch (err) {
      console.error('Failed to fetch exams data:', err);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    if (selectedChild) fetchExams(selectedChild.id);
  }, [selectedChild, fetchExams]);

  useEffect(() => {
    const handleChildChange = (e: any) => fetchExams(e.detail);
    window.addEventListener('parentChildChanged', handleChildChange);
    return () => window.removeEventListener('parentChildChanged', handleChildChange);
  }, [fetchExams]);

  if (!selectedChild) {
    return <div className="text-slate-500 text-sm text-center py-12">Please select a child to view examinations.</div>;
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[300px]">
        <div className="w-8 h-8 border-4 border-t-[#2E5BFF] border-r-[#2E5BFF] border-b-transparent border-l-transparent rounded-full animate-spin" />
      </div>
    );
  }

  const schedules: Schedule[] = examData?.schedules || [];
  const examCards: ExamCard[] = examData?.exams || [];

  return (
    <div className="space-y-6 max-w-4xl mx-auto animate-fade-in">
      {/* Page header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <h2 className="text-2xl font-extrabold text-slate-900 flex items-center gap-2">
            Exams &amp; Marks: <span className="text-[#2E5BFF]">{selectedChild.name}</span>
          </h2>
          <p className="text-slate-500 text-xs mt-1 font-light">
            Exam-wise report cards with subject scores, grades, class rank, and pass/fail status.
          </p>
        </div>
        <div className="flex bg-white border border-slate-200 p-1 rounded-2xl shrink-0 shadow-sm">
          <button onClick={() => setActiveTab('REPORT')}
            className={`px-4 py-2 rounded-xl text-xs font-bold transition-all cursor-pointer ${activeTab === 'REPORT' ? 'bg-[#2E5BFF] text-white shadow-sm' : 'text-slate-500 hover:text-slate-700 hover:bg-slate-50'}`}>
            Report Cards
          </button>
          <button onClick={() => setActiveTab('SCHEDULE')}
            className={`px-4 py-2 rounded-xl text-xs font-bold transition-all cursor-pointer ${activeTab === 'SCHEDULE' ? 'bg-[#2E5BFF] text-white shadow-sm' : 'text-slate-500 hover:text-slate-700 hover:bg-slate-50'}`}>
            Exam Schedule
          </button>
        </div>
      </div>

      {/* ══ REPORT CARDS TAB ══ */}
      {activeTab === 'REPORT' && (
        <div className="space-y-4">
          {examCards.length === 0 ? (
            <div className="bg-white border border-slate-200 p-16 rounded-3xl shadow-sm text-center space-y-3">
              <GraduationCap className="w-14 h-14 text-slate-200 mx-auto" />
              <p className="text-sm font-semibold text-slate-500">No results published yet.</p>
              <p className="text-xs font-light text-slate-400">Grades will appear here after exams are evaluated by teachers.</p>
            </div>
          ) : (
            <>
              {/* Summary bar */}
              <div className="grid grid-cols-3 gap-3">
                {[
                  { icon: BookOpen, label: 'Exams Completed', value: examCards.length },
                  { icon: CheckCircle, label: 'Overall Passed', value: `${examCards.filter(e => e.overallResult === 'PASS').length}/${examCards.length}` },
                  { icon: Trophy, label: 'Best Rank', value: examCards.length > 0 ? `#${Math.min(...examCards.filter(e => e.classSize > 0).map(e => e.rank))}` : '—' },
                ].map(({ icon: Icon, label, value }) => (
                  <div key={label} className="bg-white border border-slate-200 rounded-2xl p-3.5 flex items-center gap-3 shadow-sm">
                    <div className="w-8 h-8 rounded-xl bg-blue-50 border border-blue-100 flex items-center justify-center shrink-0">
                      <Icon className="w-4 h-4 text-[#2E5BFF]" />
                    </div>
                    <div>
                      <p className="text-[9px] font-bold text-slate-400 uppercase tracking-wider">{label}</p>
                      <p className="text-sm font-black text-slate-800">{value}</p>
                    </div>
                  </div>
                ))}
              </div>

              {/* Accordion cards */}
              <div className="space-y-3">
                {examCards.map((card, idx) => (
                  <ExamAccordionCard
                    key={card.examName}
                    card={card}
                    child={selectedChild}
                    schoolName={schoolName || 'Cambridge International School'}
                    logoUrl={logoUrl || null}
                    defaultOpen={idx === 0}
                  />
                ))}
              </div>
            </>
          )}
        </div>
      )}

      {/* ══ EXAM SCHEDULE TAB ══ */}
      {activeTab === 'SCHEDULE' && (
        <div className="bg-white border border-slate-200 p-6 rounded-3xl shadow-sm space-y-4">
          <h3 className="font-bold text-sm text-slate-800 border-b border-slate-100 pb-2.5 flex items-center gap-2">
            <Calendar className="w-4 h-4 text-[#2E5BFF]" /> Upcoming Exam Schedule
          </h3>

          {schedules.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-16 text-slate-500 text-center">
              <Calendar className="w-12 h-12 text-slate-200 mb-2" />
              <p className="text-sm font-semibold">No upcoming exam schedule.</p>
              <p className="text-xs font-light mt-1">The school has not published any timetables yet.</p>
            </div>
          ) : (
            <div className="overflow-x-auto rounded-2xl border border-slate-200">
              <table className="w-full text-xs">
                <thead>
                  <tr className="bg-[#1a2a6c] text-white">
                    {['Examination', 'Subject', 'Date', 'Time', 'Duration', 'Hall'].map((col, i) => (
                      <th key={col} className={`text-left px-4 py-3 font-bold text-[10px] uppercase tracking-wider ${i === 0 ? 'rounded-tl-2xl' : ''} ${i === 5 ? 'rounded-tr-2xl' : ''}`}>{col}</th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {schedules.map((s, idx) => (
                    <tr key={s.id} className={`border-t border-slate-100 hover:bg-blue-50/30 ${idx % 2 === 0 ? 'bg-white' : 'bg-slate-50/50'}`}>
                      <td className="px-4 py-3 font-bold text-slate-700">{s.examName}</td>
                      <td className="px-4 py-3">
                        <span className="px-2 py-0.5 rounded-lg text-[9px] font-bold bg-blue-50 border border-blue-100 text-blue-700">{s.subject}</span>
                      </td>
                      <td className="px-4 py-3 font-semibold text-slate-600">
                        {formatDateDDMMYYYY(s.examDate)}
                      </td>
                      <td className="px-4 py-3 text-slate-600 flex items-center gap-1">
                        <Clock className="w-3 h-3 text-slate-400 shrink-0" />{s.startTime} – {s.endTime}
                      </td>
                      <td className="px-4 py-3 text-slate-600">{s.duration} min</td>
                      <td className="px-4 py-3">
                        <span className="flex items-center gap-1 text-slate-500">
                          <Info className="w-3 h-3 text-slate-400 shrink-0" />{s.examHall}
                        </span>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
