import React from 'react';
import { useCollege } from '../context/CollegeContext';
import {
  X,
  Printer,
  GraduationCap,
  CheckCircle2,
  Lock,
  CreditCard,
  Building,
  Award,
  Calendar,
  FileText,
  AlertTriangle,
} from 'lucide-react';

interface ReportCardModalProps {
  isOpen: boolean;
  onClose: () => void;
  studentId: string;
  onOpenBankPayment?: () => void;
}

export const ReportCardModal: React.FC<ReportCardModalProps> = ({
  isOpen,
  onClose,
  studentId,
  onOpenBankPayment,
}) => {
  const { grades, attendance, applications, fees, isResultsLocked } = useCollege();

  if (!isOpen) return null;

  const lockStatus = isResultsLocked(studentId);
  const studentGrades = grades.filter(g => g.studentId === studentId);
  const studentAttendance = attendance.filter(a => a.studentId === studentId);
  const studentApp = applications.find(a => a.assignedStudentId === studentId);
  const studentFee = fees.find(f => f.studentId === studentId);

  // Compute attendance stats
  const totalSessions = studentAttendance.length || 1;
  const presentCount = studentAttendance.filter(a => a.status === 'Present').length;
  const lateCount = studentAttendance.filter(a => a.status === 'Late').length;
  const attendanceRate = Math.round(((presentCount + lateCount * 0.7) / totalSessions) * 100) || 92;

  // Compute GPA
  const totalGpaPoints = studentGrades.reduce((sum, g) => sum + g.gpa, 0);
  const averageGpa = studentGrades.length > 0 ? (totalGpaPoints / studentGrades.length).toFixed(2) : '3.80';

  const studentName = studentApp
    ? `${studentApp.firstNames} ${studentApp.surname}`
    : studentFee?.studentName || 'Student Candidate';
  const courseName = studentFee?.courseName || 'Diploma in Technical Education';

  return (
    <div className="fixed inset-0 z-50 bg-black/70 backdrop-blur-sm flex items-center justify-center p-2 sm:p-4 overflow-y-auto">
      <div className="bg-white rounded-2xl shadow-2xl max-w-4xl w-full max-h-[92vh] flex flex-col overflow-hidden border border-slate-200 animate-in fade-in zoom-in-95">
        
        {/* Modal Top Bar */}
        <div className="bg-slate-900 text-white px-6 py-4 flex items-center justify-between border-b border-slate-800 shrink-0">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-lg bg-emerald-600 border border-emerald-400 flex items-center justify-center font-bold text-white shadow-sm">
              <Award className="w-5 h-5" />
            </div>
            <div>
              <h2 className="text-base font-bold tracking-tight text-white leading-tight">
                Official Academic Progress Report & Transcript
              </h2>
              <p className="text-xs text-emerald-400 font-mono">
                SOCHE TECHNICAL COLLEGE • LIMBE, MALAWI
              </p>
            </div>
          </div>
          <button
            onClick={onClose}
            aria-label="Close modal"
            className="p-1.5 text-slate-400 hover:text-white hover:bg-slate-800 rounded-lg transition"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Modal Body */}
        <div className="flex-1 overflow-y-auto p-4 sm:p-6 space-y-6">
          
          {/* FEE LOCK RESTRICTION BANNER */}
          {lockStatus.isLocked ? (
            <div className="bg-amber-50 border-2 border-amber-400 rounded-2xl p-6 text-center space-y-4 shadow-sm animate-in fade-in">
              <div className="w-14 h-14 bg-amber-100 rounded-full flex items-center justify-center mx-auto text-amber-700 border border-amber-300">
                <Lock className="w-7 h-7" />
              </div>
              <div className="max-w-xl mx-auto space-y-2">
                <h3 className="text-lg font-bold text-amber-950">
                  Examination Results Restricted — Outstanding Fee Balance
                </h3>
                <p className="text-xs sm:text-sm text-slate-700 leading-relaxed">
                  In accordance with Soche Technical College academic regulations, official semester examination results and transcripts can only be accessed once tuition and boarding fees are fully settled.
                </p>
                
                <div className="bg-white p-4 rounded-xl border border-amber-300 text-left text-xs space-y-2 font-sans">
                  <div className="flex justify-between items-center pb-2 border-b border-slate-200">
                    <span className="text-slate-600">Student Name:</span>
                    <strong className="text-slate-900">{studentName} ({studentId})</strong>
                  </div>
                  <div className="flex justify-between items-center pb-2 border-b border-slate-200">
                    <span className="text-slate-600">Outstanding Balance:</span>
                    <strong className="text-rose-600 font-mono text-sm">
                      MK {lockStatus.balanceDue.toLocaleString()} MWK
                    </strong>
                  </div>
                  <div className="flex justify-between items-center text-[11px] text-slate-500">
                    <span>Payment Account:</span>
                    <span className="font-mono font-semibold text-slate-800">
                      National Bank (Customs Road) #1003452219
                    </span>
                  </div>
                </div>
              </div>

              <div className="flex flex-wrap items-center justify-center gap-3 pt-2">
                {onOpenBankPayment && (
                  <button
                    onClick={() => {
                      onClose();
                      onOpenBankPayment();
                    }}
                    className="px-5 py-2.5 bg-emerald-600 hover:bg-emerald-700 text-white text-xs font-bold rounded-lg transition shadow flex items-center gap-2"
                  >
                    <CreditCard className="w-4 h-4" />
                    Submit Bank Deposit Slip to Clear Balance
                  </button>
                )}
              </div>
            </div>
          ) : (
            /* OFFICIAL UNLOCKED REPORT CARD */
            <div className="space-y-6 animate-in fade-in">
              <div className="flex justify-end gap-2">
                <button
                  onClick={() => window.print()}
                  className="inline-flex items-center gap-1.5 bg-slate-900 hover:bg-slate-800 text-white text-xs font-semibold px-4 py-2 rounded-lg transition shadow-sm"
                >
                  <Printer className="w-4 h-4" />
                  Print Official Transcript
                </button>
              </div>

              {/* Printable Document Container */}
              <div className="border-2 border-slate-300 rounded-xl p-6 sm:p-8 bg-white shadow-sm font-sans space-y-6 text-slate-900">
                
                {/* College Header */}
                <div className="border-b-2 border-slate-900 pb-5 text-center space-y-1">
                  <div className="text-[11px] font-serif text-slate-500 uppercase tracking-widest">
                    Government of Malawi • Ministry of Labour & Manpower Development
                  </div>
                  <h1 className="text-2xl sm:text-3xl font-bold tracking-tight text-slate-900 font-serif">
                    SOCHE TECHNICAL COLLEGE
                  </h1>
                  <p className="text-xs text-slate-600 font-medium">
                    Private Bag 515, Limbe, Malawi • Tel: +265 1 845 384 • Email: principal@sochetech.org
                  </p>
                  <div className="mt-2 inline-block bg-slate-900 text-white text-xs font-bold px-4 py-1 rounded uppercase tracking-wider">
                    Official Student Academic Progress Report Card
                  </div>
                </div>

                {/* Student Info Meta Grid */}
                <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-3 p-3 bg-slate-50 border border-slate-200 rounded-lg text-xs">
                  <div>
                    <span className="text-slate-500 block">Student Name:</span>
                    <strong className="text-slate-900">{studentName}</strong>
                  </div>
                  <div>
                    <span className="text-slate-500 block">Student ID:</span>
                    <strong className="font-mono text-emerald-700">{studentId}</strong>
                  </div>
                  <div>
                    <span className="text-slate-500 block">Course / Program:</span>
                    <strong className="text-slate-900">{courseName}</strong>
                  </div>
                  <div>
                    <span className="text-slate-500 block">Academic Period:</span>
                    <strong className="text-slate-900">Semester 1 (July 2026)</strong>
                  </div>
                </div>

                {/* Performance Summary Metrics */}
                <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 text-center">
                  <div className="p-3 bg-emerald-50 border border-emerald-200 rounded-lg">
                    <span className="text-[11px] font-bold text-emerald-800 uppercase block">Cumulative GPA</span>
                    <span className="text-2xl font-bold font-mono text-emerald-950">{averageGpa}</span>
                    <span className="text-[10px] text-emerald-700 block">Scale of 4.0</span>
                  </div>

                  <div className="p-3 bg-blue-50 border border-blue-200 rounded-lg">
                    <span className="text-[11px] font-bold text-blue-800 uppercase block">Attendance Rate</span>
                    <span className="text-2xl font-bold font-mono text-blue-950">{attendanceRate}%</span>
                    <span className="text-[10px] text-blue-700 block">Minimum 75% required</span>
                  </div>

                  <div className="p-3 bg-amber-50 border border-amber-200 rounded-lg">
                    <span className="text-[11px] font-bold text-amber-800 uppercase block">Standing</span>
                    <span className="text-base font-bold text-amber-950 block mt-1">
                      {Number(averageGpa) >= 3.6 ? 'Distinction' : Number(averageGpa) >= 3.0 ? 'Credit' : 'Pass'}
                    </span>
                    <span className="text-[10px] text-amber-700 block">Good Standing</span>
                  </div>

                  <div className="p-3 bg-purple-50 border border-purple-200 rounded-lg">
                    <span className="text-[11px] font-bold text-purple-800 uppercase block">Accounts Clearance</span>
                    <span className="text-xs font-bold text-purple-900 flex items-center justify-center gap-1 mt-2">
                      <CheckCircle2 className="w-4 h-4 text-purple-700" />
                      100% Cleared
                    </span>
                    <span className="text-[10px] text-purple-700 block">Verified by Bursar</span>
                  </div>
                </div>

                {/* Grades Table */}
                <div className="overflow-x-auto border border-slate-300 rounded-lg">
                  <table className="w-full text-left text-xs border-collapse">
                    <thead>
                      <tr className="bg-slate-800 text-white font-semibold">
                        <th className="p-3">Course / Module Title</th>
                        <th className="p-3 text-center">Board</th>
                        <th className="p-3 text-center">Coursework (30%)</th>
                        <th className="p-3 text-center">Midterm (20%)</th>
                        <th className="p-3 text-center">Practicals (10%)</th>
                        <th className="p-3 text-center">Exam (40%)</th>
                        <th className="p-3 text-center">Total (100)</th>
                        <th className="p-3 text-center">Grade</th>
                        <th className="p-3 text-center">GPA</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-slate-200">
                      {studentGrades.map((g, idx) => (
                        <tr key={idx} className="hover:bg-slate-50">
                          <td className="p-3 font-medium text-slate-900">
                            {g.subjectName}
                            <span className="text-[10px] text-slate-500 block">{g.remarks}</span>
                          </td>
                          <td className="p-3 text-center font-mono text-[11px]">{g.examBoard}</td>
                          <td className="p-3 text-center font-mono">{g.courseworkScore}/30</td>
                          <td className="p-3 text-center font-mono">{g.midtermScore}/20</td>
                          <td className="p-3 text-center font-mono">{g.practicalScore}/10</td>
                          <td className="p-3 text-center font-mono">{g.finalExamScore}/40</td>
                          <td className="p-3 text-center font-mono font-bold text-slate-950">
                            {g.totalScore}%
                          </td>
                          <td className="p-3 text-center">
                            <span className="px-2 py-0.5 rounded font-bold bg-emerald-100 text-emerald-900 border border-emerald-300 text-xs">
                              {g.letterGrade}
                            </span>
                          </td>
                          <td className="p-3 text-center font-mono font-semibold">{g.gpa.toFixed(2)}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>

                {/* Grading Scale & Legend */}
                <div className="bg-slate-50 p-3 rounded-lg border border-slate-200 text-[11px] text-slate-600 flex flex-wrap items-center justify-between gap-2">
                  <span><strong>Grading Key:</strong> A+ (85-100% | 4.0), A (80-84% | 3.75), B+ (75-79% | 3.3), B (70-74% | 3.0), C (60-69% | 2.5), D (50-59% | 2.0), F (&lt;50% | Fail)</span>
                </div>

                {/* Signatures & Seal Box */}
                <div className="grid grid-cols-1 sm:grid-cols-3 gap-6 pt-4 border-t-2 border-slate-800 text-xs">
                  <div className="text-center space-y-1">
                    <div className="h-10 flex items-end justify-center font-serif italic text-slate-700">
                      Eng. Patrick Chisale
                    </div>
                    <div className="border-t border-slate-400 pt-1 font-semibold text-slate-800">
                      Head of Department / Lecturer
                    </div>
                  </div>

                  <div className="text-center space-y-1">
                    <div className="h-10 flex items-end justify-center font-serif italic text-slate-700">
                      Mr. T. Mweghama
                    </div>
                    <div className="border-t border-slate-400 pt-1 font-semibold text-slate-800">
                      Accounts Officer & Bursar
                    </div>
                  </div>

                  <div className="text-center space-y-1">
                    <div className="h-10 flex items-end justify-center font-serif italic text-emerald-800 font-bold">
                      Dr. Eddie Njunga
                    </div>
                    <div className="border-t border-slate-400 pt-1 font-semibold text-slate-800">
                      College Principal & Registrar
                    </div>
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};
