"use client";

import { useActionState } from "react";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import { acceptInviteAction, type InviteState } from "./actions";

const initialInviteState: InviteState = { attempt: 0 };

// =====================================================================
// InviteForm · Client Component
// ---------------------------------------------------------------------
// Empfängt den Token als Prop (aus der Server Component) und übergibt
// ihn als Hidden-Input an die Server Action — der Client "kennt" den
// Token nur zum Weiterleiten, validiert ihn nicht selbst.
// =====================================================================

export function InviteForm({
  token,
  userName,
}: {
  token: string;
  userName: string;
}) {
  const [state, formAction, pending] = useActionState(
    acceptInviteAction,
    initialInviteState,
  );

  // Bumping the key on each attempt forces uncontrolled inputs (including
  // checkboxes) to remount with the echoed defaultChecked values after a
  // failed submit. Passwords stay empty for security.
  const attemptKey = state.attempt;

  return (
    <form action={formAction} className="space-y-5">
      {/* Token als verstecktes Feld */}
      <input type="hidden" name="token" value={token} />

      <div className="space-y-1.5">
        <p className="text-sm text-muted-foreground">
          Du wurdest eingeladen als: <strong>{userName}</strong>
        </p>
      </div>

      {/* Passwort */}
      <div className="space-y-1.5">
        <Label htmlFor="password">Passwort wählen</Label>
        <Input
          key={`password-${attemptKey}`}
          id="password"
          name="password"
          type="password"
          autoComplete="new-password"
          required
          aria-invalid={!!state.errors?.password}
          aria-describedby={
            state.errors?.password ? "password-error" : "password-helper"
          }
        />
        {state.errors?.password?.[0] ? (
          <p
            id="password-error"
            role="alert"
            aria-live="polite"
            className="text-xs text-destructive"
          >
            {state.errors.password[0]}
          </p>
        ) : (
          <p id="password-helper" className="text-xs text-muted-foreground">
            Mindestens 8 Zeichen.
          </p>
        )}
      </div>

      {/* Passwort bestätigen */}
      <div className="space-y-1.5">
        <Label htmlFor="confirmPassword">Passwort bestätigen</Label>
        <Input
          key={`confirmPassword-${attemptKey}`}
          id="confirmPassword"
          name="confirmPassword"
          type="password"
          autoComplete="new-password"
          required
          aria-invalid={!!state.errors?.confirmPassword}
          aria-describedby={
            state.errors?.confirmPassword
              ? "confirmPassword-error"
              : undefined
          }
        />
        {state.errors?.confirmPassword?.[0] && (
          <p
            id="confirmPassword-error"
            role="alert"
            aria-live="polite"
            className="text-xs text-destructive"
          >
            {state.errors.confirmPassword[0]}
          </p>
        )}
      </div>

      {/* DSGVO-Pflicht */}
      <div className="rounded-md border p-4 space-y-4">
        <p className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
          Einwilligungen (Pflicht)
        </p>

        <div className="flex items-start gap-3">
          <Checkbox
            key={`acceptPrivacyPolicy-${attemptKey}`}
            id="acceptPrivacyPolicy"
            name="acceptPrivacyPolicy"
            required
            defaultChecked={state.values?.acceptPrivacyPolicy === true}
            aria-invalid={!!state.errors?.acceptPrivacyPolicy}
            aria-describedby={
              state.errors?.acceptPrivacyPolicy
                ? "acceptPrivacyPolicy-error"
                : undefined
            }
          />
          <div className="space-y-0.5">
            <Label htmlFor="acceptPrivacyPolicy" className="text-sm font-normal">
              Ich habe die{" "}
              <a
                href="/datenschutz"
                className="underline"
                target="_blank"
                rel="noreferrer"
              >
                Datenschutzerklärung
              </a>{" "}
              gelesen und akzeptiere sie. <span className="text-destructive">*</span>
            </Label>
            {state.errors?.acceptPrivacyPolicy?.[0] && (
              <p
                id="acceptPrivacyPolicy-error"
                role="alert"
                aria-live="polite"
                className="text-xs text-destructive"
              >
                {state.errors.acceptPrivacyPolicy[0]}
              </p>
            )}
          </div>
        </div>

        <div className="flex items-start gap-3">
          <Checkbox
            key={`directoryOptIn-${attemptKey}`}
            id="directoryOptIn"
            name="directoryOptIn"
            defaultChecked={state.values?.directoryOptIn === true}
            aria-invalid={!!state.errors?.directoryOptIn}
          />
          <div className="space-y-0.5">
            <Label htmlFor="directoryOptIn" className="text-sm font-normal">
              Ich stimme zu, dass meine Kontaktdaten im internen Kita-Adressbuch
              für andere Eltern sichtbar sind (Opt-In, jederzeit widerrufbar).
            </Label>
          </div>
        </div>
      </div>

      {/* Globaler Fehler */}
      {state.errors?._form?.[0] && (
        <p
          role="alert"
          aria-live="polite"
          className="rounded-md border border-destructive/50 bg-destructive/10 p-3 text-sm text-destructive"
        >
          {state.errors._form[0]}
        </p>
      )}

      <Button type="submit" className="w-full" disabled={pending} size="lg">
        {pending ? "Wird eingerichtet…" : "Konto aktivieren & anmelden"}
      </Button>
    </form>
  );
}
