"use client";

import { useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import Link from "next/link";
import { Reveal } from "../../../components/Reveal";
import { mergeServerCartIntoLocal } from "../../../lib/cart";
import { dispatchAuthChanged } from "../../../lib/auth";

// Standalone registration, independent of checkout — until the Wishlist
// shipped, the only way to get a customer account was the inline
// registration step inside checkout (see api/checkout/route.ts), which
// made sense when an account only ever existed to hold an order. That
// stopped being true the moment a shopper could want an account just to
// save products to a Wishlist without buying anything yet.
export function RegisterForm() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const redirectTo = searchParams.get("redirect") || "/konto/bestellungen";
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setLoading(true);
    setError(null);
    try {
      const res = await fetch("/api/account/register", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ firstName, lastName, email, password }),
      });
      const data = await res.json();
      if (!data.ok) {
        setError(data.reason || "Registrierung fehlgeschlagen.");
        setLoading(false);
        return;
      }
      await mergeServerCartIntoLocal();
      dispatchAuthChanged();
      router.push(redirectTo);
      router.refresh();
    } catch {
      setError("Registrierung ist gerade nicht möglich.");
      setLoading(false);
    }
  }

  return (
    <Reveal className="flex flex-col gap-6 items-start pt-10 pb-20 px-[var(--layout-padding-x)] w-full max-w-[26rem] mx-auto">
      <p className="font-semibold text-h-feature text-text-primary" style={{ fontFamily: "var(--font-lora)" }}>
        Konto anlegen
      </p>
      <form onSubmit={handleSubmit} className="flex flex-col gap-4 items-start w-full">
        <div className="flex gap-4 w-full">
          <label className="flex flex-col gap-2 items-start w-full">
            <span className="text-label text-text-muted">Vorname</span>
            <input
              type="text"
              required
              autoComplete="given-name"
              value={firstName}
              onChange={(e) => setFirstName(e.target.value)}
              className="w-full border border-border rounded-sm px-4 py-3 text-body-sm text-text-primary outline-none focus:border-brand transition-colors"
            />
          </label>
          <label className="flex flex-col gap-2 items-start w-full">
            <span className="text-label text-text-muted">Nachname</span>
            <input
              type="text"
              required
              autoComplete="family-name"
              value={lastName}
              onChange={(e) => setLastName(e.target.value)}
              className="w-full border border-border rounded-sm px-4 py-3 text-body-sm text-text-primary outline-none focus:border-brand transition-colors"
            />
          </label>
        </div>
        <label className="flex flex-col gap-2 items-start w-full">
          <span className="text-label text-text-muted">E-Mail-Adresse</span>
          <input
            type="email"
            required
            autoComplete="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            className="w-full border border-border rounded-sm px-4 py-3 text-body-sm text-text-primary outline-none focus:border-brand transition-colors"
          />
        </label>
        <label className="flex flex-col gap-2 items-start w-full">
          <span className="text-label text-text-muted">Passwort</span>
          <input
            type="password"
            required
            minLength={8}
            autoComplete="new-password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            className="w-full border border-border rounded-sm px-4 py-3 text-body-sm text-text-primary outline-none focus:border-brand transition-colors"
          />
        </label>
        {error && <p className="text-label text-red-600">{error}</p>}
        <button
          type="submit"
          disabled={loading}
          className={`w-full flex items-center justify-center py-4 rounded-sm bg-brand hover:bg-brand-hover active:scale-[0.97] transition-all font-bold text-body text-text-primary ${loading ? "opacity-70 pointer-events-none" : ""}`}
        >
          {loading ? "Einen Moment…" : "Konto anlegen"}
        </button>
      </form>
      <p className="text-body-sm text-text-muted">
        Schon ein Konto?{" "}
        <Link
          href={`/konto/login${redirectTo !== "/konto/bestellungen" ? `?redirect=${encodeURIComponent(redirectTo)}` : ""}`}
          className="underline hover:text-brand transition-colors"
        >
          Einloggen
        </Link>
        .
      </p>
    </Reveal>
  );
}
