"use client";

import { Button, Card, CardContent, CardDescription, CardHeader, CardTitle } from "@hexahost/ui";
import { zodResolver } from "@hookform/resolvers/zod";
import { useSearchParams } from "next/navigation";
import { useTranslations } from "next-intl";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { Link, useRouter } from "@/i18n/navigation";
import { ApiError, submitLogin } from "@/lib/api/auth";
import { createLoginSchema, type LoginFormValues } 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 LoginForm() {
  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 schema = createLoginSchema({
    emailRequired: tv("emailRequired"),
    emailInvalid: tv("emailInvalid"),
    passwordRequired: tv("passwordRequired"),
    passwordMin: tv("passwordMin"),
  });

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

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

    try {
      const result = await submitLogin(values);

      if (result.twoFactorRequired && result.challengeId) {
        router.push(`/login/2fa?challenge=${encodeURIComponent(result.challengeId)}`);
        return;
      }

      await refresh();
      const redirectTo = searchParams.get("redirect");
      router.push(redirectTo?.startsWith("/") ? redirectTo : "/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("loginTitle")}</CardTitle>
        <CardDescription>{t("loginSubtitle")}</CardDescription>
      </CardHeader>
      <CardContent>
        <form onSubmit={handleSubmit(onSubmit)} className="space-y-4" noValidate>
          <div className="space-y-2">
            <label htmlFor="email" className="text-sm font-medium text-zinc-900 dark:text-zinc-100">
              {t("email")}
            </label>
            <input
              id="email"
              type="email"
              autoComplete="email"
              placeholder={t("emailPlaceholder")}
              aria-invalid={errors.email ? "true" : "false"}
              aria-describedby={errors.email ? "email-error" : undefined}
              className={inputClassName}
              {...register("email")}
            />
            {errors.email ? (
              <p id="email-error" className="text-sm text-red-600" role="alert">
                {errors.email.message}
              </p>
            ) : null}
          </div>

          <div className="space-y-2">
            <div className="flex items-center justify-between">
              <label htmlFor="password" className="text-sm font-medium text-zinc-900 dark:text-zinc-100">
                {t("password")}
              </label>
              <Link
                href="/forgot-password"
                className="text-xs font-medium text-sky-600 hover:underline dark:text-sky-400"
              >
                {t("forgotPasswordLink")}
              </Link>
            </div>
            <input
              id="password"
              type="password"
              autoComplete="current-password"
              placeholder={t("passwordPlaceholder")}
              aria-invalid={errors.password ? "true" : "false"}
              aria-describedby={errors.password ? "password-error" : undefined}
              className={inputClassName}
              {...register("password")}
            />
            {errors.password ? (
              <p id="password-error" className="text-sm text-red-600" role="alert">
                {errors.password.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("loginTitle")}
          </Button>
        </form>

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