"use client";

import Link from "next/link";
import { FormEvent, useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { getTeacherCourseBySlug, teacherCoursesUpdatedEventName, updateTeacherCourse } from "@/lib/data/teacherCourses";
import type { Course, CourseLevel } from "@/types/course";

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

type TeacherEditCourseFormProps = {
  slug: string;
};

export default function TeacherEditCourseForm({ slug }: TeacherEditCourseFormProps) {
  const router = useRouter();
  const [course, setCourse] = useState<Course | null>(null);
  const [title, setTitle] = useState("");
  const [level, setLevel] = useState<CourseLevel>("Beginner");
  const [summary, setSummary] = useState("");
  const [instructor, setInstructor] = useState("");
  const [weeks, setWeeks] = useState(4);
  const [rating, setRating] = useState(5);
  const [saved, setSaved] = useState(false);

  useEffect(() => {
    const load = () => {
      const found = getTeacherCourseBySlug(slug) ?? null;
      setCourse(found);
      if (!found) return;
      setTitle(found.title);
      setLevel(found.level);
      setSummary(found.summary);
      setInstructor(found.instructor);
      setWeeks(found.weeks);
      setRating(found.rating);
    };

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

  const submit = (event: FormEvent) => {
    event.preventDefault();
    if (!course) return;

    updateTeacherCourse(course.slug, {
      title: title.trim(),
      level,
      summary: summary.trim(),
      instructor: instructor.trim(),
      weeks: Math.max(1, weeks),
      rating: Math.min(5, Math.max(0, rating)),
    });
    setSaved(true);
    window.setTimeout(() => setSaved(false), 1200);
  };

  if (!course) {
    return (
      <div className="mx-auto max-w-2xl space-y-3 rounded-xl border border-slate-200 bg-white p-6 shadow-sm">
        <h1 className="text-2xl font-bold text-slate-900">Teacher course not found</h1>
        <p className="text-slate-600">This editor only works for courses created in the teacher area.</p>
        <Link className="inline-flex rounded-md bg-ink px-4 py-2 text-sm font-semibold text-white" href="/teacher">
          Back to dashboard
        </Link>
      </div>
    );
  }

  return (
    <div className="mx-auto max-w-3xl space-y-5">
      <form className="space-y-4 rounded-xl border border-slate-200 bg-white p-6 shadow-sm" onSubmit={submit}>
        <h1 className="text-2xl font-bold text-slate-900">Edit Course</h1>

        <label className="block">
          <span className="mb-1 block text-sm text-slate-700">Title</span>
          <input
            className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-brand"
            onChange={(event) => setTitle(event.target.value)}
            value={title}
          />
        </label>

        <label className="block">
          <span className="mb-1 block text-sm text-slate-700">Level</span>
          <select
            className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-brand"
            onChange={(event) => setLevel(event.target.value as CourseLevel)}
            value={level}
          >
            {levels.map((item) => (
              <option key={item} value={item}>
                {item}
              </option>
            ))}
          </select>
        </label>

        <label className="block">
          <span className="mb-1 block text-sm text-slate-700">Summary</span>
          <textarea
            className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-brand"
            onChange={(event) => setSummary(event.target.value)}
            rows={3}
            value={summary}
          />
        </label>

        <div className="grid gap-4 sm:grid-cols-2">
          <label className="block">
            <span className="mb-1 block text-sm text-slate-700">Instructor</span>
            <input
              className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-brand"
              onChange={(event) => setInstructor(event.target.value)}
              value={instructor}
            />
          </label>

          <label className="block">
            <span className="mb-1 block text-sm text-slate-700">Weeks</span>
            <input
              className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-brand"
              min={1}
              onChange={(event) => setWeeks(Number(event.target.value))}
              type="number"
              value={weeks}
            />
          </label>

          <label className="block">
            <span className="mb-1 block text-sm text-slate-700">Rating (0-5)</span>
            <input
              className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-brand"
              max={5}
              min={0}
              onChange={(event) => setRating(Number(event.target.value))}
              step={0.1}
              type="number"
              value={rating}
            />
          </label>
        </div>

        <div className="flex items-center gap-3">
          <button className="rounded-md bg-ink px-4 py-2 text-sm font-semibold text-white hover:brightness-105" type="submit">
            Save changes
          </button>
          {saved ? <span className="text-sm font-medium text-emerald-700">Saved</span> : null}
          <button
            className="rounded-md border border-slate-300 px-4 py-2 text-sm hover:bg-slate-50"
            onClick={() => router.push(`/teacher/courses/${course.slug}/lessons/new`)}
            type="button"
          >
            Add lesson
          </button>
        </div>
      </form>

      <section className="rounded-xl border border-slate-200 bg-white p-6 shadow-sm">
        <h2 className="text-lg font-semibold text-slate-900">Lessons</h2>
        <div className="mt-3 space-y-2">
          {course.lessons.map((lesson) => (
            <div key={lesson.id} className="rounded-md border border-slate-200 p-3 text-sm">
              <p className="font-medium text-slate-900">{lesson.title}</p>
              <p className="text-slate-600">
                {lesson.type} | {lesson.minutes} min {lesson.isPreview ? "| Preview" : ""}
              </p>
            </div>
          ))}
        </div>
      </section>
    </div>
  );
}
