"use client";

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

const fieldClass =
  "w-full rounded-2xl border border-anouma-taupe/30 bg-white px-5 py-3.5 text-base text-anouma-plum placeholder:text-anouma-plum/50 focus:border-anouma-mauve-dark focus:outline-none";

export const MEETING_SESSION_KEY = "anouma-meeting-session";

export type StoredMeetingSession = {
  token: string;
  participantId: string;
  role: "host" | "participant";
  name: string;
  eventTitle: string;
  eventSlug: string;
};

export function JoinForm({ slug }: { slug: string }) {
  const router = useRouter();
  const [name, setName] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  async function handleSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setError(null);
    setLoading(true);
    try {
      const res = await fetch(`/api/meetings/${slug}/join`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name, password }),
        credentials: "include",
      });
      const data = await res.json();
      if (!res.ok) {
        setError(data.error || "Beitritt leider nicht möglich.");
        setLoading(false);
        return;
      }

      const session: StoredMeetingSession = {
        token: data.token,
        participantId: data.participantId,
        role: data.role,
        name,
        eventTitle: data.eventTitle,
        eventSlug: slug,
      };
      sessionStorage.setItem(MEETING_SESSION_KEY, JSON.stringify(session));
      router.push(`/termine/${slug}/call`);
    } catch {
      setError("Verbindung fehlgeschlagen. Bitte versuche es erneut.");
      setLoading(false);
    }
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-5">
      <div>
        <label htmlFor="name" className="mb-2 block text-sm font-medium text-anouma-plum">
          Dein Name
        </label>
        <input
          id="name"
          type="text"
          required
          value={name}
          onChange={(e) => setName(e.target.value)}
          placeholder="Name eingeben"
          className={fieldClass}
          autoComplete="name"
        />
      </div>
      <div>
        <label htmlFor="password" className="mb-2 block text-sm font-medium text-anouma-plum">
          Meeting-Passwort
        </label>
        <input
          id="password"
          type="text"
          required
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          placeholder="Passwort eingeben"
          className={fieldClass}
          autoComplete="off"
        />
      </div>
      {error && (
        <p role="alert" className="text-sm text-red-700">
          {error}
        </p>
      )}
      <button
        type="submit"
        disabled={loading}
        className="w-full rounded-full bg-anouma-mauve-dark px-7 py-3.5 text-sm font-medium tracking-wide text-white transition-colors duration-300 hover:bg-anouma-plum disabled:opacity-60"
      >
        {loading ? "Wird geprüft …" : "Meeting betreten"}
      </button>
    </form>
  );
}
