"use client";

import { Button, Card, CardContent, CardDescription, CardHeader, CardTitle } from "@hexahost/ui";
import { zodResolver } from "@hookform/resolvers/zod";
import { useTranslations } from "next-intl";
import { useSearchParams } from "next/navigation";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { Link, useRouter } from "@/i18n/navigation";
import { ApiError, verifyTwoFactorLogin } from "@/lib/api/auth";
import { createTwoFactorSchema, type TwoFactorFormValues } from "@/lib/schemas/auth";
import { useAuth } from "@/components/providers/auth-provider";

const inputClassName =
  "flex h-10 w-full rounded-md border border-zinc-300 bg-white px-3 text-sm text-zinc-900 placeholder:text-zinc-400 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-500 dark:border-zinc-700 dark:bg-zinc-950 dark:text-zinc-100";

export function Login2FaForm() {
  const t = useTranslations("auth");
  const tv = useTranslations("validation");
  const router = useRouter();
  const searchParams = useSearchParams();
  const { refresh } = useAuth();
  const [apiError, setApiError] = useState<string | null>(null);

  const challengeId = searchParams.get("challenge");

  const schema = createTwoFactorSchema({
    codeRequired: tv("codeRequired"),
    codeInvalid: tv("codeInvalid"),
  });

  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting },
  } = useForm<TwoFactorFormValues>({
    resolver: zodResolver(schema),
    defaultValues: { code: "" },
  });

  if (!challengeId) {
    return (
      <Card className="w-full max-w-md">
        <CardHeader>
          <CardTitle>{t("twoFactorTitle")}</CardTitle>
          <CardDescription>{t("twoFactorMissingChallenge")}</CardDescription>
        </CardHeader>
        <CardContent>
          <Link href="/login" className="text-sm font-medium text-sky-600 hover:underline dark:text-sky-400">
            {t("backToLogin")}
          </Link>
        </CardContent>
      </Card>
    );
  }

  async function onSubmit(values: TwoFactorFormValues) {
    setApiError(null);

    try {
      await verifyTwoFactorLogin(challengeId!, values.code);
      await refresh();
      router.push("/dashboard");
    } catch (error) {
      if (error instanceof ApiError) {
        setApiError(error.detail ?? error.title);
      } else {
        setApiError(t("errors.generic"));
      }
    }
  }

  return (
    <Card className="w-full max-w-md">
      <CardHeader>
        <CardTitle>{t("twoFactorTitle")}</CardTitle>
        <CardDescription>{t("twoFactorSubtitle")}</CardDescription>
      </CardHeader>
      <CardContent>
        <form onSubmit={handleSubmit(onSubmit)} className="space-y-4" noValidate>
          <div className="space-y-2">
            <label htmlFor="code" className="text-sm font-medium text-zinc-900 dark:text-zinc-100">
              {t("twoFactorCode")}
            </label>
            <input
              id="code"
              type="text"
              inputMode="numeric"
              autoComplete="one-time-code"
              placeholder="000000"
              maxLength={6}
              aria-invalid={errors.code ? "true" : "false"}
              aria-describedby={errors.code ? "code-error" : undefined}
              className={inputClassName}
              {...register("code")}
            />
            {errors.code ? (
              <p id="code-error" className="text-sm text-red-600" role="alert">
                {errors.code.message}
              </p>
            ) : null}
          </div>

          {apiError ? (
            <p className="rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-900 dark:border-red-900 dark:bg-red-950 dark:text-red-100" role="alert">
              {apiError}
            </p>
          ) : null}

          <Button type="submit" className="w-full" isLoading={isSubmitting}>
            {t("twoFactorSubmit")}
          </Button>
        </form>

        <p className="mt-4 text-center text-sm text-zinc-600 dark:text-zinc-400">
          <Link href="/login" className="font-medium text-sky-600 hover:underline dark:text-sky-400">
            {t("backToLogin")}
          </Link>
        </p>
      </CardContent>
    </Card>
  );
}
