"use client";

import { useState } from "react";
import { useActionState } from "react";
import { useTranslations } from "next-intl";
import { Link } from "@/i18n/navigation";
import { registerAction } from "@/lib/actions/auth";

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

export function RegisterForm({ locale }: { locale: string }) {
  const t = useTranslations("auth");
  const [state, formAction, pending] = useActionState(registerAction, {});
  const [clientError, setClientError] = useState<string | null>(null);
  const [salutation, setSalutation] = useState("");

  if (state.success) {
    return (
      <p className="text-sm text-[var(--rk-ink-muted)] text-center">{t("checkYourEmail")}</p>
    );
  }

  // Serverseitig wird ohnehin nochmal alles geprüft (siehe registerAction) —
  // diese Vorab-Prüfung sorgt nur dafür, dass fehlende/ungültige Angaben in
  // der gewohnten roten Fehlertext-Optik der Seite erscheinen, statt in der
  // browser-eigenen (uneinheitlich aussehenden) Validierungs-Sprechblase.
  function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    const data = new FormData(e.currentTarget);
    const firstName = String(data.get("firstName") || "").trim();
    const lastName = String(data.get("lastName") || "").trim();
    const salutationValue = String(data.get("salutation") || "").trim();
    const email = String(data.get("email") || "").trim();
    const password = String(data.get("password") || "");
    const birthDateRaw = String(data.get("birthDate") || "");
    const phone = String(data.get("phone") || "").trim();
    const billingStreet = String(data.get("billingStreet") || "").trim();
    const billingPostCode = String(data.get("billingPostCode") || "").trim();
    const billingCity = String(data.get("billingCity") || "").trim();
    const acceptTerms = data.get("acceptTerms") === "on";
    const birthDate = birthDateRaw ? new Date(birthDateRaw) : null;

    let error: string | null = null;
    if (!firstName || !lastName) error = t("validationNameRequired");
    else if (!salutationValue) error = t("validationSalutationRequired");
    else if (!EMAIL_RE.test(email)) error = t("validationEmailInvalid");
    else if (password.length < 8) error = t("validationPasswordShort");
    else if (!birthDate || Number.isNaN(birthDate.getTime()) || birthDate.getTime() > Date.now()) error = t("validationBirthDateInvalid");
    else if (phone.replace(/\D/g, "").length < 5) error = t("validationPhoneInvalid");
    else if (!billingStreet || !billingPostCode || !billingCity) error = t("validationAddressRequired");
    else if (!acceptTerms) error = t("validationAcceptTerms");

    if (error) {
      e.preventDefault();
      setClientError(error);
    } else {
      setClientError(null);
    }
  }

  return (
    <form action={formAction} onSubmit={handleSubmit} noValidate className="flex flex-col gap-4">
      <input type="hidden" name="locale" value={locale} />
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
        <Field label={t("firstNameLabel")} name="firstName" type="text" autoComplete="given-name" required />
        <Field label={t("lastNameLabel")} name="lastName" type="text" autoComplete="family-name" required />
      </div>
      <label className="flex flex-col gap-1.5 text-sm">
        <span className="text-xs uppercase tracking-[0.1em] text-[var(--rk-ink-muted)]">
          {t("salutationLabel")}
          <RequiredMark />
        </span>
        <select
          name="salutation"
          required
          value={salutation}
          onChange={(e) => setSalutation(e.target.value)}
          className="bg-transparent border border-white/15 rounded-lg px-3.5 py-2.5 text-[var(--rk-ink)] focus:outline-none focus:border-white/50 transition-colors"
        >
          <option value="" disabled>
            {t("salutationSelectPlaceholder")}
          </option>
          <option value="herr">{t("salutationHerr")}</option>
          <option value="frau">{t("salutationFrau")}</option>
          <option value="divers">{t("salutationDivers")}</option>
        </select>
      </label>
      {salutation === "divers" && (
        <Field label={t("pronounsLabel")} name="pronouns" type="text" autoComplete="off" />
      )}
      <Field label={t("nicknameLabel")} name="nickname" type="text" autoComplete="nickname" />
      <Field label={t("birthDateLabel")} name="birthDate" type="date" autoComplete="bday" required />
      <Field label={t("phoneLabel")} name="phone" type="tel" autoComplete="tel" required />
      <div className="flex flex-col gap-3">
        <span className="text-xs uppercase tracking-[0.1em] text-[var(--rk-ink-muted)]">{t("addressLabel")}</span>
        <Field label={t("billingStreetLabel")} name="billingStreet" type="text" autoComplete="street-address" required />
        <div className="grid grid-cols-[8rem_1fr] gap-4">
          <Field label={t("billingPostCodeLabel")} name="billingPostCode" type="text" autoComplete="postal-code" required />
          <Field label={t("billingCityLabel")} name="billingCity" type="text" autoComplete="address-level2" required />
        </div>
        <Field
          label={t("billingCountryCodeLabel")}
          name="billingCountryCode"
          type="text"
          autoComplete="country"
          defaultValue="DE"
        />
      </div>
      <Field label={t("emailLabel")} name="email" type="email" autoComplete="email" required />
      <Field label={t("passwordLabel")} name="password" type="password" autoComplete="new-password" required minLength={8} />
      <label className="flex items-start gap-2.5 text-xs text-[var(--rk-ink-muted)]">
        <input
          type="checkbox"
          name="acceptTerms"
          required
          className="mt-0.5 h-4 w-4 shrink-0 rounded border-white/30 bg-transparent accent-white"
        />
        <span>
          {t("acceptTermsPrefix")}{" "}
          <Link href="/agb" target="_blank" rel="noopener noreferrer" className="underline hover:text-[var(--rk-ink)]">
            {t("acceptTermsAgb")}
          </Link>{" "}
          {t("acceptTermsAnd")}{" "}
          <Link href="/datenschutz" target="_blank" rel="noopener noreferrer" className="underline hover:text-[var(--rk-ink)]">
            {t("acceptTermsPrivacy")}
          </Link>{" "}
          {t("acceptTermsSuffix")}
        </span>
      </label>
      {(clientError || state.error) && <p className="text-sm text-red-400">{clientError || state.error}</p>}
      <SubmitButton pending={pending} label={t("registerButton")} />
      <p className="text-xs text-center text-[var(--rk-ink-muted)]">
        {t("hasAccount")}{" "}
        <Link href="/login" className="underline hover:text-[var(--rk-ink)]">
          {t("loginLink")}
        </Link>
      </p>
    </form>
  );
}

