"use client";

import { useEffect, useMemo, useState, useTransition } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Check, Lock, PlayCircle } from "lucide-react";
import { toggleLessonComplete } from "@/app/(protected)/courses/[slug]/learn/actions";
import ProgressBar from "@/components/ProgressBar";

type ClassroomLesson = {
  id: string;
  title: string;
  description: string;
  videoUrl: string | null;
  estimatedDuration: number;
};

type ClassroomModule = {
  id: string;
  title: string;
  lessons: ClassroomLesson[];
};

type StudentClassroomClientProps = {
  courseSlug: string;
  courseTitle: string;
  modules: ClassroomModule[];
  initialSelectedLessonId: string;
  initialCompletedLessonIds: string[];
};

export default function StudentClassroomClient({
  courseSlug,
  courseTitle,
  modules,
  initialSelectedLessonId,
  initialCompletedLessonIds,
}: StudentClassroomClientProps) {
  const router = useRouter();
  const [isSaving, startTransition] = useTransition();
  const [selectedLessonId, setSelectedLessonId] = useState(initialSelectedLessonId);
  const [completedLessonIds, setCompletedLessonIds] = useState(initialCompletedLessonIds);

  useEffect(() => {
    setSelectedLessonId(initialSelectedLessonId);
  }, [initialSelectedLessonId]);

  useEffect(() => {
    setCompletedLessonIds(initialCompletedLessonIds);
  }, [initialCompletedLessonIds]);

  const flatLessons = useMemo(() => modules.flatMap((module) => module.lessons), [modules]);
  const completedSet = useMemo(() => new Set(completedLessonIds), [completedLessonIds]);

  const totalLessons = flatLessons.length;
  const completedCount = completedLessonIds.length;
  const progressPercent = totalLessons > 0 ? Math.round((completedCount / totalLessons) * 100) : 0;

  const selectedLesson =
    flatLessons.find((lesson) => lesson.id === selectedLessonId) ?? flatLessons[0] ?? null;

  const isRestricted = (lessonId: string) => {
    const lessonIndex = flatLessons.findIndex((lesson) => lesson.id === lessonId);
    if (lessonIndex <= 0) return false;
    if (completedSet.has(lessonId)) return false;
    const previousLesson = flatLessons[lessonIndex - 1];
    return !completedSet.has(previousLesson.id);
  };

  const navigateToLesson = (lessonId: string) => {
    if (isRestricted(lessonId)) return;
    setSelectedLessonId(lessonId);
    router.push(`/courses/${courseSlug}/learn?lesson=${lessonId}`, { scroll: false });
  };

  const handleToggleComplete = async () => {
    if (!selectedLesson || isSaving) return;

    const lessonId = selectedLesson.id;
    const wasCompleted = completedSet.has(lessonId);

    setCompletedLessonIds((prev) =>
      wasCompleted ? prev.filter((id) => id !== lessonId) : [...prev, lessonId],
    );

    startTransition(async () => {
      const result = await toggleLessonComplete({ courseSlug, lessonId });

      if (!result.success) {
        setCompletedLessonIds((prev) =>
          wasCompleted ? [...prev, lessonId] : prev.filter((id) => id !== lessonId),
        );
        return;
      }

      setCompletedLessonIds((prev) => {
        if (result.isCompleted) {
          return prev.includes(lessonId) ? prev : [...prev, lessonId];
        }
        return prev.filter((id) => id !== lessonId);
      });

      router.refresh();
    });
  };

  if (!selectedLesson) {
    return (
      <div className="rounded-xl border border-slate-200 bg-white p-6">
        <h1 className="text-2xl font-semibold text-slate-900">No lessons available yet</h1>
        <p className="mt-2 text-sm text-slate-600">This course does not have lessons configured.</p>
      </div>
    );
  }

  return (
    <div className="grid gap-6 lg:grid-cols-[1.7fr_1fr]">
      <section className="space-y-4 rounded-xl border border-slate-200 bg-white p-5">
        <Link href={`/courses/${courseSlug}`} className="text-sm font-medium text-slate-600 hover:text-slate-900">
          {"<-"} Back to Course
        </Link>

        <div className="aspect-video overflow-hidden rounded-xl border border-slate-200 bg-black">
          {selectedLesson.videoUrl ? (
            <video
              key={`${selectedLesson.id}-${selectedLesson.videoUrl}`}
              className="h-full w-full"
              controls
              onEnded={handleToggleComplete}
              src={selectedLesson.videoUrl}
            />
          ) : (
            <div className="flex h-full items-center justify-center text-sm text-slate-300">
              Video not available for this lesson
            </div>
          )}
        </div>

        <div className="space-y-2 rounded-xl border border-slate-200 bg-white p-4">
          <h1 className="text-2xl font-semibold text-slate-900">{selectedLesson.title}</h1>
          {selectedLesson.description ? (
            <p className="text-sm text-slate-600">{selectedLesson.description}</p>
          ) : null}
          <p className="text-xs text-slate-500">
            Duration: {Math.max(1, Math.ceil(selectedLesson.estimatedDuration / 60))} min
          </p>
        </div>

        <button
          type="button"
          onClick={handleToggleComplete}
          disabled={isSaving}
          className="rounded-md border border-slate-300 bg-slate-900 px-4 py-2 text-sm font-medium text-white hover:bg-slate-800 disabled:opacity-60"
        >
          {completedSet.has(selectedLesson.id) ? "Mark as Incomplete" : "Mark as Complete"}
        </button>
      </section>

      <aside className="rounded-xl border border-slate-200 bg-white p-4">
        <h2 className="mb-3 text-lg font-semibold text-slate-900">Course Content</h2>
        <p className="mb-3 text-xs text-slate-500">{courseTitle}</p>
        <div className="mb-4">
          <ProgressBar
            value={progressPercent}
            label={`${completedCount}/${totalLessons} lessons (${progressPercent}%)`}
          />
        </div>

        <div className="max-h-[70vh] space-y-4 overflow-y-auto pr-1">
          {modules.map((module, moduleIndex) => (
            <div key={module.id} className="rounded-xl border border-slate-200 bg-slate-50/40">
              <div className="border-b border-slate-200 px-3 py-2">
                <p className="text-sm font-semibold text-slate-800">
                  Module {moduleIndex + 1}: {module.title}
                </p>
              </div>

              <div className="space-y-1 p-2">
                {module.lessons.map((lesson, lessonIndex) => {
                  const completed = completedSet.has(lesson.id);
                  const restricted = isRestricted(lesson.id);
                  const active = lesson.id === selectedLesson.id;

                  return (
                    <button
                      key={lesson.id}
                      type="button"
                      disabled={restricted}
                      onClick={() => navigateToLesson(lesson.id)}
                      className={`flex w-full items-center gap-2 rounded-lg border px-2 py-2 text-left text-sm transition-colors ${
                        active
                          ? "border-slate-300 bg-white text-slate-900"
                          : "border-transparent bg-white/70 text-slate-700 hover:border-slate-200"
                      } ${restricted ? "cursor-not-allowed opacity-60 hover:border-transparent" : ""}`}
                    >
                      <span className="inline-flex h-5 w-5 items-center justify-center">
                        {completed ? (
                          <Check className="h-4 w-4 text-emerald-600" />
                        ) : restricted ? (
                          <Lock className="h-4 w-4 text-slate-400" />
                        ) : (
                          <PlayCircle className="h-4 w-4 text-slate-500" />
                        )}
                      </span>
                      <span className="line-clamp-1">
                        {lessonIndex + 1}. {lesson.title}
                      </span>
                    </button>
                  );
                })}
              </div>
            </div>
          ))}
        </div>
      </aside>
    </div>
  );
}
