import { useEffect, useMemo } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Link, Navigate, useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { AlertCircle, Loader2, Moon, Sun, UtensilsCrossed } from "lucide-react";
import { useAuth } from "@/hooks/useAuth";
import { authStore } from "@/store/authStore";
import { themeStore, toggleTheme } from "@/store/themeStore";
import { LanguageSwitcher } from "@/components/ui/LanguageSwitcher";

type RegisterForm = {
  email: string;
  userName?: string;
  password: string;
  confirmPassword: string;
};

export function RegisterPage() {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const { register: registerUser, registerPending, registerError, resetRegisterError } = useAuth();
  const accessToken = authStore.useStore((s) => s.accessToken);
  const theme = themeStore.useStore((s) => s.theme);

  const registerSchema = useMemo(
    () =>
      z
        .object({
          email: z.string().min(1, t("validation.emailRequired")).email(t("validation.emailInvalid")),
          userName: z.string().max(256, t("validation.displayNameTooLong")).optional(),
          password: z
            .string()
            .min(8, t("validation.passwordMinLength"))
            .regex(/[A-Z]/, t("validation.passwordUppercase"))
            .regex(/[a-z]/, t("validation.passwordLowercase"))
            .regex(/[0-9]/, t("validation.passwordDigit")),
          confirmPassword: z.string().min(1, t("validation.confirmPasswordRequired")),
        })
        .refine((data) => data.password === data.confirmPassword, {
          message: t("validation.passwordsMismatch"),
          path: ["confirmPassword"],
        }),
    [t],
  );

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<RegisterForm>({
    resolver: zodResolver(registerSchema),
    defaultValues: { email: "", userName: "", password: "", confirmPassword: "" },
  });

  useEffect(() => () => resetRegisterError(), [resetRegisterError]);

  if (accessToken) {
    return <Navigate to="/" replace />;
  }

  const onSubmit = async (data: RegisterForm) => {
    try {
      await registerUser({
        email: data.email,
        password: data.password,
        userName: data.userName?.trim() || undefined,
      });
      navigate("/", { replace: true });
    } catch {
      // Error surfaced via registerError below.
    }
  };

  return (
    <div className="relative flex min-h-screen items-center justify-center bg-gradient-to-br from-brand-50 to-slate-100 px-4 dark:from-slate-950 dark:to-slate-900">
      <div className="absolute right-4 top-4 flex items-center gap-2">
        <LanguageSwitcher />
        <button
          type="button"
          onClick={toggleTheme}
          className="btn-secondary !px-2.5 !py-2"
          aria-label={t("nav.toggleTheme")}
        >
          {theme === "dark" ? <Sun className="h-5 w-5" /> : <Moon className="h-5 w-5" />}
        </button>
      </div>

      <div className="w-full max-w-md">
        <div className="mb-8 flex flex-col items-center text-center">
          <span className="grid h-14 w-14 place-items-center rounded-2xl bg-brand-600 text-white shadow-lg">
            <UtensilsCrossed className="h-7 w-7" />
          </span>
          <h1 className="mt-4 text-2xl font-extrabold tracking-tight">{t("auth.createAccountTitle")}</h1>
          <p className="mt-1 text-sm text-slate-500 dark:text-slate-400">{t("auth.createAccountSubtitle")}</p>
        </div>

        <form onSubmit={handleSubmit(onSubmit)} className="card space-y-5 p-6 sm:p-8" noValidate>
          {registerError && (
            <div
              role="alert"
              className="flex items-start gap-2 rounded-xl bg-red-50 p-3 text-sm text-red-700 dark:bg-red-950/40 dark:text-red-300"
            >
              <AlertCircle className="mt-0.5 h-4 w-4 shrink-0" />
              <span>{registerError}</span>
            </div>
          )}

          <div>
            <label htmlFor="email" className="mb-1.5 block text-sm font-medium">
              {t("auth.email")}
            </label>
            <input
              id="email"
              type="email"
              autoComplete="email"
              className="input"
              placeholder={t("auth.emailPlaceholder")}
              {...register("email")}
            />
            {errors.email && <p className="mt-1.5 text-sm text-red-600">{errors.email.message}</p>}
          </div>

          <div>
            <label htmlFor="userName" className="mb-1.5 block text-sm font-medium">
              {t("auth.displayName")}{" "}
              <span className="text-slate-400">({t("common.optional")})</span>
            </label>
            <input
              id="userName"
              type="text"
              autoComplete="name"
              className="input"
              placeholder={t("auth.displayNamePlaceholder")}
              {...register("userName")}
            />
            {errors.userName && (
              <p className="mt-1.5 text-sm text-red-600">{errors.userName.message}</p>
            )}
          </div>

          <div>
            <label htmlFor="password" className="mb-1.5 block text-sm font-medium">
              {t("auth.password")}
            </label>
            <input
              id="password"
              type="password"
              autoComplete="new-password"
              className="input"
              placeholder="••••••••"
              {...register("password")}
            />
            {errors.password && (
              <p className="mt-1.5 text-sm text-red-600">{errors.password.message}</p>
            )}
            <p className="mt-1 text-xs text-slate-500 dark:text-slate-400">{t("auth.passwordHint")}</p>
          </div>

          <div>
            <label htmlFor="confirmPassword" className="mb-1.5 block text-sm font-medium">
              {t("auth.confirmPassword")}
            </label>
            <input
              id="confirmPassword"
              type="password"
              autoComplete="new-password"
              className="input"
              placeholder="••••••••"
              {...register("confirmPassword")}
            />
            {errors.confirmPassword && (
              <p className="mt-1.5 text-sm text-red-600">{errors.confirmPassword.message}</p>
            )}
          </div>

          <button type="submit" disabled={registerPending} className="btn-primary w-full">
            {registerPending && <Loader2 className="h-4 w-4 animate-spin" />}
            {registerPending ? t("auth.creatingAccount") : t("auth.createAccount")}
          </button>

          <p className="text-center text-sm text-slate-500 dark:text-slate-400">
            {t("auth.hasAccount")}{" "}
            <Link to="/login" className="font-semibold text-brand-600 hover:text-brand-700">
              {t("auth.signIn")}
            </Link>
          </p>
        </form>
      </div>
    </div>
  );
}
