"use client";

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

const lessonTypes: LessonType[] = ["video", "reading", "interactive"];

type TeacherNewLessonFormProps = {
  slug: string;
};

export default function TeacherNewLessonForm({ slug }: TeacherNewLessonFormProps) {
  const router = useRouter();
  const [course, setCourse] = useState<Course | null>(null);
  const [title, setTitle] = useState("");
  const [type, setType] = useState<LessonType>("video");
  const [minutes, setMinutes] = useState(10);
  const [isPreview, setIsPreview] = useState(false);
  const [videoUrl, setVideoUrl] = useState("");
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const load = () => setCourse(getTeacherCourseBySlug(slug) ?? null);
    load();
    window.addEventListener(teacherCoursesUpdatedEventName, load);
    return () => window.removeEventListener(teacherCoursesUpdatedEventName, load);
  }, [slug]);

  const submit = (event: FormEvent) => {
    event.preventDefault();
    setError(null);

    if (!course) {
      setError("Teacher course not found.");
      return;
    }

    if (!title.trim()) {
      setError("Lesson title is required.");
      return;
    }

    addLessonToTeacherCourse(course.slug, {
      title: title.trim(),
      type,
      minutes: Math.max(1, minutes),
      isPreview,
      videoUrl: type === "video" ? videoUrl.trim() : undefined,
    });

    router.push(`/teacher/courses/${course.slug}/edit`);
  };

  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 lesson creator 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 (
    <form className="mx-auto max-w-2xl 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">Add Lesson</h1>
      <p className="text-sm text-slate-600">Course: {course.title}</p>

      <label className="block">
        <span className="mb-1 block text-sm text-slate-700">Lesson 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>

      <div className="grid gap-4 sm:grid-cols-2">
        <label className="block">
          <span className="mb-1 block text-sm text-slate-700">Type</span>
          <select
            className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-brand"
            onChange={(event) => setType(event.target.value as LessonType)}
            value={type}
          >
            {lessonTypes.map((item) => (
              <option key={item} value={item}>
                {item}
              </option>
            ))}
          </select>
        </label>

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

      <label className="flex items-center gap-2 text-sm text-slate-700">
        <input checked={isPreview} onChange={(event) => setIsPreview(event.target.checked)} type="checkbox" />
        Mark as preview lesson
      </label>

      {type === "video" ? (
        <label className="block">
          <span className="mb-1 block text-sm text-slate-700">Video URL (placeholder)</span>
          <input
            className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-brand"
            onChange={(event) => setVideoUrl(event.target.value)}
            placeholder="https://example.com/video"
            value={videoUrl}
          />
        </label>
      ) : null}

      {error ? <p className="text-sm text-red-600">{error}</p> : null}

      <button className="rounded-md bg-ink px-4 py-2 text-sm font-semibold text-white hover:brightness-105" type="submit">
        Save lesson
      </button>
    </form>
  );
}
