"use client";

import { useEffect, useMemo, useState } from "react";
import CourseCard from "@/components/CourseCard";
import Tabs from "@/components/Tabs";
import { getAllCourses } from "@/lib/data/courseCatalog";
import {
  getCourseProgressPercent,
  progressUpdatedEventName,
} from "@/lib/progress/localProgress";
import { teacherCoursesUpdatedEventName } from "@/lib/data/teacherCourses";
import { supabaseBrowser } from "@/lib/supabase/browser";
import type { Course, CourseLevel } from "@/types/course";

const levels: CourseLevel[] = ["Beginner", "Intermediate", "Advanced"];

export default function CoursesPage() {
  const [activeLevel, setActiveLevel] = useState<CourseLevel>("Beginner");
  const [userId, setUserId] = useState("guest");
  const [progressBySlug, setProgressBySlug] = useState<Record<string, number>>({});
  const [courses, setCourses] = useState<Course[]>(() => getAllCourses());

  const counts = useMemo(
    () =>
      levels.reduce(
        (acc, level) => {
          acc[level] = courses.filter((course) => course.level === level).length;
          return acc;
        },
        {} as Record<CourseLevel, number>,
      ),
    [courses],
  );

  useEffect(() => {
    const loadCourses = () => {
      setCourses(getAllCourses());
    };

    loadCourses();
    window.addEventListener(teacherCoursesUpdatedEventName, loadCourses);
    return () => window.removeEventListener(teacherCoursesUpdatedEventName, loadCourses);
  }, []);

  useEffect(() => {
    const client = supabaseBrowser();
    if (!client) return;

    client.auth.getUser().then(({ data }) => {
      setUserId(data.user?.id ?? "guest");
    });

    const { data } = client.auth.onAuthStateChange((_event, session) => {
      setUserId(session?.user?.id ?? "guest");
    });

    return () => data.subscription.unsubscribe();
  }, []);

  useEffect(() => {
    const load = () => {
      const nextProgress: Record<string, number> = {};
      for (const course of courses) {
        nextProgress[course.slug] = getCourseProgressPercent(userId, course.slug, course.lessons.length);
      }
      setProgressBySlug(nextProgress);
    };

    load();
    window.addEventListener(progressUpdatedEventName, load);
    window.addEventListener(teacherCoursesUpdatedEventName, load);
    return () => {
      window.removeEventListener(progressUpdatedEventName, load);
      window.removeEventListener(teacherCoursesUpdatedEventName, load);
    };
  }, [courses, userId]);

  const filteredCourses = useMemo(
    () => courses.filter((course) => course.level === activeLevel),
    [activeLevel, courses],
  );

  return (
    <div className="space-y-8">
      <section className="acve-panel p-5">
        <div className="flex flex-wrap items-center gap-4">
          <Tabs active={activeLevel} onChange={setActiveLevel} options={levels} />
          <span className="text-base font-semibold text-slate-600">{counts[activeLevel]} courses in this level</span>
        </div>
      </section>

      <section className="acve-panel px-6 py-8">
        <div className="flex items-start gap-4">
          <div className="mt-1 flex h-12 w-12 items-center justify-center rounded-xl bg-accent text-2xl font-semibold text-white">C</div>
          <div>
            <h1 className="text-3xl text-[#202a39] md:text-5xl">{activeLevel} Level Courses</h1>
            <p className="mt-2 text-base text-slate-600 md:text-2xl">
              {activeLevel === "Beginner"
                ? "Perfect for those new to English law. Build a strong foundation with fundamental concepts and terminology."
                : activeLevel === "Intermediate"
                  ? "Deepen practical analysis skills with real-world drafting, contract review, and legal communication."
                  : "Master complex legal reasoning and advanced writing for high-impact legal practice."}
            </p>
          </div>
        </div>
      </section>

      <div className="grid gap-5 md:grid-cols-2 xl:grid-cols-3">
        {filteredCourses.map((course) => (
          <CourseCard key={course.slug} course={course} progress={progressBySlug[course.slug] ?? 0} />
        ))}
      </div>
    </div>
  );
}
