import React, { useState } from 'react';
import { useCollege } from '../context/CollegeContext';
import {
  Award,
  GraduationCap,
  CalendarCheck,
  CheckCircle2,
  Lock,
  Unlock,
  Printer,
  TrendingUp,
  Search,
  Filter,
  BarChart2,
  Clock,
  AlertTriangle,
} from 'lucide-react';

interface AcademicsViewProps {
  onOpenReportCard: (studentId: string) => void;
  onOpenBankPayment: () => void;
}

export const AcademicsView: React.FC<AcademicsViewProps> = ({
  onOpenReportCard,
  onOpenBankPayment,
}) => {
  const { grades, attendance, fees, currentUser, isResultsLocked, courses } = useCollege();
  const [selectedStudentId, setSelectedStudentId] = useState<string>(
    currentUser.role === 'student' || currentUser.role === 'parent'
      ? currentUser.studentId || 'STC/2026/ICT-108'
      : 'STC/2026/ICT-108'
  );

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

  // Attendance metrics
  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) || 90;

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

  return (
    <div className="space-y-6">
      
      {/* Banner */}
      <div className="bg-slate-900 text-white rounded-2xl p-6 shadow-md border border-slate-800 flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div className="space-y-1">
          <div className="flex items-center gap-2">
            <span className="bg-emerald-500 text-slate-950 font-mono text-[10px] font-bold px-2 py-0.5 rounded uppercase">
              Academic Analytics & Records
            </span>
            <span className="text-xs text-slate-400">July 2026 Semester</span>
          </div>
          <h1 className="text-xl sm:text-2xl font-bold tracking-tight text-white">
            Student Academic Progress & Performance Reports
          </h1>
          <p className="text-xs sm:text-sm text-slate-300">
            Real-time continuous assessments (CATs), laboratory practicals, and examination board marks.
          </p>
        </div>

        {/* Student Selector for Admin/Teacher */}
        {(currentUser.role === 'admin' || currentUser.role === 'teacher') && (
          <div className="bg-slate-800 p-2.5 rounded-xl border border-slate-700">
            <label className="block text-[10px] text-slate-400 font-semibold uppercase mb-0.5">Select Candidate:</label>
            <select
              value={selectedStudentId}
              onChange={e => setSelectedStudentId(e.target.value)}
              className="bg-transparent text-white font-bold text-xs focus:outline-none"
            >
              {fees.map(f => (
                <option key={f.studentId} value={f.studentId} className="bg-slate-900 text-white">
                  {f.studentName} ({f.studentId})
                </option>
              ))}
            </select>
          </div>
        )}
      </div>

      {/* Overview Cards */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
        <div className="bg-white p-4 rounded-xl border border-slate-200 shadow-xs space-y-1">
          <span className="text-xs font-semibold text-slate-500 uppercase tracking-wider block">Cumulative GPA</span>
          <div className="flex items-baseline justify-between">
            <span className="text-2xl font-bold font-mono text-slate-900">
              {lockStatus.isLocked ? 'Restricted' : avgGpa}
            </span>
            <span className="text-[10px] font-bold text-emerald-700 bg-emerald-100 px-2 py-0.5 rounded">
              Scale 4.0
            </span>
          </div>
        </div>

        <div className="bg-white p-4 rounded-xl border border-slate-200 shadow-xs space-y-1">
          <span className="text-xs font-semibold text-slate-500 uppercase tracking-wider block">Attendance Rate</span>
          <div className="flex items-baseline justify-between">
            <span className="text-2xl font-bold font-mono text-slate-900">{attendanceRate}%</span>
            <span className="text-[10px] font-bold text-blue-700 bg-blue-100 px-2 py-0.5 rounded">
              75% Min Req.
            </span>
          </div>
        </div>

        <div className="bg-white p-4 rounded-xl border border-slate-200 shadow-xs space-y-1">
          <span className="text-xs font-semibold text-slate-500 uppercase tracking-wider block">Fee Clearance</span>
          <div className="flex items-baseline justify-between">
            <span className={`text-base font-bold font-mono ${lockStatus.isLocked ? 'text-rose-600' : 'text-emerald-700'}`}>
              {lockStatus.isLocked ? `MK ${lockStatus.balanceDue.toLocaleString()}` : 'Cleared (MK 0)'}
            </span>
            <span className={`text-[10px] font-bold px-1.5 py-0.5 rounded ${
              lockStatus.isLocked ? 'bg-rose-100 text-rose-800' : 'bg-emerald-100 text-emerald-800'
            }`}>
              {lockStatus.isLocked ? 'Locked' : 'Released'}
            </span>
          </div>
        </div>

        <div className="bg-white p-4 rounded-xl border border-slate-200 shadow-xs space-y-1">
          <span className="text-xs font-semibold text-slate-500 uppercase tracking-wider block">Modules Registered</span>
          <div className="flex items-baseline justify-between">
            <span className="text-2xl font-bold font-mono text-slate-900">{studentGrades.length}</span>
            <span className="text-[10px] font-semibold text-slate-600 bg-slate-100 px-2 py-0.5 rounded">
              Accredited
            </span>
          </div>
        </div>
      </div>

      {/* Main Gradebook Container */}
      <div className="bg-white rounded-2xl border border-slate-200 shadow-xs p-6 space-y-5">
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 border-b border-slate-200 pb-4">
          <div>
            <div className="flex items-center gap-2">
              <h2 className="text-base font-bold text-slate-900">
                Gradebook & Continuous Assessment Breakdown
              </h2>
              <span className="font-mono text-xs text-emerald-800 bg-emerald-50 px-2 py-0.5 rounded border border-emerald-200 font-semibold">
                {selectedStudentId}
              </span>
            </div>
            <p className="text-xs text-slate-500">
              Grading Scheme: Coursework (30%) + Midterm (20%) + Practicals (10%) + Final Exam (40%) = 100%
            </p>
          </div>

          <button
            onClick={() => onOpenReportCard(selectedStudentId)}
            className="px-4 py-2 bg-slate-900 hover:bg-slate-800 text-white font-semibold text-xs rounded-lg transition flex items-center gap-2 self-start"
          >
            <Printer className="w-4 h-4 text-emerald-400" />
            Generate Printable Transcript
          </button>
        </div>

        {/* Lock Notice */}
        {lockStatus.isLocked ? (
          <div className="bg-amber-50 border-2 border-amber-400 rounded-xl p-5 text-center space-y-3">
            <div className="w-10 h-10 bg-amber-100 rounded-full flex items-center justify-center mx-auto text-amber-700">
              <Lock className="w-5 h-5" />
            </div>
            <div className="max-w-md mx-auto text-xs space-y-1">
              <strong className="text-amber-950 font-bold block text-sm">
                Official Examination Results Restricted
              </strong>
              <p className="text-slate-600">
                Candidate has an outstanding fee balance of <strong>MK {lockStatus.balanceDue.toLocaleString()}</strong>. Examination transcripts and final grades are locked until accounts clearance is confirmed by the Bursar.
              </p>
            </div>
            <button
              onClick={onOpenBankPayment}
              className="px-4 py-2 bg-emerald-600 hover:bg-emerald-700 text-white font-bold rounded-lg text-xs"
            >
              Deposit / Clear Fee Balance
            </button>
          </div>
        ) : (
          <div className="overflow-x-auto border border-slate-200 rounded-xl">
            <table className="w-full text-left text-xs">
              <thead>
                <tr className="bg-slate-100 text-slate-700 font-semibold border-b border-slate-200">
                  <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 => (
                  <tr key={g.id} className="hover:bg-slate-50">
                    <td className="p-3 font-semibold text-slate-900">
                      {g.subjectName}
                      <span className="text-[10px] text-slate-500 block font-normal">{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-900">{g.totalScore}%</td>
                    <td className="p-3 text-center">
                      <span className="px-2 py-0.5 rounded font-bold text-xs bg-emerald-100 text-emerald-900 border border-emerald-300">
                        {g.letterGrade}
                      </span>
                    </td>
                    <td className="p-3 text-center font-mono font-semibold">{g.gpa.toFixed(2)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* Attendance History Section */}
      <div className="bg-white rounded-2xl border border-slate-200 shadow-xs p-6 space-y-4">
        <h2 className="text-base font-bold text-slate-900">
          Class Attendance & Workshop Participation Logs
        </h2>

        <div className="border border-slate-200 rounded-xl overflow-hidden text-xs">
          <table className="w-full text-left">
            <thead>
              <tr className="bg-slate-100 text-slate-700 font-semibold border-b border-slate-200">
                <th className="p-3">Date</th>
                <th className="p-3">Workshop / Session Topic</th>
                <th className="p-3">Lecturer</th>
                <th className="p-3">Status</th>
                <th className="p-3">Guardian Notice</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-200">
              {studentAttendance.map(att => (
                <tr key={att.id} className="hover:bg-slate-50">
                  <td className="p-3 font-mono text-slate-900">{att.date}</td>
                  <td className="p-3 font-medium text-slate-800">{att.sessionName}</td>
                  <td className="p-3 text-slate-600">{att.markedBy}</td>
                  <td className="p-3">
                    <span className={`px-2.5 py-0.5 rounded text-[10px] font-bold ${
                      att.status === 'Present'
                        ? 'bg-emerald-100 text-emerald-900'
                        : att.status === 'Late'
                        ? 'bg-amber-100 text-amber-900'
                        : 'bg-rose-100 text-rose-900'
                    }`}>
                      {att.status}
                    </span>
                  </td>
                  <td className="p-3 text-slate-500 font-mono text-[10px]">
                    {att.alertSentToParent ? 'Alert Dispatched' : 'Standard Log'}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
};
