import { useState } from "react";
import { useForm } from "react-hook-form";
import { useAuth } from "@/hooks/useAuth";
import { useNavigate, Link } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { FiAtSign, FiLock } from "react-icons/fi";
import Card from "@/components/ui/Card";
import Input from "@/components/ui/Input";
import Button from "@/components/ui/Button";
import Spinner from "@/components/ui/Spinner";
import FormErrorBanner from "@/components/ui/FormErrorBanner";
import { applyServerErrors } from "@/utils/formErrors";
import { useTurnstile } from "@/hooks/useTurnstile";

interface LoginForm {
  username: string;
  password: string;
}

export default function LoginPage() {
  const { t } = useTranslation("auth");
  const { login } = useAuth();
  const navigate = useNavigate();

  const form = useForm<LoginForm>({
    defaultValues: { username: "", password: "" },
  });
  const { register, handleSubmit, formState, clearErrors } = form;
  const { errors, isSubmitting } = formState;
  const [rootError, setRootError] = useState<string | undefined>();
  const { containerRef, token: turnstileToken, enabled: turnstileEnabled, reset: resetTurnstile } = useTurnstile();

  async function onSubmit(values: LoginForm) {
    if (!turnstileToken) return;
    setRootError(undefined);
    clearErrors();
    try {
      await login({ ...values, turnstile_token: turnstileToken ?? "" });
      navigate("/social/feed");
    } catch (err) {
      setRootError(applyServerErrors(form, err) ?? t("login.errors.generic"));
      resetTurnstile();
    }
  }

  // Client-side validation failed — at least clear any stale root banner
  // so the user isn't shown a server message that no longer applies.
  function onInvalid() {
    setRootError(undefined);
  }

  const disabled = isSubmitting || !turnstileToken;

  return (
    <div className="min-h-screen flex items-center justify-center p-4">
      <Card className="w-full max-w-md" padded={false}>
        <div className="px-8 pt-8 pb-2">
          <h1 className="text-3xl font-bold text-rainbow">{t("login.title")}</h1>
          <p className="mt-1 text-sm text-brand-text/70">{t("login.subtitle")}</p>
        </div>

        <form onSubmit={handleSubmit(onSubmit, onInvalid)} className="space-y-5 p-8" noValidate>
          <FormErrorBanner message={rootError} />

          <Input
            label={t("login.usernameLabel")}
            placeholder={t("login.usernamePlaceholder")}
            icon={<FiAtSign />}
            autoComplete="username"
            error={errors.username?.message}
            disabled={disabled}
            {...register("username", { required: t("login.errors.missing") })}
          />

          <Input
            type="password"
            label={t("login.passwordLabel")}
            placeholder={t("login.passwordPlaceholder")}
            icon={<FiLock />}
            autoComplete="current-password"
            error={errors.password?.message}
            disabled={disabled}
            {...register("password", { required: t("login.errors.missing") })}
          />

          <div className="text-right text-xs">
            <Link
              to="/social/password-reset"
              className="text-brand-lines hover:text-brand-accent"
            >
              {t("login.forgot")}
            </Link>
          </div>

          {turnstileEnabled && <div ref={containerRef} className="flex justify-center" />}

          <Button type="submit" fullWidth loading={isSubmitting} disabled={disabled}>
            {isSubmitting ? (
              <>
                <Spinner size={16} /> {t("login.submitting")}
              </>
            ) : (
              t("login.submit")
            )}
          </Button>

          <p className="text-center text-sm text-brand-text/70">
            {t("login.noAccount")}{" "}
            <Link
              to="/social/register"
              className="font-semibold text-brand-accent hover:underline"
            >
              {t("login.registerCta")}
            </Link>
          </p>
        </form>
      </Card>
    </div>
  );
}
