"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";

export function EnrollButton({ courseSlug }: { courseSlug: string }) {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function onClick() {
    setLoading(true);
    setError(null);
    const res = await fetch("/api/enroll", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ courseSlug }),
    });
    const data = (await res.json().catch(() => ({}))) as { error?: string };
    setLoading(false);
    if (!res.ok) {
      setError(data.error ?? "Einschreibung fehlgeschlagen.");
      return;
    }
    router.refresh();
  }

  return (
    <div>
      <button type="button" className="btn btn-primary" disabled={loading} onClick={onClick}>
        {loading ? "…" : "In diesen Kurs einschreiben"}
      </button>
      {error ? <p className="error">{error}</p> : null}
    </div>
  );
}
