"use client";

import { Button, Card, CardContent, CardDescription, CardHeader, CardTitle } from "@hexahost/ui";
import { zodResolver } from "@hookform/resolvers/zod";
import { useTranslations } from "next-intl";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { Link, useRouter } from "@/i18n/navigation";
import { ApiError, submitRegister } from "@/lib/api/auth";
import { createRegisterSchema, type RegisterFormValues } from "@/lib/schemas/auth";

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 RegisterForm() {
  const t = useTranslations("auth");
  const tv = useTranslations("validation");
  const router = useRouter();
  const [apiError, setApiError] = useState<string | null>(null);

  const schema = createRegisterSchema({
    emailRequired: tv("emailRequired"),
    emailInvalid: tv("emailInvalid"),
    passwordRequired: tv("passwordRequired"),
    passwordMin: tv("passwordMin"),
    confirmPasswordRequired: tv("confirmPasswordRequired"),
    passwordMismatch: tv("passwordMismatch"),
    usernameInvalid: tv("usernameInvalid"),
  });

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

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

    try {
      await submitRegister({
        email: values.email,
        password: values.password,
        ...(values.username ? { username: values.username } : {}),
        ...(values.displayName ? { displayName: values.displayName } : {}),
      });
      router.push("/verify-email?sent=1");
    } 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("registerTitle")}</CardTitle>
        <CardDescription>{t("registerSubtitle")}</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">
            <label htmlFor="username" className="text-sm font-medium text-zinc-900 dark:text-zinc-100">
              {t("username")}{" "}
              <span className="font-normal text-zinc-500">({t("optional")})</span>
            </label>
            <input
              id="username"
              type="text"
              autoComplete="username"
              placeholder={t("usernamePlaceholder")}
              aria-invalid={errors.username ? "true" : "false"}
              aria-describedby={errors.username ? "username-error" : undefined}
              className={inputClassName}
              {...register("username")}
            />
            {errors.username ? (
              <p id="username-error" className="text-sm text-red-600" role="alert">
                {errors.username.message}
              </p>
            ) : null}
          </div>

          <div className="space-y-2">
            <label htmlFor="displayName" className="text-sm font-medium text-zinc-900 dark:text-zinc-100">
              {t("displayName")}{" "}
              <span className="font-normal text-zinc-500">({t("optional")})</span>
            </label>
            <input
              id="displayName"
              type="text"
              autoComplete="name"
              placeholder={t("displayNamePlaceholder")}
              aria-invalid={errors.displayName ? "true" : "false"}
              className={inputClassName}
              {...register("displayName")}
            />
          </div>

          <div className="space-y-2">
            <label htmlFor="password" className="text-sm font-medium text-zinc-900 dark:text-zinc-100">
              {t("password")}
            </label>
            <input
              id="password"
              type="password"
              autoComplete="new-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>

          <div className="space-y-2">
            <label
              htmlFor="confirmPassword"
              className="text-sm font-medium text-zinc-900 dark:text-zinc-100"
            >
              {t("confirmPassword")}
            </label>
            <input
              id="confirmPassword"
              type="password"
              autoComplete="new-password"
              placeholder={t("passwordPlaceholder")}
              aria-invalid={errors.confirmPassword ? "true" : "false"}
              aria-describedby={errors.confirmPassword ? "confirm-password-error" : undefined}
              className={inputClassName}
              {...register("confirmPassword")}
            />
            {errors.confirmPassword ? (
              <p id="confirm-password-error" className="text-sm text-red-600" role="alert">
                {errors.confirmPassword.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("registerTitle")}
          </Button>
        </form>

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