"use client";

import { useState } from "react";

export default function EventForm() {
  const [status, setStatus] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  const onSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setStatus(null);
    setError(null);

    const formData = new FormData(event.currentTarget);
    const payload = {
      title: formData.get("title"),
      description: formData.get("description"),
      location: formData.get("location"),
      startAt: formData.get("startAt"),
      endAt: formData.get("endAt")
    };

    try {
      const response = await fetch("/api/events", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload)
      });

      if (!response.ok) {
        const data = await response.json();
        throw new Error(data.error || "Fehler beim Speichern.");
      }

      event.currentTarget.reset();
      setStatus("Termin vorgeschlagen. Ein Admin bestaetigt ihn.");
    } catch (err) {
      setError((err as Error).message);
    }
  };

  return (
    <section className="rounded bg-white p-4 shadow-sm">
      <h2 className="text-lg font-semibold">Termin vorschlagen</h2>
      <form onSubmit={onSubmit} className="mt-4 grid gap-3 md:grid-cols-2">
        <input
          name="title"
          placeholder="Titel"
          required
          className="rounded border border-slate-300 px-3 py-2"
        />
        <input
          name="location"
          placeholder="Ort"
          className="rounded border border-slate-300 px-3 py-2"
        />
        <input
          name="startAt"
          type="datetime-local"
          required
          className="rounded border border-slate-300 px-3 py-2"
        />
        <input
          name="endAt"
          type="datetime-local"
          required
          className="rounded border border-slate-300 px-3 py-2"
        />
        <textarea
          name="description"
          placeholder="Beschreibung"
          className="min-h-[96px] rounded border border-slate-300 px-3 py-2 md:col-span-2"
        />
        <button
          type="submit"
          className="rounded bg-brand-500 px-4 py-2 text-white md:col-span-2"
        >
          Vorschlag senden
        </button>
      </form>
      {status && <p className="mt-3 text-sm text-emerald-600">{status}</p>}
      {error && <p className="mt-3 text-sm text-red-600">{error}</p>}
    </section>
  );
}
