"use client";

import { useSearchParams } from "next/navigation";
import Link from "next/link";
import { useId, useMemo, useState } from "react";
import { Eye, EyeOff } from "lucide-react";

import { Alert, Field, Input } from "@/components/ui/form";
import { Button } from "@/components/ui/button";
import { useAuthSubmit, type AuthMode } from "@/components/auth/use-auth-submit";

/**
 * Sign-in / sign-up form for the `/login` and `/register` routes.
 *
 * One component drives both routes so the field set, the error surface and the
 * submit handling can never drift apart. The request handling lives in
 * `useAuthSubmit`, shared with the header auth modal.
 *
 * There is deliberately no password strength meter or hint. Password complexity
 * rules were removed, so any non-empty password is valid and the server will
 * say so; a "Weak" label above a submit button that accepts the password would
 * only be misleading. The one real rule — not empty — is enforced by
 * `passwordSchema` on the server and surfaces here as a normal field error.
 */

export function AuthForm({ mode }: { mode: AuthMode }) {
  const params = useSearchParams();

  const uid = useId();
  const ids = useMemo(
    () => ({
      identifier: `${uid}-identifier`,
      password: `${uid}-password`,
      show: `${uid}-show`,
      username: `${uid}-username`,
      email: `${uid}-email`,
      confirm: `${uid}-confirm`,
      displayName: `${uid}-display`,
      terms: `${uid}-terms`,
    }),
    [uid],
  );

  const [showPassword, setShowPassword] = useState(false);

  const nextPath = params.get("next");
  const safeNext = nextPath && nextPath.startsWith("/") && !nextPath.startsWith("//") ? nextPath : "/";

  const { pending, formError, fieldErrors, onSubmit } = useAuthSubmit({ mode, nextPath: safeNext });

  return (
    <form onSubmit={onSubmit} noValidate className="space-y-5">
      {formError ? <Alert tone="error">{formError}</Alert> : null}

      {mode === "login" ? (
        <Field label="Email or username" htmlFor={ids.identifier} error={fieldErrors.email}>
          <Input
            id={ids.identifier}
            name="identifier"
            type="text"
            autoComplete="username"
            placeholder="you@example.com"
            required
            autoFocus
            invalid={Boolean(fieldErrors.email)}
          />
        </Field>
      ) : (
        <>
          <Field label="Username" htmlFor={ids.username} error={fieldErrors.username}>
            <Input
              id={ids.username}
              name="username"
              type="text"
              autoComplete="username"
              placeholder="cinephile"
              minLength={3}
              maxLength={32}
              required
              autoFocus
              invalid={Boolean(fieldErrors.username)}
            />
          </Field>

          <Field label="Email" htmlFor={ids.email} error={fieldErrors.email}>
            <Input
              id={ids.email}
              name="email"
              type="email"
              autoComplete="email"
              placeholder="you@example.com"
              required
              invalid={Boolean(fieldErrors.email)}
            />
          </Field>

          <Field
            label="Display name"
            htmlFor={ids.displayName}
            hint="Optional. Shown next to your profile."
            error={fieldErrors.displayName}
          >
            <Input
              id={ids.displayName}
              name="displayName"
              type="text"
              autoComplete="nickname"
              placeholder="How should we greet you?"
              maxLength={80}
            />
          </Field>
        </>
      )}

      <Field label="Password" htmlFor={ids.password} error={fieldErrors.password}>
        <div className="relative">
          <Input
            id={ids.password}
            name="password"
            type={showPassword ? "text" : "password"}
            autoComplete={mode === "login" ? "current-password" : "new-password"}
            placeholder="••••••••"
            required
            className="pr-12"
            invalid={Boolean(fieldErrors.password)}
          />
          <button
            type="button"
            id={ids.show}
            onClick={() => setShowPassword((v) => !v)}
            aria-label={showPassword ? "Hide password" : "Show password"}
            aria-pressed={showPassword}
            className="absolute inset-y-0 right-0 grid w-12 place-items-center text-ink-muted transition-colors hover:text-ink"
          >
            {showPassword ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
          </button>
        </div>
      </Field>

      {mode === "register" ? (
        <>
          <Field label="Confirm password" htmlFor={ids.confirm} error={fieldErrors.confirmPassword}>
            <Input
              id={ids.confirm}
              name="confirmPassword"
              type={showPassword ? "text" : "password"}
              autoComplete="new-password"
              placeholder="Repeat your password"
              required
              invalid={Boolean(fieldErrors.confirmPassword)}
            />
          </Field>

          <label className="flex cursor-pointer items-start gap-2.5 text-[13px] text-ink-muted">
            <input
              id={ids.terms}
              name="acceptTerms"
              type="checkbox"
              required
              className="mt-0.5 size-4 shrink-0 cursor-pointer rounded-sm accent-brand-500"
            />
            <span>
              I agree to the{" "}
              <Link href="/terms" className="font-semibold text-ink underline-offset-4 hover:underline">
                Terms of Use
              </Link>{" "}
              and{" "}
              <Link href="/privacy" className="font-semibold text-ink underline-offset-4 hover:underline">
                Privacy Policy
              </Link>
              .
            </span>
          </label>
        </>
      ) : null}

      <Button
        type="submit"
        variant="primary"
        size="lg"
        loading={pending}
        className="w-full"
      >
        {mode === "login" ? "Sign in" : "Create account"}
      </Button>
    </form>
  );
}

