'use client';

import { useState, useEffect, useCallback } from 'react';
import { useParams, useRouter } from 'next/navigation';
import Link from 'next/link';
import { motion, AnimatePresence } from 'framer-motion';
import {
  ArrowLeft, ArrowRight, CheckCircle, XCircle, BookOpen, Clock,
  Sparkles, GraduationCap, Trophy, RotateCcw, ChevronDown, ChevronUp, ExternalLink,
  Play, Loader2
} from 'lucide-react';
import { ACADEMY_CURRICULUM } from '@/lib/dark-factory/academy';
import { ACADEMY_VIDEOS } from '@/lib/dark-factory/academy/video-map';
import type { StudentProgress, QuizQuestion } from '@/lib/dark-factory/academy';

export default function LessonPage() {
  const params = useParams();
  const router = useRouter();
  const lessonId = params.lessonId as string;
  const lesson = ACADEMY_CURRICULUM.find(l => l.id === lessonId);
  const lessonIndex = ACADEMY_CURRICULUM.findIndex(l => l.id === lessonId);
  const nextLesson = lessonIndex >= 0 && lessonIndex < ACADEMY_CURRICULUM.length - 1
    ? ACADEMY_CURRICULUM[lessonIndex + 1]
    : null;

  const [currentSection, setCurrentSection] = useState(0);
  const [showQuiz, setShowQuiz] = useState(false);
  const [quizAnswers, setQuizAnswers] = useState<Record<string, number>>({});
  const [quizSubmitted, setQuizSubmitted] = useState(false);
  const [expandedCode, setExpandedCode] = useState<Record<string, boolean>>({});
  const [progress, setProgress] = useState<Record<string, StudentProgress>>({});
  const [mounted, setMounted] = useState(false);
  const [videoUrl, setVideoUrl] = useState<string | null>(null);
  const [videoLoading, setVideoLoading] = useState(false);
  const [videoError, setVideoError] = useState(false);

  useEffect(() => {
    setMounted(true);
    try {
      const saved = localStorage.getItem('df-academy-progress');
      if (saved) setProgress(JSON.parse(saved));
    } catch { /* ignore */ }
  }, []);

  // Fetch video URL on mount
  useEffect(() => {
    if (!lessonId || !ACADEMY_VIDEOS[lessonId]) return;
    setVideoLoading(true);
    fetch(`/api/dark-factory/academy/video?lessonId=${lessonId}`)
      .then(r => r.json())
      .then(data => {
        if (data.videoUrl) setVideoUrl(data.videoUrl);
        else setVideoError(true);
      })
      .catch(() => setVideoError(true))
      .finally(() => setVideoLoading(false));
  }, [lessonId]);

  const saveProgress = useCallback((updated: Record<string, StudentProgress>) => {
    setProgress(updated);
    try {
      localStorage.setItem('df-academy-progress', JSON.stringify(updated));
    } catch { /* ignore */ }
  }, []);

  const markSectionComplete = useCallback((sectionId: string) => {
    if (!lesson) return;
    const current = progress[lesson.id] || {
      lessonId: lesson.id,
      sectionsCompleted: [],
      quizScore: null,
      quizAttempts: 0,
      completedAt: null,
      startedAt: new Date().toISOString(),
    };
    if (!current.sectionsCompleted.includes(sectionId)) {
      const updated = {
        ...progress,
        [lesson.id]: { ...current, sectionsCompleted: [...current.sectionsCompleted, sectionId] },
      };
      saveProgress(updated);
    }
  }, [lesson, progress, saveProgress]);

  const handleQuizSubmit = useCallback(() => {
    if (!lesson) return;
    const totalQuestions = lesson.quiz.length;
    const correctCount = lesson.quiz.filter(
      q => quizAnswers[q.id] === q.correctIndex
    ).length;
    const score = Math.round((correctCount / totalQuestions) * 100);
    setQuizSubmitted(true);

    const current = progress[lesson.id] || {
      lessonId: lesson.id,
      sectionsCompleted: [],
      quizScore: null,
      quizAttempts: 0,
      completedAt: null,
      startedAt: new Date().toISOString(),
    };
    const updated = {
      ...progress,
      [lesson.id]: {
        ...current,
        quizScore: score,
        quizAttempts: current.quizAttempts + 1,
        completedAt: score >= 70 ? new Date().toISOString() : current.completedAt,
      },
    };
    saveProgress(updated);
  }, [lesson, quizAnswers, progress, saveProgress]);

  const handleRetakeQuiz = () => {
    setQuizAnswers({});
    setQuizSubmitted(false);
  };

  if (!lesson) {
    return (
      <div className="min-h-screen bg-[#0C1222] flex items-center justify-center">
        <div className="text-center">
          <h1 className="text-2xl text-white mb-4">Lesson not found</h1>
          <Link href="/dark-factory/academy" className="text-sky-400 hover:underline">Back to Academy</Link>
        </div>
      </div>
    );
  }

  const currentSectionData = lesson.sections[currentSection];
  const allSectionsViewed = mounted && lesson.sections.every(
    s => progress[lesson.id]?.sectionsCompleted?.includes(s.id)
  );
  const quizScore = progress[lesson.id]?.quizScore;
  const isCompleted = !!progress[lesson.id]?.completedAt;

  return (
    <div className="min-h-screen bg-[#0C1222]">
      {/* Header */}
      <div className="sticky top-0 z-20 bg-[#0C1222]/95 backdrop-blur border-b border-slate-800">
        <div className="max-w-5xl mx-auto px-6 py-4 flex items-center justify-between">
          <Link href="/dark-factory/academy" className="flex items-center gap-2 text-gray-400 hover:text-white transition-colors text-sm">
            <ArrowLeft className="w-4 h-4" /> Academy
          </Link>
          <div className="text-center">
            <span className="text-xs text-gray-500 uppercase tracking-wider">Module {lesson.moduleNumber}</span>
            <h1 className="text-white font-semibold text-sm">{lesson.title}</h1>
          </div>
          <div className="flex items-center gap-2 text-xs text-gray-500">
            <Clock className="w-3 h-3" /> {lesson.duration}
          </div>
        </div>
      </div>

      <div className="max-w-5xl mx-auto px-6 py-8">
        {/* Tesa Intro Card */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="bg-gradient-to-br from-sky-500/10 to-orange-500/10 border border-sky-500/20 rounded-xl p-6 mb-8"
        >
          <div className="flex items-start gap-4">
            <div className="w-10 h-10 rounded-full bg-sky-500/20 flex items-center justify-center shrink-0">
              <Sparkles className="w-5 h-5 text-sky-400" />
            </div>
            <div>
              <p className="text-sky-400 text-sm font-medium mb-1">Professor Tesa — {lesson.tesaOutfit}</p>
              <p className="text-white italic">&ldquo;{lesson.tesaQuote}&rdquo;</p>
            </div>
          </div>
        </motion.div>

        {/* Video Lecture */}
        {ACADEMY_VIDEOS[lessonId] && (
          <div className="mb-8">
            <div className="bg-black/40 border border-slate-700/50 rounded-xl overflow-hidden">
              <div className="px-4 py-3 border-b border-slate-700/50 flex items-center gap-2">
                <Play className="w-4 h-4 text-sky-400" />
                <span className="text-sm text-gray-300 font-medium">Video Lecture — Professor Tesa</span>
                {ACADEMY_VIDEOS[lessonId] && (
                  <span className="text-xs text-gray-500 ml-auto">{ACADEMY_VIDEOS[lessonId].duration}s</span>
                )}
              </div>
              <div className="aspect-video bg-black flex items-center justify-center">
                {videoLoading && (
                  <div className="flex flex-col items-center gap-3">
                    <Loader2 className="w-8 h-8 text-sky-400 animate-spin" />
                    <p className="text-gray-400 text-sm">Loading lecture video...</p>
                  </div>
                )}
                {videoError && !videoLoading && (
                  <div className="flex flex-col items-center gap-3 text-gray-500">
                    <Play className="w-8 h-8" />
                    <p className="text-sm">Video unavailable — continue with text content below</p>
                  </div>
                )}
                {videoUrl && !videoLoading && (
                  <video
                    src={videoUrl}
                    controls
                    className="w-full h-full"
                    poster=""
                    preload="metadata"
                  >
                    Your browser does not support the video tag.
                  </video>
                )}
              </div>
            </div>
          </div>
        )}

        {/* Learning Objectives */}
        <div className="bg-white/5 border border-slate-700/50 rounded-xl p-6 mb-8">
          <h3 className="text-white font-semibold mb-3 flex items-center gap-2">
            <GraduationCap className="w-5 h-5 text-sky-400" /> Learning Objectives
          </h3>
          <ul className="space-y-2">
            {lesson.learningObjectives.map((obj, i) => (
              <li key={i} className="flex items-start gap-2 text-gray-300 text-sm">
                <CheckCircle className="w-4 h-4 text-sky-500/50 mt-0.5 shrink-0" />
                {obj}
              </li>
            ))}
          </ul>
        </div>

        {/* Section Navigation */}
        {!showQuiz && (
          <div className="flex items-center gap-2 mb-6 overflow-x-auto pb-2">
            {lesson.sections.map((section, idx) => {
              const viewed = progress[lesson.id]?.sectionsCompleted?.includes(section.id);
              return (
                <button
                  key={section.id}
                  onClick={() => setCurrentSection(idx)}
                  className={`px-4 py-2 rounded-lg text-sm whitespace-nowrap transition-colors ${
                    currentSection === idx
                      ? 'bg-sky-500/20 text-sky-400 border border-sky-500/30'
                      : viewed
                        ? 'bg-green-500/10 text-green-400 border border-green-500/20'
                        : 'bg-white/5 text-gray-400 border border-slate-700/50 hover:text-white'
                  }`}
                >
                  {viewed && <CheckCircle className="w-3 h-3 inline mr-1" />}
                  {section.title}
                </button>
              );
            })}
            <button
              onClick={() => setShowQuiz(true)}
              className={`px-4 py-2 rounded-lg text-sm whitespace-nowrap transition-colors ${
                showQuiz
                  ? 'bg-amber-500/20 text-amber-400 border border-amber-500/30'
                  : 'bg-white/5 text-gray-400 border border-slate-700/50 hover:text-white'
              }`}
            >
              🏆 Quiz
            </button>
          </div>
        )}

        {/* Content or Quiz */}
        <AnimatePresence mode="wait">
          {!showQuiz && currentSectionData ? (
            <motion.div
              key={currentSectionData.id}
              initial={{ opacity: 0, x: 20 }}
              animate={{ opacity: 1, x: 0 }}
              exit={{ opacity: 0, x: -20 }}
              onAnimationComplete={() => markSectionComplete(currentSectionData.id)}
              className="space-y-6"
            >
              <h2 className="text-2xl font-bold text-white">{currentSectionData.title}</h2>

              {/* Content - render markdown-like */}
              <div className="text-gray-300 leading-relaxed whitespace-pre-wrap text-[15px]">
                {currentSectionData.content.split('\n').map((line, i) => {
                  if (line.startsWith('**') && line.endsWith('**')) {
                    return <p key={i} className="font-semibold text-white mt-4 mb-2">{line.replace(/\*\*/g, '')}</p>;
                  }
                  if (line.startsWith('|')) {
                    return <p key={i} className="font-mono text-sm text-gray-400">{line}</p>;
                  }
                  if (line.match(/^\d+\./)) {
                    return <p key={i} className="ml-4">{line}</p>;
                  }
                  return <p key={i}>{line}</p>;
                })}
              </div>

              {/* Code Example */}
              {currentSectionData.codeExample && (
                <div className="border border-slate-700/50 rounded-xl overflow-hidden">
                  <button
                    onClick={() => setExpandedCode(prev => ({ ...prev, [currentSectionData.id]: !prev[currentSectionData.id] }))}
                    className="w-full flex items-center justify-between px-4 py-3 bg-slate-800/50 text-sm text-gray-300 hover:text-white transition-colors"
                  >
                    <span>💻 {currentSectionData.codeExample.caption}</span>
                    {expandedCode[currentSectionData.id] ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
                  </button>
                  {expandedCode[currentSectionData.id] && (
                    <pre className="p-4 bg-black/50 text-sm text-green-300 overflow-x-auto">
                      <code>{currentSectionData.codeExample.code}</code>
                    </pre>
                  )}
                </div>
              )}

              {/* Tesa Note */}
              {currentSectionData.tesaNote && (
                <div className="bg-sky-500/5 border border-sky-500/20 rounded-xl p-4 flex items-start gap-3">
                  <Sparkles className="w-5 h-5 text-sky-400 mt-0.5 shrink-0" />
                  <div>
                    <p className="text-sky-400 text-sm font-medium mb-1">Tesa says:</p>
                    <p className="text-gray-300 text-sm italic">&ldquo;{currentSectionData.tesaNote}&rdquo;</p>
                  </div>
                </div>
              )}

              {/* Diagram */}
              {currentSectionData.diagram && (
                <div className="bg-slate-800/30 border border-slate-700/50 rounded-xl p-4">
                  <p className="font-mono text-sm text-sky-300 text-center">{currentSectionData.diagram}</p>
                </div>
              )}

              {/* Navigation */}
              <div className="flex items-center justify-between pt-6 border-t border-slate-800">
                <button
                  onClick={() => setCurrentSection(Math.max(0, currentSection - 1))}
                  disabled={currentSection === 0}
                  className="flex items-center gap-2 text-gray-400 hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
                >
                  <ArrowLeft className="w-4 h-4" /> Previous
                </button>
                {currentSection < lesson.sections.length - 1 ? (
                  <button
                    onClick={() => setCurrentSection(currentSection + 1)}
                    className="flex items-center gap-2 text-sky-400 hover:text-sky-300 transition-colors"
                  >
                    Next <ArrowRight className="w-4 h-4" />
                  </button>
                ) : (
                  <button
                    onClick={() => setShowQuiz(true)}
                    className="flex items-center gap-2 px-4 py-2 bg-amber-500/20 text-amber-400 rounded-lg hover:bg-amber-500/30 transition-colors"
                  >
                    <Trophy className="w-4 h-4" /> Take the Quiz
                  </button>
                )}
              </div>
            </motion.div>
          ) : showQuiz ? (
            <motion.div
              key="quiz"
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              className="space-y-6"
            >
              <div className="flex items-center justify-between">
                <h2 className="text-2xl font-bold text-white flex items-center gap-2">
                  <Trophy className="w-6 h-6 text-amber-400" /> Module {lesson.moduleNumber} Quiz
                </h2>
                <button onClick={() => setShowQuiz(false)} className="text-gray-400 hover:text-white text-sm">
                  Back to lesson
                </button>
              </div>

              {lesson.quiz.map((q, idx) => {
                const answered = quizAnswers[q.id] !== undefined;
                const isCorrect = quizSubmitted && quizAnswers[q.id] === q.correctIndex;
                const isWrong = quizSubmitted && answered && quizAnswers[q.id] !== q.correctIndex;

                return (
                  <div key={q.id} className={`p-6 rounded-xl border transition-colors ${
                    isCorrect ? 'bg-green-500/5 border-green-500/20' :
                    isWrong ? 'bg-red-500/5 border-red-500/20' :
                    'bg-white/5 border-slate-700/50'
                  }`}>
                    <p className="text-white font-medium mb-4">{idx + 1}. {q.question}</p>
                    <div className="space-y-2">
                      {q.options.map((opt, optIdx) => (
                        <button
                          key={optIdx}
                          onClick={() => !quizSubmitted && setQuizAnswers(prev => ({ ...prev, [q.id]: optIdx }))}
                          disabled={quizSubmitted}
                          className={`w-full text-left px-4 py-3 rounded-lg border transition-colors text-sm ${
                            quizSubmitted && optIdx === q.correctIndex
                              ? 'bg-green-500/10 border-green-500/30 text-green-400'
                              : quizSubmitted && quizAnswers[q.id] === optIdx && optIdx !== q.correctIndex
                                ? 'bg-red-500/10 border-red-500/30 text-red-400'
                                : quizAnswers[q.id] === optIdx
                                  ? 'bg-sky-500/10 border-sky-500/30 text-sky-400'
                                  : 'bg-white/5 border-slate-700/50 text-gray-300 hover:border-sky-500/30'
                          }`}
                        >
                          {opt}
                        </button>
                      ))}
                    </div>

                    {/* Explanation */}
                    {quizSubmitted && (
                      <div className={`mt-4 p-3 rounded-lg text-sm ${
                        isCorrect ? 'bg-green-500/10 text-green-300' : 'bg-red-500/10 text-red-300'
                      }`}>
                        <p className="font-medium mb-1">
                          {isCorrect ? <CheckCircle className="w-4 h-4 inline mr-1" /> : <XCircle className="w-4 h-4 inline mr-1" />}
                          {isCorrect ? 'Correct!' : 'Incorrect'}
                        </p>
                        <p className="text-gray-300">{q.explanation}</p>
                        <p className="mt-2 italic text-gray-400">
                          Tesa: &ldquo;{isCorrect ? q.tesaReaction.correct : q.tesaReaction.incorrect}&rdquo;
                        </p>
                      </div>
                    )}
                  </div>
                );
              })}

              {/* Submit / Results */}
              {!quizSubmitted ? (
                <button
                  onClick={handleQuizSubmit}
                  disabled={Object.keys(quizAnswers).length < lesson.quiz.length}
                  className="w-full py-3 bg-amber-500/20 text-amber-400 rounded-lg font-medium hover:bg-amber-500/30 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
                >
                  Submit Quiz ({Object.keys(quizAnswers).length}/{lesson.quiz.length} answered)
                </button>
              ) : (
                <div className="p-6 bg-white/5 border border-slate-700/50 rounded-xl text-center">
                  <Trophy className={`w-12 h-12 mx-auto mb-3 ${
                    (quizScore ?? 0) >= 70 ? 'text-amber-400' : 'text-gray-500'
                  }`} />
                  <p className="text-2xl font-bold text-white mb-1">
                    {quizScore ?? 0}%
                  </p>
                  <p className="text-gray-400 mb-4">
                    {(quizScore ?? 0) >= 70
                      ? 'Module complete! You may proceed.'
                      : 'You need 70% to pass. Review the material and try again.'
                    }
                  </p>
                  <div className="flex items-center justify-center gap-3">
                    {(quizScore ?? 0) < 70 && (
                      <button
                        onClick={handleRetakeQuiz}
                        className="flex items-center gap-2 px-4 py-2 bg-white/10 text-white rounded-lg hover:bg-white/20 transition-colors"
                      >
                        <RotateCcw className="w-4 h-4" /> Retake Quiz
                      </button>
                    )}
                    {nextLesson && (quizScore ?? 0) >= 70 && (
                      <Link
                        href={`/dark-factory/academy/${nextLesson.id}`}
                        className="flex items-center gap-2 px-4 py-2 bg-sky-500/20 text-sky-400 rounded-lg hover:bg-sky-500/30 transition-colors"
                      >
                        Next Module <ArrowRight className="w-4 h-4" />
                      </Link>
                    )}
                  </div>
                </div>
              )}
            </motion.div>
          ) : null}
        </AnimatePresence>

        {/* Further Reading */}
        {lesson.furtherReading.length > 0 && (
          <div className="mt-12 p-6 bg-white/5 border border-slate-700/50 rounded-xl">
            <h3 className="text-white font-semibold mb-3 flex items-center gap-2">
              <BookOpen className="w-5 h-5 text-sky-400" /> Further Reading
            </h3>
            <div className="space-y-2">
              {lesson.furtherReading.map((link, i) => (
                <a
                  key={i}
                  href={link.url}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="flex items-center gap-2 text-sky-400 hover:text-sky-300 text-sm transition-colors"
                >
                  <ExternalLink className="w-3 h-3" /> {link.title}
                </a>
              ))}
            </div>
          </div>
        )}

        {/* Continue to Next Module / Back to Academy */}
        <div className="mt-12 pt-8 border-t border-slate-700/50">
          <div className="flex items-center justify-between gap-4">
            {lessonIndex > 0 && (
              <Link
                href={`/dark-factory/academy/${ACADEMY_CURRICULUM[lessonIndex - 1].id}`}
                className="flex items-center gap-2 px-5 py-3 rounded-xl bg-white/5 border border-slate-700/50 text-gray-400 hover:text-white hover:border-slate-600 transition-colors text-sm"
              >
                <ArrowLeft className="w-4 h-4" />
                <span className="hidden sm:inline">Module {ACADEMY_CURRICULUM[lessonIndex - 1].moduleNumber}:</span> {ACADEMY_CURRICULUM[lessonIndex - 1].title}
              </Link>
            )}
            {!lessonIndex && <div />}
            {nextLesson ? (
              <Link
                href={`/dark-factory/academy/${nextLesson.id}`}
                className="flex items-center gap-2 px-6 py-3 rounded-xl bg-sky-500/20 border border-sky-500/30 text-sky-400 hover:bg-sky-500/30 hover:text-sky-300 transition-colors font-medium text-sm ml-auto"
              >
                Continue: Module {nextLesson.moduleNumber} — {nextLesson.title} <ArrowRight className="w-4 h-4" />
              </Link>
            ) : (
              <Link
                href="/dark-factory/academy"
                className="flex items-center gap-2 px-6 py-3 rounded-xl bg-gradient-to-r from-amber-500/20 to-sky-500/20 border border-amber-500/30 text-amber-400 hover:from-amber-500/30 hover:to-sky-500/30 transition-colors font-medium text-sm ml-auto"
              >
                <Trophy className="w-4 h-4" /> Back to Academy — Course Complete!
              </Link>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
