'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { motion } from 'framer-motion';
import {
  GraduationCap, Clock, BookOpen, ChevronRight, Lock, CheckCircle, Star,
  Sparkles, Factory, Play, ArrowLeft, ArrowRight
} from 'lucide-react';
import { ACADEMY_CURRICULUM } from '@/lib/dark-factory/academy';
import { ACADEMY_VIDEOS } from '@/lib/dark-factory/academy/video-map';
import type { StudentProgress } from '@/lib/dark-factory/academy';

const DIFFICULTY_COLORS = {
  beginner: 'text-green-400 bg-green-400/10 border-green-400/20',
  intermediate: 'text-amber-400 bg-amber-400/10 border-amber-400/20',
  advanced: 'text-red-400 bg-red-400/10 border-red-400/20',
};

export default function AcademyPage() {
  const [progress, setProgress] = useState<Record<string, StudentProgress>>({});
  const [mounted, setMounted] = useState(false);

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

  const completedCount = Object.values(progress).filter(p => p.completedAt).length;
  const totalLessons = ACADEMY_CURRICULUM.length;
  const progressPercent = totalLessons > 0 ? Math.round((completedCount / totalLessons) * 100) : 0;

  const isLessonUnlocked = (lessonId: string): boolean => {
    const lesson = ACADEMY_CURRICULUM.find(l => l.id === lessonId);
    if (!lesson) return false;
    if (lesson.prerequisites.length === 0) return true;
    return lesson.prerequisites.every(prereq => progress[prereq]?.completedAt);
  };

  return (
    <div className="min-h-screen bg-[#0C1222]">
      {/* Nav Bar */}
      <header className="sticky top-0 z-50 bg-[#0C1222]/95 backdrop-blur-lg border-b border-slate-800">
        <div className="max-w-6xl mx-auto px-6 py-4 flex items-center justify-between">
          <div className="flex items-center gap-6">
            <Link href="/dark-factory" className="flex items-center gap-2 text-gray-400 hover:text-white transition-colors">
              <ArrowLeft className="w-4 h-4" />
              <Factory className="w-5 h-5" />
              <span className="hidden sm:inline text-sm">The Hearth</span>
            </Link>
            <div className="h-5 w-px bg-slate-700" />
            <div className="flex items-center gap-2 text-sky-400">
              <GraduationCap className="w-5 h-5" />
              <span className="font-semibold">Academy</span>
            </div>
          </div>
          {mounted && completedCount > 0 && (
            <div className="flex items-center gap-3 text-sm">
              <span className="text-gray-400">{completedCount}/{totalLessons}</span>
              <div className="w-24 h-2 bg-white/10 rounded-full overflow-hidden">
                <div
                  className="h-full bg-gradient-to-r from-sky-500 to-orange-500 rounded-full transition-all duration-500"
                  style={{ width: `${progressPercent}%` }}
                />
              </div>
              <span className="text-sky-400 font-medium">{progressPercent}%</span>
            </div>
          )}
        </div>
      </header>

      {/* Hero */}
      <div className="relative overflow-hidden">
        <div className="absolute inset-0 bg-gradient-to-b from-sky-900/20 via-transparent to-transparent" />
        <div className="relative max-w-6xl mx-auto px-6 pt-12 pb-10">
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            className="text-center"
          >
            <h1 className="text-4xl lg:text-5xl font-bold text-white mb-4">
              Professor Tesa&apos;s Guide to<br />
              <span className="text-transparent bg-clip-text bg-gradient-to-r from-sky-400 to-orange-400">
                Autonomous Code Generation
              </span>
            </h1>
            <p className="text-gray-400 text-lg max-w-2xl mx-auto">
              10 video lectures. From orientation to capstone. Watch, learn, quiz.
            </p>
          </motion.div>
        </div>
      </div>

      {/* Tesa Intro */}
      <div className="max-w-6xl mx-auto px-6 pb-6">
        <div className="bg-gradient-to-br from-sky-500/10 to-orange-500/10 border border-sky-500/20 rounded-xl p-5 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">Professor Tesa Aria Murphy</p>
            <p className="text-gray-300 mt-1 text-sm">
              &ldquo;Welcome to my classroom. Every module has a video lecture, hands-on content, and a quiz.
              Pay attention. I grade hard.&rdquo;
            </p>
          </div>
        </div>
      </div>

      {/* Course Grid */}
      <div className="max-w-6xl mx-auto px-6 pb-20">
        <div className="grid gap-4 md:grid-cols-2">
          {ACADEMY_CURRICULUM.map((lesson, idx) => {
            const unlocked = isLessonUnlocked(lesson.id);
            const completed = !!progress[lesson.id]?.completedAt;
            const quizScore = progress[lesson.id]?.quizScore;
            const hasVideo = !!ACADEMY_VIDEOS[lesson.id];

            return (
              <motion.div
                key={lesson.id}
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: idx * 0.04 }}
              >
                {unlocked ? (
                  <Link
                    href={`/dark-factory/academy/${lesson.id}`}
                    className="block group h-full"
                  >
                    <div className={`h-full p-6 rounded-2xl border transition-all duration-300 hover:scale-[1.01] hover:shadow-lg hover:shadow-sky-500/5 ${
                      completed
                        ? 'bg-green-500/5 border-green-500/20 hover:border-green-400/40'
                        : 'bg-white/5 border-slate-700/50 hover:border-sky-500/40 hover:bg-white/[0.07]'
                    }`}>
                      {/* Module header */}
                      <div className="flex items-center justify-between mb-4">
                        <div className="flex items-center gap-3">
                          <div className={`w-12 h-12 rounded-xl flex items-center justify-center text-lg font-bold ${
                            completed ? 'bg-green-500/20 text-green-400' : 'bg-sky-500/20 text-sky-400'
                          }`}>
                            {completed ? <CheckCircle className="w-6 h-6" /> : lesson.moduleNumber}
                          </div>
                          <div>
                            <span className="text-xs text-gray-500 uppercase tracking-wider block">Module {lesson.moduleNumber}</span>
                            <h3 className="text-lg font-bold text-white group-hover:text-sky-400 transition-colors leading-tight">
                              {lesson.title}
                            </h3>
                          </div>
                        </div>
                        <ChevronRight className="w-5 h-5 text-gray-600 group-hover:text-sky-400 group-hover:translate-x-1 transition-all shrink-0" />
                      </div>

                      {/* Description */}
                      <p className="text-gray-400 text-sm mb-4 line-clamp-2">{lesson.description}</p>

                      {/* Meta row */}
                      <div className="flex items-center gap-3 flex-wrap">
                        {hasVideo && (
                          <span className="inline-flex items-center gap-1.5 text-xs font-medium px-3 py-1.5 rounded-full bg-sky-500/15 text-sky-400 border border-sky-500/20">
                            <Play className="w-3.5 h-3.5" /> Video Lecture
                          </span>
                        )}
                        <span className={`text-xs px-2.5 py-1 rounded-full border ${DIFFICULTY_COLORS[lesson.difficulty]}`}>
                          {lesson.difficulty}
                        </span>
                        <span className="flex items-center gap-1 text-xs text-gray-500">
                          <Clock className="w-3 h-3" /> {lesson.duration}
                        </span>
                        <span className="flex items-center gap-1 text-xs text-gray-500">
                          <BookOpen className="w-3 h-3" /> {lesson.sections.length} sections
                        </span>
                        {quizScore !== null && quizScore !== undefined && (
                          <span className="text-xs px-2.5 py-1 rounded-full text-amber-400 bg-amber-400/10 border border-amber-400/20 flex items-center gap-1">
                            <Star className="w-3 h-3" /> {quizScore}%
                          </span>
                        )}
                      </div>

                      {/* Tesa outfit teaser */}
                      <div className="mt-3 pt-3 border-t border-slate-700/30">
                        <p className="text-xs text-gray-600 italic">
                          Tesa wears: {lesson.tesaOutfit}
                        </p>
                      </div>
                    </div>
                  </Link>
                ) : (
                  <div className="h-full p-6 rounded-2xl border border-slate-800/50 bg-white/[0.02] opacity-50">
                    <div className="flex items-center gap-3 mb-4">
                      <div className="w-12 h-12 rounded-xl bg-slate-800/50 flex items-center justify-center">
                        <Lock className="w-5 h-5 text-gray-600" />
                      </div>
                      <div>
                        <span className="text-xs text-gray-600 uppercase tracking-wider block">Module {lesson.moduleNumber}</span>
                        <h3 className="text-lg font-bold text-gray-500">{lesson.title}</h3>
                      </div>
                    </div>
                    <p className="text-gray-600 text-sm">
                      Complete {lesson.prerequisites.map(p => {
                        const prereq = ACADEMY_CURRICULUM.find(l => l.id === p);
                        return prereq ? `Module ${prereq.moduleNumber}` : p;
                      }).join(', ')} first
                    </p>
                  </div>
                )}
              </motion.div>
            );
          })}
        </div>

        {/* Bottom CTA */}
        <div className="mt-12 text-center">
          <Link
            href="/dark-factory"
            className="inline-flex items-center gap-2 text-gray-400 hover:text-white transition-colors"
          >
            <ArrowLeft className="w-4 h-4" /> Back to The Hearth
          </Link>
        </div>
      </div>
    </div>
  );
}
