import React, { useState } from 'react';
import { Award, BookOpen, Calendar, CheckSquare, Clock, GraduationCap, Play, Square, Award as Medal, User, LogOut, CheckCircle2 } from 'lucide-react';
import { Course, Enrollment, Language, LiveClass, Student } from '../types';
import { translations, sampleLiveClasses } from '../data';

interface StudentPortalProps {
  student: Student;
  enrollments: Enrollment[];
  courses: Course[];
  lang: Language;
  onLogout: () => void;
  onUpdateEnrollments: (updated: Enrollment[]) => void;
}

export default function StudentPortal({
  student,
  enrollments,
  courses,
  lang,
  onLogout,
  onUpdateEnrollments
}: StudentPortalProps) {
  const t = translations[lang];
  const [selectedEnrollment, setSelectedEnrollment] = useState<Enrollment | null>(
    enrollments.length > 0 ? enrollments[0] : null
  );
  const [showCertificate, setShowCertificate] = useState<Course | null>(null);
  const [activeTab, setActiveTab] = useState<'my_courses' | 'live_classes' | 'profile'>('my_courses');

  // Find course details for enrollments
  const enrolledCourses = enrollments.map(e => {
    const course = courses.find(c => c.id === e.courseId);
    return { enrollment: e, course };
  }).filter(item => item.course !== undefined) as Array<{ enrollment: Enrollment, course: Course }>;

  // Update modules completion
  const handleToggleModule = (courseId: string, moduleIndex: number) => {
    const updated = enrollments.map(e => {
      if (e.courseId === courseId) {
        let completed = [...e.completedModules];
        if (completed.includes(moduleIndex)) {
          completed = completed.filter(i => i !== moduleIndex);
        } else {
          completed.push(moduleIndex);
        }
        
        const course = courses.find(c => c.id === courseId);
        const totalModules = course?.modules.length || 1;
        const progress = Math.round((completed.length / totalModules) * 100);
        const status: 'not_started' | 'in_progress' | 'completed' = progress === 100 ? 'completed' : progress > 0 ? 'in_progress' : 'not_started';
        const grade = progress === 100 ? 'A+ (Excellent)' : undefined;

        const newEnrollment: Enrollment = {
          ...e,
          completedModules: completed,
          progress,
          status,
          grade
        };

        // Keep local state updated
        if (selectedEnrollment && selectedEnrollment.courseId === courseId) {
          setSelectedEnrollment(newEnrollment);
        }

        return newEnrollment;
      }
      return e;
    });

    onUpdateEnrollments(updated);
  };

  return (
    <div 
      className="bg-white/95 backdrop-blur-md rounded-2xl shadow-xl border border-teal-50 overflow-hidden"
      dir={lang === 'ar' ? 'rtl' : 'ltr'}
    >
      {/* Student Top Panel */}
      <div className="bg-gradient-to-r from-teal-850 to-teal-700 text-white p-6 md:p-8">
        <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
          <div className="flex items-center gap-4">
            <div className="bg-white/10 p-3 rounded-full border border-white/20">
              <User size={32} className="text-amber-400" />
            </div>
            <div>
              <p className="text-xs text-teal-100 font-medium tracking-wider uppercase font-mono">
                {t.studentPortal}
              </p>
              <h2 className="text-xl md:text-2xl font-bold font-sans mt-0.5">
                {t.welcomeBack}, {student.name}
              </h2>
              <p className="text-xs text-teal-100/80 mt-1">
                {student.email} • {student.phone}
              </p>
            </div>
          </div>
          <div className="flex items-center gap-3 w-full md:w-auto">
            <button
              onClick={onLogout}
              className="flex items-center justify-center gap-2 bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-xl text-xs font-semibold transition-all shadow-md w-full md:w-auto"
            >
              <LogOut size={14} />
              <span>{t.logoutBtn}</span>
            </button>
          </div>
        </div>

        {/* Inner Navigation Tabs */}
        <div className="flex border-t border-white/10 mt-6 pt-4 gap-6 text-sm">
          <button
            onClick={() => setActiveTab('my_courses')}
            className={`pb-2 px-1 font-semibold transition-all relative ${
              activeTab === 'my_courses' ? 'text-amber-400' : 'text-teal-100 hover:text-white'
            }`}
          >
            {lang === 'en' ? 'My Enrolled Courses' : 'دوراتي التعليمية'}
            {activeTab === 'my_courses' && (
              <span className="absolute bottom-0 left-0 right-0 h-0.5 bg-amber-400 rounded-full" />
            )}
          </button>
          <button
            onClick={() => setActiveTab('live_classes')}
            className={`pb-2 px-1 font-semibold transition-all relative ${
              activeTab === 'live_classes' ? 'text-amber-400' : 'text-teal-100 hover:text-white'
            }`}
          >
            {lang === 'en' ? 'Live Interactive Classrooms' : 'قاعات البث المباشر'}
            {activeTab === 'live_classes' && (
              <span className="absolute bottom-0 left-0 right-0 h-0.5 bg-amber-400 rounded-full" />
            )}
          </button>
          <button
            onClick={() => setActiveTab('profile')}
            className={`pb-2 px-1 font-semibold transition-all relative ${
              activeTab === 'profile' ? 'text-amber-400' : 'text-teal-100 hover:text-white'
            }`}
          >
            {lang === 'en' ? 'Student Profile Card' : 'الملف الشخصي للطالب'}
            {activeTab === 'profile' && (
              <span className="absolute bottom-0 left-0 right-0 h-0.5 bg-amber-400 rounded-full" />
            )}
          </button>
        </div>
      </div>

      {/* Main Tab Contents */}
      <div className="p-6 md:p-8 min-h-[400px]">
        {/* TAB 1: MY COURSES */}
        {activeTab === 'my_courses' && (
          <div>
            {enrolledCourses.length === 0 ? (
              <div className="text-center py-16 px-4 flex flex-col items-center justify-center">
                <BookOpen size={48} className="text-teal-300 mb-4" />
                <p className="text-gray-600 font-medium max-w-md mx-auto leading-relaxed">
                  {t.portalNoCourses}
                </p>
              </div>
            ) : (
              <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
                {/* Left side: Course list */}
                <div className="lg:col-span-5 space-y-4">
                  <h3 className="font-bold text-gray-800 text-sm tracking-wider uppercase mb-3 text-teal-800 border-b pb-2">
                    {lang === 'en' ? 'Select Active Syllabus' : 'اختر المقرر الدراسي'}
                  </h3>
                  {enrolledCourses.map(({ enrollment, course }) => {
                    const isSelected = selectedEnrollment?.courseId === course.id;
                    return (
                      <button
                        key={course.id}
                        onClick={() => setSelectedEnrollment(enrollment)}
                        className={`w-full text-left p-4 rounded-xl border transition-all flex items-start gap-3 ${
                          isSelected
                            ? 'border-teal-500 bg-teal-50/40 ring-1 ring-teal-500'
                            : 'border-gray-200 hover:border-teal-200 hover:bg-gray-50'
                        }`}
                        dir={lang === 'ar' ? 'rtl' : 'ltr'}
                      >
                        <img
                          src={course.image}
                          alt={course.title}
                          className="w-16 h-16 rounded-lg object-cover shadow-sm mt-0.5"
                          referrerPolicy="no-referrer"
                        />
                        <div className="flex-1 min-w-0">
                          <span className="inline-block text-[10px] font-extrabold px-2 py-0.5 rounded-full bg-teal-100 text-teal-800 uppercase mb-1">
                            {lang === 'en' ? course.category : course.categoryAr}
                          </span>
                          <h4 className="font-semibold text-gray-800 text-sm line-clamp-1">
                            {lang === 'en' ? course.title : course.titleAr}
                          </h4>
                          <div className="flex items-center gap-2 mt-2">
                            <div className="flex-1 bg-gray-200 h-1.5 rounded-full overflow-hidden">
                              <div 
                                className="bg-teal-600 h-1.5 rounded-full transition-all duration-300" 
                                style={{ width: `${enrollment.progress}%` }}
                              />
                            </div>
                            <span className="text-xs font-bold text-teal-700 font-mono">
                              {enrollment.progress}%
                            </span>
                          </div>
                        </div>
                      </button>
                    );
                  })}
                </div>

                {/* Right side: Active Course Syllabus & Progress details */}
                <div className="lg:col-span-7">
                  {selectedEnrollment ? (
                    (() => {
                      const activeItem = enrolledCourses.find(item => item.course.id === selectedEnrollment.courseId);
                      if (!activeItem) return null;
                      const { course, enrollment } = activeItem;
                      const totalModules = course.modules.length;
                      
                      return (
                        <div className="bg-teal-50/10 p-6 rounded-xl border border-teal-100/50 space-y-6">
                          <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 pb-4 border-b">
                            <div>
                              <span className="text-xs font-semibold text-teal-700">
                                {lang === 'en' ? 'ACADEMIC COURSE MODULES' : 'مقررات الدراسة الأكاديمية'}
                              </span>
                              <h3 className="font-bold text-gray-800 text-lg md:text-xl mt-1">
                                {lang === 'en' ? course.title : course.titleAr}
                              </h3>
                              <p className="text-xs text-gray-500 mt-1">
                                {t.instructor}: <strong className="text-teal-800">{lang === 'en' ? course.instructor : course.instructorAr}</strong>
                              </p>
                            </div>
                            
                            {/* Certificate Unlock Banner */}
                            {enrollment.progress === 100 ? (
                              <button
                                onClick={() => setShowCertificate(course)}
                                className="bg-amber-500 hover:bg-amber-600 text-white font-bold text-xs py-2.5 px-4 rounded-xl flex items-center gap-2 shadow-md hover:shadow-lg transition-all animate-bounce"
                              >
                                <Award size={16} />
                                <span>{t.congratsCertificate}</span>
                              </button>
                            ) : (
                              <div className="bg-gray-100 border text-gray-500 rounded-xl px-3 py-1.5 text-xs font-semibold flex items-center gap-2">
                                <Clock size={14} />
                                <span>{lang === 'en' ? `${100 - enrollment.progress}% left for Certificate` : `متبقي ${100 - enrollment.progress}٪ للشهادة`}</span>
                              </div>
                            )}
                          </div>

                          {/* Progress bar info */}
                          <div className="grid grid-cols-2 sm:grid-cols-3 gap-4 bg-white p-4 rounded-xl border border-gray-100 shadow-sm">
                            <div className="text-center sm:border-r border-gray-100">
                              <span className="text-[10px] text-gray-400 block uppercase font-mono font-bold">{lang === 'en' ? 'Syllabus Progress' : 'نسبة الإنجاز'}</span>
                              <span className="text-lg font-extrabold text-teal-700 font-mono">{enrollment.progress}%</span>
                            </div>
                            <div className="text-center sm:border-r border-gray-100">
                              <span className="text-[10px] text-gray-400 block uppercase font-mono font-bold">{lang === 'en' ? 'Modules Completed' : 'المقررات المنجزة'}</span>
                              <span className="text-lg font-extrabold text-teal-700 font-mono">{enrollment.completedModules.length} / {totalModules}</span>
                            </div>
                            <div className="text-center col-span-2 sm:col-span-1">
                              <span className="text-[10px] text-gray-400 block uppercase font-mono font-bold">{t.grade}</span>
                              <span className="text-sm font-extrabold text-amber-600 block mt-1">
                                {enrollment.progress === 100 ? 'A+ (Excellent)' : enrollment.progress >= 50 ? 'B (Good)' : 'C (In Progress)'}
                              </span>
                            </div>
                          </div>

                          {/* Interactive list of lessons/modules */}
                          <div className="space-y-3">
                            <h4 className="font-semibold text-gray-700 text-sm">
                              {lang === 'en' ? 'Check modules to mark as completed:' : 'حدد المقررات التي أتممتها للتقدم في الدورة:'}
                            </h4>
                            <div className="space-y-2">
                              {(lang === 'en' ? course.modules : course.modulesAr).map((module, index) => {
                                const isCompleted = enrollment.completedModules.includes(index);
                                return (
                                  <button
                                    key={index}
                                    type="button"
                                    onClick={() => handleToggleModule(course.id, index)}
                                    className={`w-full text-left p-3.5 rounded-xl border flex items-center justify-between transition-all ${
                                      isCompleted
                                        ? 'bg-teal-50/30 border-teal-200 text-teal-900'
                                        : 'bg-white border-gray-100 text-gray-700 hover:bg-gray-50'
                                    }`}
                                    dir={lang === 'ar' ? 'rtl' : 'ltr'}
                                  >
                                    <div className="flex items-center gap-3">
                                      {isCompleted ? (
                                        <CheckSquare className="text-teal-600 shrink-0" size={18} />
                                      ) : (
                                        <Square className="text-gray-300 shrink-0" size={18} />
                                      )}
                                      <span className="text-xs md:text-sm font-medium line-clamp-1">
                                        {index + 1}. {module}
                                      </span>
                                    </div>
                                    <span className={`text-[10px] font-bold px-2 py-0.5 rounded uppercase ${
                                      isCompleted ? 'bg-teal-100 text-teal-800' : 'bg-gray-100 text-gray-500'
                                    }`}>
                                      {isCompleted ? (lang === 'en' ? 'Complete' : 'مكتمل') : (lang === 'en' ? 'Pending' : 'قيد الانتظار')}
                                    </span>
                                  </button>
                                );
                              })}
                            </div>
                          </div>
                        </div>
                      );
                    })()
                  ) : (
                    <div className="text-center py-12 text-gray-400">
                      {lang === 'en' ? 'Select a course from the left pane to view progress.' : 'اختر دورة من القائمة لعرض نسبة الإنجاز والدروس.'}
                    </div>
                  )}
                </div>
              </div>
            )}
          </div>
        )}

        {/* TAB 2: LIVE CLASSES */}
        {activeTab === 'live_classes' && (
          <div className="space-y-6">
            <div className="border-b pb-3 flex justify-between items-center">
              <div>
                <h3 className="font-bold text-gray-800 text-base">{t.portalLiveTitle}</h3>
                <p className="text-xs text-gray-500 mt-0.5">
                  {lang === 'en' ? 'Connect directly to your virtual live classrooms.' : 'اتصل مباشرة بفصولك الدراسية الافتراضية عبر البث المباشر.'}
                </p>
              </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {sampleLiveClasses.map((live) => (
                <div 
                  key={live.id}
                  className="bg-white border border-gray-200 hover:border-teal-300 transition-all rounded-xl p-5 shadow-sm space-y-4 relative overflow-hidden flex flex-col justify-between"
                >
                  {/* Class Badge */}
                  <div className="flex justify-between items-center">
                    <span className={`text-[10px] font-extrabold px-2.5 py-0.5 rounded-full uppercase ${
                      live.platform === 'Zoom' ? 'bg-blue-100 text-blue-700' : 'bg-green-100 text-green-700'
                    }`}>
                      {live.platform} Stream
                    </span>
                    <span className="text-[10px] font-bold font-mono text-amber-600 bg-amber-50 px-2.5 py-0.5 rounded-full">
                      {t.meetStatusUpcoming}
                    </span>
                  </div>

                  <div className="space-y-1">
                    <h4 className="font-bold text-gray-800 text-sm md:text-base leading-snug line-clamp-2">
                      {lang === 'en' ? live.title : live.titleAr}
                    </h4>
                    <p className="text-xs text-gray-500 font-medium">
                      {t.instructor}: <span className="text-teal-800 font-semibold">{lang === 'en' ? live.instructor : live.instructor}</span>
                    </p>
                  </div>

                  {/* Date Time info */}
                  <div className="bg-gray-50 p-3 rounded-lg border text-xs grid grid-cols-2 gap-2 text-left font-mono text-gray-600">
                    <div>
                      <span className="text-[10px] text-gray-400 block uppercase font-sans font-bold">{t.classDate}</span>
                      <span>{live.date}</span>
                    </div>
                    <div>
                      <span className="text-[10px] text-gray-400 block uppercase font-sans font-bold">{t.classTime}</span>
                      <span>{live.time} UTC</span>
                    </div>
                  </div>

                  <a
                    href={live.link}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="w-full bg-teal-700 hover:bg-teal-800 text-white font-bold text-xs py-2.5 px-4 rounded-xl flex items-center justify-center gap-2 transition-all shadow-md mt-2"
                  >
                    <Play size={14} fill="currentColor" />
                    <span>{t.joinClass} ({live.platform})</span>
                  </a>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* TAB 3: STUDENT PROFILE CARD */}
        {activeTab === 'profile' && (
          <div className="max-w-xl mx-auto bg-gray-50 rounded-2xl border p-6 md:p-8 space-y-6">
            <div className="flex items-center gap-4 pb-4 border-b">
              <div className="bg-teal-700 text-white p-3 rounded-full">
                <GraduationCap size={28} />
              </div>
              <div>
                <h3 className="font-bold text-gray-800 text-base">{student.name}</h3>
                <p className="text-xs text-gray-500">{lang === 'en' ? 'Verified Academy Student' : 'طالب أكاديمي معتمد'}</p>
              </div>
            </div>

            <div className="space-y-4 text-xs md:text-sm">
              <div className="grid grid-cols-3 py-1">
                <span className="text-gray-400 font-semibold">{t.fullName}</span>
                <span className="col-span-2 font-bold text-gray-800">{student.name}</span>
              </div>
              <div className="grid grid-cols-3 py-1">
                <span className="text-gray-400 font-semibold">{t.emailAddress}</span>
                <span className="col-span-2 font-mono text-gray-800">{student.email}</span>
              </div>
              <div className="grid grid-cols-3 py-1">
                <span className="text-gray-400 font-semibold">{t.phoneNumber}</span>
                <span className="col-span-2 font-mono text-gray-800">{student.phone}</span>
              </div>
              <div className="grid grid-cols-3 py-1">
                <span className="text-gray-400 font-semibold">{lang === 'en' ? 'Admission Date' : 'تاريخ الالتحاق'}</span>
                <span className="col-span-2 font-mono text-gray-850">{student.registeredAt}</span>
              </div>
              {student.bio && (
                <div className="pt-4 border-t">
                  <span className="text-gray-400 font-semibold block mb-1">{t.bio}</span>
                  <p className="text-gray-600 bg-white p-3 rounded-xl border leading-relaxed">
                    {student.bio}
                  </p>
                </div>
              )}
            </div>
          </div>
        )}
      </div>

      {/* ACADEMIC CERTIFICATE MODAL DISPLAY */}
      {showCertificate && (
        <div className="fixed inset-0 bg-black/75 backdrop-blur-md z-50 flex items-center justify-center p-4">
          <div className="bg-amber-50/90 rounded-2xl max-w-2xl w-full p-1 border-4 border-amber-600 shadow-2xl relative overflow-hidden animate-in fade-in zoom-in-95 duration-300">
            {/* Elegant Double border certificate */}
            <div className="border border-amber-600/60 p-6 md:p-10 text-center space-y-6 relative bg-white rounded-xl">
              
              {/* Islamic Pattern Accent Corners */}
              <div className="absolute top-2 left-2 text-amber-600 font-serif text-2xl select-none">✦</div>
              <div className="absolute top-2 right-2 text-amber-600 font-serif text-2xl select-none">✦</div>
              <div className="absolute bottom-2 left-2 text-amber-600 font-serif text-2xl select-none">✦</div>
              <div className="absolute bottom-2 right-2 text-amber-600 font-serif text-2xl select-none">✦</div>

              <div className="flex justify-center mb-2">
                {/* Academic Seal Badge icon */}
                <div className="bg-amber-500 text-white p-4 rounded-full shadow-md border-4 border-white">
                  <Medal size={40} />
                </div>
              </div>

              <div className="space-y-1">
                <h2 className="font-serif font-extrabold text-teal-900 text-xl md:text-2xl tracking-wide">
                  أكاديمية دار الفكر الدولية
                </h2>
                <h3 className="font-sans font-bold text-xs md:text-sm tracking-widest text-amber-600 uppercase">
                  Dar Al-Fikr International Academy Board
                </h3>
              </div>

              <div className="py-2">
                <p className="font-serif italic text-gray-500 text-sm">
                  {lang === 'en' ? 'This academic credential is proud to authorize that' : 'نشهد بموجب هذه الإجازة العلمية الموثقة أن الطالب'}
                </p>
                <h4 className="font-serif font-extrabold text-teal-800 text-2xl md:text-3xl my-2 border-b-2 border-amber-400 inline-block px-6">
                  {student.name}
                </h4>
                <p className="font-serif text-sm text-gray-600 max-w-md mx-auto leading-relaxed mt-2">
                  {lang === 'en' 
                    ? `has successfully fulfilled all course milestones and rigorous examinations required to pass the academy's official curriculum for:` 
                    : `قد أتم بنجاح وتفوق جميع المقررات الدراسية والاختبارات الأكاديمية والعملية المطلوبة لاجتياز دورة:`}
                </p>
                <h5 className="font-serif font-bold text-lg md:text-xl text-gray-800 mt-2">
                  " {lang === 'en' ? showCertificate.title : showCertificate.titleAr} "
                </h5>
              </div>

              {/* Grid with Signatures & Certificate Verification Seal */}
              <div className="grid grid-cols-2 md:grid-cols-3 gap-6 pt-6 border-t border-amber-100 text-xs text-left">
                <div className="text-center space-y-1">
                  <div className="font-mono text-gray-400 select-none font-bold italic line-through mb-1">Ibr. Al-Hassan</div>
                  <span className="block border-t border-gray-300 pt-1 font-bold text-gray-700">Prof. Ibrahim Al-Hassan</span>
                  <span className="text-[10px] text-gray-400 block">{lang === 'en' ? 'Academic Director' : 'العميد الأكاديمي'}</span>
                </div>
                
                <div className="hidden md:flex justify-center items-center">
                  {/* Decorative gold-like seal of completion */}
                  <div className="border-2 border-dashed border-amber-500 rounded-full w-20 h-20 flex flex-col items-center justify-center text-[8px] text-amber-600 font-extrabold leading-none uppercase text-center select-none bg-amber-50">
                    <span>BOARD</span>
                    <span className="my-1 text-teal-800 text-[10px]">VERIFIED</span>
                    <span>9026461916</span>
                  </div>
                </div>

                <div className="text-center space-y-1">
                  <div className="font-mono text-gray-400 select-none font-bold italic line-through mb-1">Umar-Habu</div>
                  <span className="block border-t border-gray-300 pt-1 font-bold text-gray-700">Dr. Fatima Umar</span>
                  <span className="text-[10px] text-gray-400 block">{lang === 'en' ? 'Board Secretary' : 'أمين مجلس الإدارة'}</span>
                </div>
              </div>

              <div className="flex gap-4 justify-center pt-4">
                <button
                  onClick={() => window.print()}
                  className="bg-teal-700 hover:bg-teal-800 text-white font-bold text-xs py-2 px-4 rounded-xl shadow-md transition-all flex items-center gap-1"
                >
                  {lang === 'en' ? 'Print Certificate' : 'طباعة الإجازة والشهادة'}
                </button>
                <button
                  onClick={() => setShowCertificate(null)}
                  className="bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold text-xs py-2 px-4 rounded-xl border transition-all"
                >
                  {lang === 'en' ? 'Close' : 'إغلاق'}
                </button>
              </div>

            </div>
          </div>
        </div>
      )}
    </div>
  );
}
