"use client";

import Link from "next/link";
import { useEffect, useState } from "react";
import { getTeacherCourses, teacherCoursesUpdatedEventName } from "@/lib/data/teacherCourses";
import type { Course } from "@/types/course";

export default function TeacherDashboardClient() {
  const [courses, setCourses] = useState<Course[]>([]);

  useEffect(() => {
    const load = () => setCourses(getTeacherCourses());
    load();
    window.addEventListener(teacherCoursesUpdatedEventName, load);
    return () => window.removeEventListener(teacherCoursesUpdatedEventName, load);
  }, []);

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between gap-3">
        <div>
          <h1 className="text-3xl font-bold text-slate-900">Teacher Dashboard</h1>
          <p className="text-slate-600">Manage teacher-created courses stored locally for MVP.</p>
        </div>
        <Link
          className="rounded-md bg-ink px-4 py-2 text-sm font-semibold text-white hover:brightness-105"
          href="/teacher/courses/new"
        >
          Create course
        </Link>
      </div>

      {courses.length === 0 ? (
        <div className="rounded-xl border border-dashed border-slate-300 bg-white p-6 text-sm text-slate-600">
          No teacher-created courses yet.
        </div>
      ) : (
        <div className="grid gap-4">
          {courses.map((course) => (
            <article key={course.slug} className="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
              <div className="flex flex-wrap items-start justify-between gap-3">
                <div>
                  <p className="text-xs font-semibold uppercase tracking-wide text-brand">{course.level}</p>
                  <h2 className="text-xl font-semibold text-slate-900">{course.title}</h2>
                  <p className="mt-1 text-sm text-slate-600">{course.summary}</p>
                </div>
                <div className="flex gap-2">
                  <Link
                    className="rounded-md border border-slate-300 px-3 py-1.5 text-sm hover:bg-slate-50"
                    href={`/teacher/courses/${course.slug}/edit`}
                  >
                    Edit
                  </Link>
                  <Link
                    className="rounded-md border border-slate-300 px-3 py-1.5 text-sm hover:bg-slate-50"
                    href={`/teacher/courses/${course.slug}/lessons/new`}
                  >
                    Add lesson
                  </Link>
                </div>
              </div>
            </article>
          ))}
        </div>
      )}
    </div>
  );
}
