"use client";

import { createCourse } from "@/app/(protected)/teacher/actions"; // Server Action
import { useRouter } from "next/navigation";
import { useState, FormEvent } from "react";
import Link from "next/link";

export default function TeacherNewCourseForm() {
  const router = useRouter();
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setIsLoading(true);
    setError(null);

    const formData = new FormData(event.currentTarget);

    try {
      // 1. Call the Server Action
      const result = await createCourse(formData);

      if (result.success && result.data) {
        // 2. Redirect to the Course Editor
        // We will build the [slug]/edit page next
        router.push(`/teacher/courses/${result.data.slug}/edit`);
      } else {
        setError(result.error || "Algo salió mal al crear el curso.");
        setIsLoading(false);
      }
    } catch {
      setError("Error de conexión. Inténtalo de nuevo.");
      setIsLoading(false);
    }
  }

  return (
    <div className="mx-auto max-w-2xl">
      {/* Breadcrumb / Back Link */}
      <div className="mb-6">
        <Link
          href="/teacher"
          className="text-sm text-slate-500 hover:text-slate-900 transition-colors"
        >
          ← Volver al Panel
        </Link>
      </div>

      <div className="rounded-xl border border-slate-200 bg-white p-8 shadow-sm">
        <h1 className="text-2xl font-bold text-slate-900 mb-2">Crear Nuevo Curso</h1>
        <p className="text-slate-600 mb-8">
          Empieza con un título. Podrás agregar lecciones, cuestionarios y más detalles en la siguiente pantalla.
        </p>

        <form onSubmit={handleSubmit} className="space-y-6">
          <div>
            <label
              htmlFor="title"
              className="block text-sm font-medium text-slate-700 mb-1"
            >
              Título del Curso
            </label>
            <input
              id="title"
              name="title"
              type="text"
              required
              disabled={isLoading}
              placeholder="Ej. Inglés Jurídico: Contratos Internacionales"
              className="w-full rounded-lg border border-slate-300 px-4 py-2 outline-none focus:border-black focus:ring-1 focus:ring-black transition-all disabled:opacity-50 disabled:bg-slate-50"
              autoFocus
            />
            <p className="mt-2 text-xs text-slate-500">
              Esto generará la URL pública de tu curso.
            </p>
          </div>

          {error && (
            <div className="bg-red-50 text-red-600 text-sm p-3 rounded-md border border-red-100">
              {error}
            </div>
          )}

          <div className="flex items-center gap-4 pt-4">
            <Link
              href="/teacher"
              className="px-4 py-2 text-sm font-medium text-slate-600 hover:text-slate-900 transition-colors"
            >
              Cancelar
            </Link>
            <button
              type="submit"
              disabled={isLoading}
              className="rounded-lg bg-black px-6 py-2 text-sm font-medium text-white hover:bg-slate-800 transition-colors disabled:opacity-50 flex items-center gap-2"
            >
              {isLoading ? (
                <>Creating...</>
              ) : (
                "Crear Curso & Continuar"
              )}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}