"use client";

import * as React from "react";
import Link from "next/link";
import { useActionState } from "react";
import { MailCheck } from "lucide-react";
import { requestPasswordResetAction } 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";

export function ForgotPasswordForm() {
  const [state, formAction, pending] = useActionState<AuthActionState, FormData>(
    requestPasswordResetAction,
    null,
  );
  const [identifier, setIdentifier] = React.useState("");

  const failure = state && state.ok === false ? state : null;
  const sent = Boolean(state && state.ok === true);

  if (sent) {
    return (
      <div className="space-y-5">
        <div className="flex size-11 items-center justify-center rounded-xl bg-emerald-100 text-emerald-600 dark:bg-emerald-500/15 dark:text-emerald-400">
          <MailCheck className="size-5" />
        </div>
        <p className="text-sm leading-relaxed text-foreground">{authTexts.forgotSent}</p>
        <FormAlert tone="info">{authTexts.forgotConsoleNote}</FormAlert>
        <Link
          href="/signin"
          className="inline-block text-sm font-medium text-primary transition-colors hover:text-primary/80"
        >
          {authTexts.backToSignIn}
        </Link>
      </div>
    );
  }

  return (
    <form action={formAction} className="space-y-5">
      {failure ? <FormAlert tone="error">{failure.error}</FormAlert> : null}

      <TextField
        id="identifier"
        name="identifier"
        label={authTexts.identifierLabel}
        placeholder={authTexts.identifierPlaceholder}
        autoComplete="username"
        value={identifier}
        onChange={setIdentifier}
        error={failure?.fieldErrors?.identifier}
        disabled={pending}
        autoFocus
        required
      />

      <SubmitButton
        pending={pending}
        label={authTexts.forgotSubmit}
        pendingLabel={authTexts.forgotSubmitting}
      />
    </form>
  );
}

export default ForgotPasswordForm;