export function Field({
  label,
  name,
  type,
  autoComplete,
  required,
  minLength,
  defaultValue,
  min,
  max,
}: {
  label: string;
  name: string;
  type: string;
  autoComplete?: string;
  required?: boolean;
  minLength?: number;
  defaultValue?: string;
  min?: string;
  max?: string;
}) {
  return (
    <label className="flex flex-col gap-1.5 text-sm">
      <span className="text-xs uppercase tracking-[0.1em] text-[var(--rk-ink-muted)]">
        {label}
        {required && (
          <span className="text-[var(--rk-accent)]" title="Pflichtfeld">
            {" "}
            *
          </span>
        )}
      </span>
      <input
        name={name}
        type={type}
        autoComplete={autoComplete}
        required={required}
        minLength={minLength}
        defaultValue={defaultValue}
        min={min}
        max={max}
        className="bg-transparent border border-white/15 rounded-lg px-3.5 py-2.5 text-[var(--rk-ink)] focus:outline-none focus:border-white/50 transition-colors"
      />
    </label>
  );
}

// Für hand-verdrahtete Felder (z. B. <select>), die nicht über die Field-
// Komponente laufen — gleiche Markierung, damit Pflichtfelder überall
// einheitlich aussehen.
export function RequiredMark() {
  return (
    <span className="text-[var(--rk-accent)]" title="Pflichtfeld">
      {" "}
      *
    </span>
  );
}

export function SubmitButton({ pending, label }: { pending: boolean; label: string }) {
  return (
    <button
      type="submit"
      disabled={pending}
      className="mt-2 rounded-lg bg-[var(--rk-accent)] px-6 py-3 text-xs font-semibold uppercase tracking-[0.2em] text-[#141413] transition-opacity hover:opacity-90 disabled:opacity-50"
    >
      {pending ? "…" : label}
    </button>
  );
}
