"use client";

import * as React from "react";
import Link from "next/link";
import { useActionState } from "react";
import { Gift } from "lucide-react";
import { Checkbox } from "@/components/ui/checkbox";
import { signUpAction } from "@/lib/actions/auth";
import { authTexts } from "@/lib/i18n/auth";
import type { AuthActionState } from "@/lib/validation/auth";
import { FormAlert } from "../_components/form-alert";
import { SubmitButton } from "../_components/submit-button";
import { TextField } from "../_components/text-field";

const EMPTY = {
  firstName: "",
  lastName: "",
  username: "",
  email: "",
  phone: "",
  password: "",
  confirmPassword: "",
};

export function SignUpForm({
  requireTerms,
  hasReferral,
}: {
  requireTerms: boolean;
  hasReferral: boolean;
}) {
  const [state, formAction, pending] = useActionState<AuthActionState, FormData>(
    signUpAction,
    null,
  );

  const [values, setValues] = React.useState(EMPTY);
  const [accepted, setAccepted] = React.useState(false);

  const failure = state && state.ok === false ? state : null;
  const fieldErrors = failure?.fieldErrors ?? {};

  const set = (key: keyof typeof EMPTY) => (next: string) =>
    setValues((current) => ({ ...current, [key]: next }));

  return (
    <form action={formAction} className="space-y-5">
      {hasReferral ? (
        <div className="flex items-start gap-2.5 rounded-lg border border-cyan-200 bg-cyan-50 px-3 py-2.5 text-sm text-cyan-800 dark:border-cyan-500/25 dark:bg-cyan-500/10 dark:text-cyan-300">
          <Gift className="mt-0.5 size-4 shrink-0" />
          <span>{authTexts.referralApplied}</span>
        </div>
      ) : null}

      {failure ? <FormAlert tone="error">{failure.error}</FormAlert> : null}

      <div className="grid gap-5 sm:grid-cols-2">
        <TextField
          id="firstName"
          name="firstName"
          label={authTexts.firstNameLabel}
          autoComplete="given-name"
          value={values.firstName}
          onChange={set("firstName")}
          error={fieldErrors.firstName}
          disabled={pending}
          autoFocus
          required
        />
        <TextField
          id="lastName"
          name="lastName"
          label={authTexts.lastNameLabel}
          autoComplete="family-name"
          value={values.lastName}
          onChange={set("lastName")}
          error={fieldErrors.lastName}
          disabled={pending}
          required
        />
      </div>

      <TextField
        id="username"
        name="username"
        label={authTexts.usernameLabel}
        placeholder={authTexts.usernamePlaceholder}
        autoComplete="username"
        value={values.username}
        onChange={set("username")}
        error={fieldErrors.username}
        disabled={pending}
        required
      />

      <TextField
        id="email"
        name="email"
        type="email"
        label={authTexts.emailLabel}
        placeholder={authTexts.emailPlaceholder}
        autoComplete="email"
        inputMode="email"
        value={values.email}
        onChange={set("email")}
        error={fieldErrors.email}
        disabled={pending}
        required
      />

      <TextField
        id="phone"
        name="phone"
        type="tel"
        label={authTexts.phoneLabel}
        placeholder={authTexts.phonePlaceholder}
        autoComplete="tel"
        inputMode="tel"
        badge={authTexts.phoneOptional}
        value={values.phone}
        onChange={set("phone")}
        error={fieldErrors.phone}
        disabled={pending}
      />

      <div className="grid gap-5 sm:grid-cols-2">
        <TextField
          id="password"
          name="password"
          type="password"
          label={authTexts.passwordLabel}
          placeholder={authTexts.passwordPlaceholder}
          autoComplete="new-password"
          value={values.password}
          onChange={set("password")}
          error={fieldErrors.password}
          hint={authTexts.passwordHint}
          disabled={pending}
          required
        />
        <TextField
          id="confirmPassword"
          name="confirmPassword"
          type="password"
          label={authTexts.confirmPasswordLabel}
          placeholder={authTexts.passwordPlaceholder}
          autoComplete="new-password"
          value={values.confirmPassword}
          onChange={set("confirmPassword")}
          error={fieldErrors.confirmPassword}
          disabled={pending}
          required
        />
      </div>

      {requireTerms ? (
        <div className="space-y-1.5">
          <div className="flex items-start gap-2.5">
            <Checkbox
              id="terms"
              name="terms"
              checked={accepted}
              onCheckedChange={(checked) => setAccepted(checked === true)}
              disabled={pending}
              className="mt-0.5"
            />
            <label htmlFor="terms" className="text-sm leading-relaxed text-muted-foreground">
              {authTexts.termsLabel}{" "}
              <Link
                href="/terms"
                target="_blank"
                className="font-medium text-primary transition-colors hover:text-primary/80"
              >
                {authTexts.termsLink}
              </Link>
              .
            </label>
          </div>
          {fieldErrors.terms ? (
            <p className="text-xs font-medium text-destructive">{fieldErrors.terms}</p>
          ) : null}
        </div>
      ) : null}

      <SubmitButton
        pending={pending}
        label={authTexts.signUpSubmit}
        pendingLabel={authTexts.signUpSubmitting}
      />
    </form>
  );
}

export default SignUpForm;
