'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import { useAuth } from '@/context/AuthContext';
import { apiRequest } from '@/lib/api';
import { getMediaUrl } from '@/lib/media';
import SecureVideoPlayer from '@/components/SecureVideoPlayer';
import {
  BookOpen,
  GraduationCap,
  Sparkles,
  ArrowRight,
  Clock,
  PlayCircle,
  ShieldCheck,
  ChevronDown,
  ChevronUp,
  Lock,
  Unlock,
  X,
  Video,
  FileText,
  Download,
} from 'lucide-react';

export default function StudentDashboardPage() {
  const { user } = useAuth();
  const [subscriptions, setSubscriptions] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [expandedCourseId, setExpandedCourseId] = useState<string | null>(null);
  const [courseLessons, setCourseLessons] = useState<{ [courseId: string]: any[] }>({});
  const [loadingLessons, setLoadingLessons] = useState<{ [courseId: string]: boolean }>({});
  const [activeVideo, setActiveVideo] = useState<{
    fileKey: string;
    courseId: string;
    title: string;
  } | null>(null);

  useEffect(() => {
    const fetchSubscriptions = async () => {
      setLoading(true);
      const res = await apiRequest('/subscriptions');
      if (res.success && res.subscriptions) {
        setSubscriptions(res.subscriptions);
      }
      setLoading(false);
    };

    fetchSubscriptions();
  }, []);

  const toggleViewLessons = async (courseId: string, chapters: any[]) => {
    if (expandedCourseId === courseId) {
      setExpandedCourseId(null);
      return;
    }

    setExpandedCourseId(courseId);

    if (!courseLessons[courseId]) {
      setLoadingLessons((prev) => ({ ...prev, [courseId]: true }));
      try {
        const res = await apiRequest(`/lessons?courseId=${courseId}`);
        if (res.success && res.lessons && res.lessons.length > 0) {
          setCourseLessons((prev) => ({ ...prev, [courseId]: res.lessons }));
        } else if (chapters && chapters.length > 0) {
          setCourseLessons((prev) => ({ ...prev, [courseId]: chapters }));
        } else {
          setCourseLessons((prev) => ({ ...prev, [courseId]: [] }));
        }
      } catch (err) {
        setCourseLessons((prev) => ({ ...prev, [courseId]: chapters || [] }));
      } finally {
        setLoadingLessons((prev) => ({ ...prev, [courseId]: false }));
      }
    }
  };

  const isLessonUnlocked = (sub: any, lessonId: string) => {
    // If subscription is full-course access (no specific restricted lessons list), all lessons in course are unlocked
    if (!sub.lessons || sub.lessons.length === 0) return true;

    // Otherwise check if lessonId is explicitly in sub.lessons list
    return sub.lessons.some(
      (l: any) => (typeof l === 'string' ? l : l._id || l.toString()) === lessonId
    );
  };

  return (
    <div className="space-y-8 max-w-6xl mx-auto pb-12">
      {/* Compact Welcome Bar */}
      <div className="p-4 sm:p-5 rounded-2xl bg-white border border-gray-200/80 shadow-xs flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div className="flex items-center gap-3.5">
          <div className="w-10 h-10 rounded-xl bg-[#FECE00] text-black flex items-center justify-center font-black text-sm shrink-0 shadow-xs">
            <Sparkles className="w-5 h-5 text-black" />
          </div>
          <div>
            <div className="flex items-center gap-2">
              <h1 className="text-base sm:text-lg font-extrabold text-gray-900 tracking-tight">
                Willkommen, {user?.name}!
              </h1>
            </div>
            <p className="text-xs text-gray-500 font-medium mt-0.5">
              Access your enrolled German level modules and video lessons.
            </p>
          </div>
        </div>

        <Link
          href="/#courses"
          className="px-4 py-2 rounded-xl bg-gray-900 hover:bg-[#FECE00] text-white hover:text-black font-extrabold text-xs uppercase tracking-wider shadow-xs transition-all flex items-center justify-center gap-2 group shrink-0 active:scale-95"
        >
          <span>Browse All Courses</span>
          <ArrowRight className="w-3.5 h-3.5 transition-transform group-hover:translate-x-0.5" />
        </Link>
      </div>

      {/* Enrolled Courses Section */}
      <div className="space-y-4">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2.5">
            <GraduationCap className="w-5 h-5 text-amber-600" />
            <h2 className="text-xl font-extrabold text-gray-900">Your Enrolled Courses</h2>
          </div>
          <span className="text-xs font-bold text-gray-500 bg-gray-100 px-3 py-1 rounded-full border border-gray-200">
            {subscriptions.length} Active Enrollment{subscriptions.length !== 1 ? 's' : ''}
          </span>
        </div>

        {loading ? (
          <div className="p-16 text-center text-gray-500 font-semibold bg-white rounded-3xl border border-gray-200/80 shadow-xs flex flex-col items-center justify-center gap-3">
            <div className="w-8 h-8 border-3 border-[#FECE00] border-t-transparent rounded-full animate-spin" />
            <span>Loading your courses...</span>
          </div>
        ) : subscriptions.length === 0 ? (
          <div className="p-12 sm:p-16 text-center bg-white rounded-3xl border border-gray-200/80 shadow-xs space-y-4">
            <div className="w-16 h-16 rounded-3xl bg-amber-50 border border-amber-200/80 text-amber-600 flex items-center justify-center mx-auto shadow-xs">
              <BookOpen className="w-8 h-8 text-amber-600 stroke-[1.8]" />
            </div>

            <div className="space-y-1.5 max-w-md mx-auto">
              <h3 className="text-lg font-extrabold text-gray-900">No Courses Enrolled Yet</h3>
              <p className="text-xs sm:text-sm text-gray-500 font-medium leading-relaxed">
                You have not enrolled in any German language courses yet. Explore our structured level modules from A1 to B2 and start learning today.
              </p>
            </div>

            <div className="pt-2">
              <Link
                href="/#courses"
                className="px-4 py-2 bg-[#FECE00] hover:bg-[#e5b800] text-black text-sm font-medium rounded-lg shadow-sm transition-colors flex items-center justify-center gap-2 cursor-pointer inline-flex"
              >
                <span>Explore Course Catalog</span>
                <ArrowRight className="w-4 h-4 text-black" />
              </Link>
            </div>
          </div>
        ) : (
          <div className="grid grid-cols-1 gap-6 items-start">
            {subscriptions.map((sub) => {
              const expiryDate = new Date(sub.expiryDate);
              const daysRemaining = Math.max(0, Math.ceil((expiryDate.getTime() - Date.now()) / (1000 * 60 * 60 * 24)));
              const courseId = sub.course?._id || sub.course;
              const isExpanded = expandedCourseId === courseId;
              const lessons = courseLessons[courseId] || sub.course?.chapters || [];

              return (
                <div
                  key={sub._id}
                  className="bg-white rounded-3xl border border-gray-200/90 p-6 shadow-sm hover:shadow-md transition-all duration-200 flex flex-col justify-between space-y-5"
                >
                  <div className="space-y-3">
                    <div className="flex items-center justify-between">
                      <span className="px-3 py-1 rounded-full text-xs font-black bg-black text-[#FECE00] uppercase tracking-wider">
                        Level {sub.course?.level || 'A1'}
                      </span>
                      <span className="text-xs font-semibold text-gray-500 flex items-center gap-1">
                        <Clock className="w-3.5 h-3.5 text-gray-400" />
                        <span>{daysRemaining} days access left</span>
                      </span>
                    </div>

                    <h3 className="text-lg font-extrabold text-gray-900">
                      {sub.course?.title || 'German Course Module'}
                    </h3>

                  </div>

                  <div className="pt-4 border-t border-gray-100 flex flex-wrap items-center justify-between gap-3 text-xs">
                    <span className="text-gray-500 font-medium flex items-center gap-1">
                      <ShieldCheck className="w-4 h-4 text-emerald-600" />
                      <span>Expires: {expiryDate.toLocaleDateString(undefined, { year: 'numeric', month: 'long', day: 'numeric' })}</span>
                    </span>

                    <button
                      onClick={() => toggleViewLessons(courseId, sub.course?.chapters)}
                      className="px-4 py-2 rounded-xl bg-gray-900 hover:bg-[#FECE00] text-white hover:text-black font-extrabold text-xs shadow-xs transition flex items-center gap-1.5 cursor-pointer active:scale-95"
                    >
                      <BookOpen className="w-4 h-4" />
                      <span>{isExpanded ? 'Hide Lessons' : 'View Lessons'}</span>
                      {isExpanded ? (
                        <ChevronUp className="w-3.5 h-3.5" />
                      ) : (
                        <ChevronDown className="w-3.5 h-3.5" />
                      )}
                    </button>
                  </div>

                  {/* Expanded Lessons List Section */}
                  {isExpanded && (
                    <div className="pt-4 border-t border-gray-100 space-y-3 animate-fadeIn">
                      <div className="flex items-center justify-between">
                        <span className="text-xs font-extrabold uppercase tracking-wider text-gray-600 flex items-center gap-1.5">
                          <Video className="w-4 h-4 text-[#FECE00]" />
                          Course Lessons ({lessons.length})
                        </span>
                      </div>

                      {loadingLessons[courseId] ? (
                        <div className="p-4 text-center text-xs text-gray-500 font-semibold flex items-center justify-center gap-2">
                          <div className="w-4 h-4 border-2 border-[#FECE00] border-t-transparent rounded-full animate-spin" />
                          <span>Loading lesson contents...</span>
                        </div>
                      ) : lessons.length === 0 ? (
                        <div className="p-4 text-center text-xs text-gray-500 bg-gray-50 rounded-xl border border-gray-100 font-medium">
                          No lessons available for this course yet.
                        </div>
                      ) : (
                        <div className="space-y-2 max-h-80 overflow-y-auto pr-1">
                          {lessons.map((lesson: any, index: number) => {
                            const lessonId = lesson._id || `lesson-${index}`;
                            const unlocked = isLessonUnlocked(sub, lessonId);
                            const videoKey = lesson.videoReference;

                            return (
                              <div
                                key={lessonId}
                                className={`p-3.5 rounded-2xl border transition-all flex items-center justify-between gap-3 ${unlocked
                                  ? 'bg-emerald-50/40 border-emerald-200/80 hover:bg-emerald-50'
                                  : 'bg-gray-50 border-gray-200/70 opacity-80'
                                  }`}
                              >
                                <div className="flex items-center gap-3 min-w-0">
                                  {/* Status Icon */}
                                  <div
                                    className={`w-8 h-8 rounded-xl flex items-center justify-center shrink-0 font-bold ${unlocked
                                      ? 'bg-emerald-100 text-emerald-700 shadow-xs'
                                      : 'bg-gray-200 text-gray-500'
                                      }`}
                                  >
                                    {unlocked ? (
                                      <Unlock className="w-4 h-4 text-emerald-600" />
                                    ) : (
                                      <Lock className="w-4 h-4 text-gray-500" />
                                    )}
                                  </div>

                                  <div className="min-w-0">
                                    <h4 className="text-xs font-bold text-gray-900 truncate">
                                      {lesson.chapterNumber ? `Lesson ${lesson.chapterNumber}: ` : ''}
                                      {lesson.title}
                                    </h4>
                                    {lesson.durationMinutes ? (
                                      <p className="text-[11px] text-gray-500 font-medium">
                                        {lesson.durationMinutes} mins duration
                                      </p>
                                    ) : null}
                                  </div>
                                </div>

                                {/* Action Button */}
                                <div className="shrink-0 flex items-center gap-2">
                                  {unlocked ? (
                                    <>
                                      {lesson.isDownloadableScriptActive && lesson.scriptFileUrl && (
                                        <a
                                          href={getMediaUrl(lesson.scriptFileUrl, 'pdfs')}
                                          target="_blank"
                                          rel="noopener noreferrer"
                                          className="px-3 py-1.5 rounded-xl bg-[#FECE00]/20 hover:bg-[#FECE00]/40 text-amber-900 font-extrabold text-[11px] shadow-xs transition flex items-center gap-1.5 cursor-pointer active:scale-95"
                                        >
                                          <Download className="w-3.5 h-3.5" />
                                          <span>Script</span>
                                        </a>
                                      )}
                                      {lesson.isDownloadableHomeworkActive && lesson.homeworkFileUrl && (
                                        <a
                                          href={getMediaUrl(lesson.homeworkFileUrl, 'pdfs')}
                                          target="_blank"
                                          rel="noopener noreferrer"
                                          className="px-3 py-1.5 rounded-xl bg-[#FECE00]/20 hover:bg-[#FECE00]/40 text-amber-900 font-extrabold text-[11px] shadow-xs transition flex items-center gap-1.5 cursor-pointer active:scale-95"
                                        >
                                          <FileText className="w-3.5 h-3.5" />
                                          <span>Homework</span>
                                        </a>
                                      )}
                                      <button
                                        onClick={() => {
                                          // Request immediate fullscreen to close & dismiss open DevTools sidebars
                                          try {
                                            const elem = document.documentElement;
                                            if (elem.requestFullscreen) {
                                              elem.requestFullscreen().catch(() => {});
                                            } else if ((elem as any).webkitRequestFullscreen) {
                                              (elem as any).webkitRequestFullscreen();
                                            }
                                          } catch (e) {}

                                          setActiveVideo({
                                            fileKey: videoKey,
                                            courseId,
                                            title: lesson.title,
                                          });
                                        }}
                                        className="px-3 py-1.5 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white font-extrabold text-[11px] shadow-xs transition flex items-center gap-1.5 cursor-pointer active:scale-95"
                                      >
                                        <PlayCircle className="w-3.5 h-3.5" />
                                        <span>Watch</span>
                                      </button>
                                    </>
                                  ) : (
                                    <span className="px-2.5 py-1 rounded-lg bg-gray-200 text-gray-600 font-bold text-[10px] uppercase tracking-wider flex items-center gap-1">
                                      <Lock className="w-3 h-3" /> Locked
                                    </span>
                                  )}
                                </div>
                              </div>
                            );
                          })}
                        </div>
                      )}
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* Protected Direct Video Overlay */}
      {activeVideo && (
        <div className="fixed inset-0 z-50 bg-black flex items-center justify-center p-0 animate-fadeIn !m-0 overflow-hidden">
          <button
            onClick={() => setActiveVideo(null)}
            className="absolute top-5 right-5 z-50 w-10 h-10 rounded-full bg-black/60 hover:bg-black/90 text-white flex items-center justify-center transition cursor-pointer border border-white/20 shadow-lg"
            title="Close Video"
          >
            <X className="w-5 h-5" />
          </button>

          {/* Direct Full Video Player */}
          <div className="w-full h-full flex items-center justify-center bg-black">
            <SecureVideoPlayer
              fileKey={activeVideo.fileKey}
              courseId={activeVideo.courseId}
              title={activeVideo.title}
              fullScreenDirect={true}
            />
          </div>
        </div>
      )}
    </div>
  );
}

