import React, { useState, useEffect } from 'react';
import QRCode from 'qrcode';
import { useCollege } from '../context/CollegeContext';
import {
  GraduationCap,
  Award,
  CalendarCheck,
  CreditCard,
  BookOpen,
  Lock,
  Unlock,
  CheckCircle2,
  AlertTriangle,
  Upload,
  Download,
  FileText,
  FileCheck,
  Clock,
  Printer,
  ChevronRight,
  TrendingUp,
  QrCode,
  ShieldCheck,
  UserCheck,
  Camera,
  ExternalLink,
  Sparkles,
} from 'lucide-react';
import confetti from 'canvas-confetti';
import { StudentIDCardModal } from '../components/StudentIDCardModal';

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

export const StudentDashboard: React.FC<StudentDashboardProps> = ({
  onOpenBankPayment,
  onOpenReportCard,
  onOpenCalendarSync,
}) => {
  const {
    currentUser,
    grades,
    attendance,
    fees,
    assignments,
    studyMaterials,
    isResultsLocked,
    submitAssignmentWork,
  } = useCollege();

  const studentId = currentUser.studentId || 'STC/2026/ICT-108';
  const lockStatus = isResultsLocked(studentId);
  const studentFee = fees.find(f => f.studentId === studentId);
  const studentGrades = grades.filter(g => g.studentId === studentId);
  const studentAttendance = attendance.filter(a => a.studentId === studentId);

  // Digital Student ID Modal State
  const [isIdModalOpen, setIsIdModalOpen] = useState(false);
  const [dashQrDataUrl, setDashQrDataUrl] = useState<string>('');

  // Generate Dash QR thumbnail
  useEffect(() => {
    const payload = {
      institution: 'Soche Technical College',
      studentId: studentId,
      studentName: currentUser.name,
      intake: 'July - December 2026 Intake',
      course: studentFee?.courseName || currentUser.title || 'ICT - Systems Support',
      clearance: lockStatus.isLocked ? 'Pending Balance' : '100% Cleared',
      verified: true,
    };
    QRCode.toDataURL(
      JSON.stringify(payload),
      {
        errorCorrectionLevel: 'M',
        margin: 1,
        width: 140,
        color: { dark: '#0f172a', light: '#ffffff' },
      },
      (err, url) => {
        if (!err && url) {
          setDashQrDataUrl(url);
        }
      }
    );
  }, [studentId, currentUser.name, studentFee, lockStatus.isLocked]);

  // Submissions State
  const [submittingAsnId, setSubmittingAsnId] = useState<string | null>(null);
  const [asnFileName, setAsnFileName] = useState('');
  const [asnNotes, setAsnNotes] = useState('');

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

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

  const handleUploadAssignment = (asnId: string) => {
    if (!asnFileName) {
      alert('Please specify the assignment file name.');
      return;
    }
    submitAssignmentWork(asnId, {
      fileName: asnFileName,
      fileSize: '3.2 MB',
      notes: asnNotes || 'Completed practical task.',
    });
    setSubmittingAsnId(null);
    setAsnFileName('');
    setAsnNotes('');
    try {
      confetti({ particleCount: 40, spread: 60 });
    } catch (e) {}
  };

  return (
    <div className="space-y-6">
      
      {/* Student Profile & Status 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="flex items-center gap-4">
          <img
            src={currentUser.avatarUrl || 'https://images.unsplash.com/photo-1539571696357-5a69c17a67c6?w=150&auto=format&fit=crop&q=80'}
            alt={currentUser.name}
            className="w-14 h-14 rounded-full object-cover border-2 border-emerald-400"
          />
          <div>
            <div className="flex items-center gap-2">
              <span className="bg-emerald-600 text-white font-mono text-[10px] font-bold px-2 py-0.5 rounded">
                {studentId}
              </span>
              <span className="text-xs text-slate-400 font-medium">July – December 2026 Intake</span>
            </div>
            <h1 className="text-xl sm:text-2xl font-bold tracking-tight text-white">{currentUser.name}</h1>
            <p className="text-xs text-slate-300">{currentUser.title || studentFee?.courseName || 'Technical Education Candidate'}</p>
          </div>
        </div>

        <div className="flex flex-wrap items-center gap-2.5">
          <button
            onClick={() => setIsIdModalOpen(true)}
            className="px-4 py-2 bg-emerald-500 hover:bg-emerald-400 text-slate-950 text-xs font-bold rounded-lg transition shadow flex items-center gap-1.5"
          >
            <QrCode className="w-4 h-4" />
            Digital Student ID & QR
          </button>

          <button
            onClick={onOpenBankPayment}
            className="px-4 py-2 bg-amber-500 hover:bg-amber-600 text-slate-950 text-xs font-bold rounded-lg transition shadow flex items-center gap-1.5"
          >
            <CreditCard className="w-4 h-4" />
            Bank Fee Portal
          </button>
          
          <button
            onClick={() => onOpenReportCard(studentId)}
            className="px-4 py-2 bg-slate-800 hover:bg-slate-700 text-white text-xs font-bold rounded-lg border border-slate-700 transition shadow flex items-center gap-1.5"
          >
            <Award className="w-4 h-4 text-emerald-400" />
            Official Report Card
          </button>
        </div>
      </div>

      {/* DIGITAL STUDENT IDENTIFICATION & QR PASS WIDGET */}
      <div className="bg-gradient-to-r from-slate-900 via-slate-800 to-slate-900 text-white rounded-2xl p-5 shadow-md border border-slate-700 relative overflow-hidden">
        <div className="absolute top-0 right-0 w-80 h-80 bg-emerald-500/10 rounded-full blur-3xl pointer-events-none" />
        
        <div className="flex flex-col md:flex-row items-start md:items-center justify-between gap-5 relative z-10">
          
          {/* Student Photo & Identity Data */}
          <div className="flex items-center gap-4">
            <div className="relative group shrink-0">
              <img
                src={currentUser.avatarUrl || 'https://images.unsplash.com/photo-1539571696357-5a69c17a67c6?w=150&auto=format&fit=crop&q=80'}
                alt={currentUser.name}
                className="w-16 h-16 sm:w-20 sm:h-20 rounded-2xl object-cover border-2 border-emerald-400 shadow-md"
              />
              <div className="absolute -bottom-1 -right-1 bg-emerald-500 text-slate-950 p-1 rounded-full shadow">
                <ShieldCheck className="w-3.5 h-3.5" />
              </div>
            </div>

            <div className="space-y-1">
              <div className="flex flex-wrap items-center gap-2">
                <span className="bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 text-[10px] font-bold px-2 py-0.5 rounded-full uppercase tracking-wider">
                  Verified Student ID
                </span>
                <span className={`text-[10px] font-bold px-2 py-0.5 rounded-full ${
                  lockStatus.isLocked ? 'bg-amber-500/20 text-amber-300 border border-amber-500/30' : 'bg-emerald-500 text-slate-950'
                }`}>
                  {lockStatus.isLocked ? 'Provisional • Fee Balance Pending' : 'Officially Registered & Cleared'}
                </span>
              </div>
              <h3 className="text-base sm:text-lg font-bold text-white tracking-tight flex items-center gap-2">
                {currentUser.name}
                <span className="font-mono text-xs text-slate-400 font-normal">({studentId})</span>
              </h3>
              <p className="text-xs text-slate-300">
                {currentUser.title || studentFee?.courseName || 'ICT - Systems Support (City and Guilds)'}
              </p>
              <div className="flex items-center gap-3 text-[11px] text-slate-400 font-mono pt-0.5">
                <span>Intake: July – Dec 2026</span>
                <span>•</span>
                <span>National Bank A/C: 1003452219</span>
              </div>
            </div>
          </div>

          {/* QR Code & Actions */}
          <div className="flex items-center gap-4 bg-slate-950/60 p-3 rounded-xl border border-slate-700/80 w-full md:w-auto justify-between md:justify-start">
            <div className="bg-white p-1.5 rounded-lg shadow shrink-0">
              {dashQrDataUrl ? (
                <img
                  src={dashQrDataUrl}
                  alt="Student ID QR Code"
                  className="w-16 h-16 object-contain"
                />
              ) : (
                <div className="w-16 h-16 bg-slate-100 flex items-center justify-center animate-pulse">
                  <QrCode className="w-6 h-6 text-slate-400" />
                </div>
              )}
            </div>

            <div className="space-y-1.5 pr-2">
              <span className="text-[10px] font-bold text-emerald-400 uppercase tracking-wide block">
                Digital Campus Pass
              </span>
              <p className="text-[11px] text-slate-300 leading-tight">
                Scan for library, exam hall, and gate entry clearance.
              </p>
              <button
                onClick={() => setIsIdModalOpen(true)}
                className="px-3 py-1 bg-emerald-600 hover:bg-emerald-500 text-white font-bold text-xs rounded-lg transition shadow-xs flex items-center gap-1.5"
              >
                <ExternalLink className="w-3.5 h-3.5" />
                <span>View Full ID Pass</span>
              </button>
            </div>
          </div>

        </div>
      </div>

      {/* Snapshot 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">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] text-emerald-700 bg-emerald-100 px-2 py-0.5 rounded font-bold">
              {attendanceRate >= 75 ? 'Qualified' : 'Warning'}
            </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">Academic Standing</span>
          <div className="flex items-baseline justify-between">
            <span className="text-2xl font-bold font-mono text-slate-900">
              {lockStatus.isLocked ? 'Locked' : avgGpa}
            </span>
            <span className="text-[10px] text-blue-700 bg-blue-100 px-2 py-0.5 rounded font-bold">
              {lockStatus.isLocked ? 'Fee Due' : 'Distinction'}
            </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">Tuition Status</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] px-1.5 py-0.5 rounded font-bold ${
              lockStatus.isLocked ? 'bg-rose-100 text-rose-800' : 'bg-emerald-100 text-emerald-800'
            }`}>
              {lockStatus.isLocked ? '30% Due' : 'Paid 100%'}
            </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">Assignments</span>
          <div className="flex items-baseline justify-between">
            <span className="text-2xl font-bold font-mono text-slate-900">{assignments.length}</span>
            <span className="text-[10px] text-slate-600 bg-slate-100 px-2 py-0.5 rounded font-semibold">
              Practical Labs
            </span>
          </div>
        </div>
      </div>

      {/* SECTION 1: EXAMINATION RESULTS (CRITICAL RESTRICTION FEATURE) */}
      <div className="bg-white rounded-2xl border border-slate-200 shadow-xs p-6 space-y-5">
        <div className="flex items-center justify-between border-b border-slate-200 pb-3">
          <div className="flex items-center gap-2">
            <div className="w-8 h-8 rounded-lg bg-emerald-100 flex items-center justify-center text-emerald-800">
              <Award className="w-4 h-4" />
            </div>
            <div>
              <h2 className="text-base font-bold text-slate-900">
                Official Examination Results & Academic Performance
              </h2>
              <p className="text-xs text-slate-500">
                Continuous Assessment Tests & Final Examination Board Marks
              </p>
            </div>
          </div>

          <button
            onClick={() => onOpenReportCard(studentId)}
            className="px-3.5 py-1.5 bg-slate-900 hover:bg-slate-800 text-white rounded-lg text-xs font-semibold flex items-center gap-1.5 shadow-sm"
          >
            <Printer className="w-3.5 h-3.5 text-emerald-400" />
            Official Report Card
          </button>
        </div>

        {/* Lock or Unlock Display */}
        {lockStatus.isLocked ? (
          <div className="bg-amber-50 border-2 border-amber-400 rounded-2xl p-6 text-center space-y-3">
            <div className="w-12 h-12 bg-amber-100 rounded-full flex items-center justify-center mx-auto text-amber-700 border border-amber-300">
              <Lock className="w-6 h-6" />
            </div>
            <div className="max-w-lg mx-auto space-y-1">
              <h3 className="font-bold text-amber-950 text-base">
                Examination Results Locked — Fee Balance Outstanding
              </h3>
              <p className="text-xs text-slate-700 leading-relaxed">
                As per college policy, official examination marks and transcripts are restricted until full tuition is cleared. Your current balance is <strong>MK {lockStatus.balanceDue.toLocaleString()}</strong>.
              </p>
              <p className="text-[11px] text-slate-500 font-mono pt-1">
                Deposit into National Bank Customs Road Account: <strong>1003452219</strong> (Soche Technical College).
              </p>
            </div>

            <div className="pt-2 flex justify-center">
              <button
                onClick={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" />
                Upload Bank Deposit Slip to Unlock Marks
              </button>
            </div>
          </div>
        ) : (
          <div className="space-y-4">
            <div className="p-3 bg-emerald-50 border border-emerald-300 rounded-xl text-xs font-medium text-emerald-950 flex items-center justify-between">
              <div className="flex items-center gap-2">
                <CheckCircle2 className="w-4 h-4 text-emerald-600 shrink-0" />
                <span>
                  Fees 100% Cleared. Your official examination results and academic standing are verified.
                </span>
              </div>
              <span className="font-mono font-bold text-emerald-800 text-xs">
                GPA: {avgGpa} / 4.0
              </span>
            </div>

            {/* Grades Grid */}
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              {studentGrades.map(grd => (
                <div
                  key={grd.id}
                  className="border border-slate-200 rounded-xl p-4 bg-slate-50/50 space-y-2 text-xs"
                >
                  <div className="flex items-start justify-between gap-2">
                    <div>
                      <h4 className="font-bold text-slate-900 text-sm">{grd.subjectName}</h4>
                      <span className="text-[10px] text-slate-500 font-mono">{grd.examBoard} • {grd.semester}</span>
                    </div>
                    <span className="px-2.5 py-1 bg-emerald-100 text-emerald-900 border border-emerald-300 rounded font-bold text-sm">
                      {grd.letterGrade}
                    </span>
                  </div>

                  <div className="grid grid-cols-4 gap-2 pt-1 font-mono text-center text-[11px] bg-white p-2 rounded border border-slate-200">
                    <div>
                      <span className="text-slate-400 block text-[9px]">CW (30)</span>
                      <strong>{grd.courseworkScore}</strong>
                    </div>
                    <div>
                      <span className="text-slate-400 block text-[9px]">MID (20)</span>
                      <strong>{grd.midtermScore}</strong>
                    </div>
                    <div>
                      <span className="text-slate-400 block text-[9px]">PRAC (10)</span>
                      <strong>{grd.practicalScore}</strong>
                    </div>
                    <div>
                      <span className="text-slate-400 block text-[9px]">EXAM (40)</span>
                      <strong>{grd.finalExamScore}</strong>
                    </div>
                  </div>

                  <p className="text-slate-600 text-[11px] italic">"{grd.remarks}"</p>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>

      {/* SECTION 2: ASSIGNMENT SUBMISSION HUB & PRACTICAL LABS */}
      <div className="bg-white rounded-2xl border border-slate-200 shadow-xs p-6 space-y-4">
        <div className="flex items-center justify-between border-b border-slate-200 pb-3">
          <div className="flex items-center gap-2">
            <div className="w-8 h-8 rounded-lg bg-blue-100 flex items-center justify-center text-blue-800">
              <FileCheck className="w-4 h-4" />
            </div>
            <div>
              <h2 className="text-base font-bold text-slate-900">Assignments & Practical Submissions</h2>
              <p className="text-xs text-slate-500">Upload lab projects and view lecturer remarks</p>
            </div>
          </div>
        </div>

        <div className="grid grid-cols-1 gap-4">
          {assignments.map(asn => (
            <div
              key={asn.id}
              className="border border-slate-200 rounded-xl p-4 bg-slate-50/50 space-y-3 text-xs"
            >
              <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">
                <div>
                  <h4 className="font-bold text-sm text-slate-900">{asn.title}</h4>
                  <span className="text-slate-500 font-mono text-[11px]">
                    Course: {asn.courseCode} • Due: {asn.dueDate} • Total Marks: {asn.totalMarks}
                  </span>
                </div>

                {asn.mySubmission ? (
                  <span className="bg-emerald-100 text-emerald-900 px-3 py-1 rounded-full font-bold text-[11px] border border-emerald-300 self-start">
                    Status: {asn.mySubmission.status} {asn.mySubmission.score ? `(${asn.mySubmission.score}/${asn.totalMarks})` : ''}
                  </span>
                ) : (
                  <button
                    onClick={() => setSubmittingAsnId(asn.id)}
                    className="px-3 py-1.5 bg-emerald-600 hover:bg-emerald-700 text-white font-bold rounded-lg text-xs self-start"
                  >
                    Submit Work
                  </button>
                )}
              </div>

              <p className="text-slate-700 leading-relaxed">{asn.instructions}</p>

              {/* My submission details */}
              {asn.mySubmission && (
                <div className="p-3 bg-white border border-slate-200 rounded-lg space-y-1">
                  <div className="flex justify-between font-medium text-slate-800">
                    <span>Uploaded: {asn.mySubmission.fileName} ({asn.mySubmission.fileSize})</span>
                    <span className="text-slate-400 font-mono text-[10px]">{asn.mySubmission.submittedAt}</span>
                  </div>
                  {asn.mySubmission.feedback && (
                    <p className="text-emerald-800 text-[11px] bg-emerald-50 p-2 rounded border border-emerald-200">
                      <strong>Lecturer Feedback:</strong> {asn.mySubmission.feedback}
                    </p>
                  )}
                </div>
              )}

              {/* Submit Box */}
              {submittingAsnId === asn.id && (
                <div className="p-4 bg-white border border-emerald-300 rounded-xl space-y-3 animate-in fade-in">
                  <h5 className="font-bold text-slate-900">Upload Project File / Laboratory Code</h5>
                  
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                    <div>
                      <label className="block font-semibold text-slate-700 mb-1">FILE NAME</label>
                      <input
                        type="text"
                        placeholder="e.g. Chimwemwe_Phiri_VLAN_Lab.pkt"
                        value={asnFileName}
                        onChange={e => setAsnFileName(e.target.value)}
                        className="w-full p-2 border border-slate-300 rounded text-xs font-mono"
                      />
                    </div>
                    <div>
                      <label className="block font-semibold text-slate-700 mb-1">SUBMISSION NOTES</label>
                      <input
                        type="text"
                        placeholder="Optional remarks for the lecturer..."
                        value={asnNotes}
                        onChange={e => setAsnNotes(e.target.value)}
                        className="w-full p-2 border border-slate-300 rounded text-xs"
                      />
                    </div>
                  </div>

                  <div className="flex justify-end gap-2">
                    <button
                      onClick={() => setSubmittingAsnId(null)}
                      className="px-3 py-1.5 text-slate-600 hover:bg-slate-100 rounded text-xs"
                    >
                      Cancel
                    </button>
                    <button
                      onClick={() => handleUploadAssignment(asn.id)}
                      className="px-4 py-1.5 bg-emerald-600 hover:bg-emerald-700 text-white font-bold rounded text-xs"
                    >
                      Confirm Upload
                    </button>
                  </div>
                </div>
              )}
            </div>
          ))}
        </div>
      </div>

      {/* SECTION 3: CLOUD STUDY LIBRARY */}
      <div className="bg-white rounded-2xl border border-slate-200 shadow-xs p-6 space-y-4">
        <div className="flex items-center justify-between border-b border-slate-200 pb-3">
          <div className="flex items-center gap-2">
            <div className="w-8 h-8 rounded-lg bg-purple-100 flex items-center justify-center text-purple-800">
              <BookOpen className="w-4 h-4" />
            </div>
            <div>
              <h2 className="text-base font-bold text-slate-900">Cloud Study Library & Past Exam Papers</h2>
              <p className="text-xs text-slate-500">Official syllabi, revision materials, and exam schemes</p>
            </div>
          </div>
        </div>

        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          {studyMaterials.map(mat => (
            <div
              key={mat.id}
              className="border border-slate-200 rounded-xl p-4 bg-slate-50 flex flex-col justify-between space-y-3 text-xs"
            >
              <div className="space-y-1">
                <div className="flex items-center justify-between">
                  <span className="px-2 py-0.5 bg-purple-100 text-purple-900 border border-purple-200 rounded text-[10px] font-bold">
                    {mat.category}
                  </span>
                  <span className="font-mono text-slate-500 text-[10px]">{mat.fileType} • {mat.fileSize}</span>
                </div>
                <h4 className="font-bold text-sm text-slate-900">{mat.title}</h4>
                <p className="text-slate-600 text-[11px] leading-relaxed">{mat.description}</p>
              </div>

              <div className="flex items-center justify-between pt-2 border-t border-slate-200">
                <span className="text-slate-500 text-[10px]">Uploaded by {mat.uploadedBy}</span>
                <button
                  onClick={() => alert(`Downloading "${mat.title}" (${mat.fileSize})...`)}
                  className="px-3 py-1 bg-white hover:bg-slate-100 border border-slate-300 text-slate-800 font-semibold rounded text-xs flex items-center gap-1 shadow-xs"
                >
                  <Download className="w-3 h-3 text-emerald-600" />
                  Download
                </button>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* DIGITAL STUDENT ID MODAL */}
      <StudentIDCardModal
        isOpen={isIdModalOpen}
        onClose={() => setIsIdModalOpen(false)}
        user={currentUser}
        studentFee={studentFee}
      />

    </div>
  );
};
