import { useEffect, useMemo } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Link, Navigate, useLocation, 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 LoginForm = {
  email: string;
  password: string;
};

export function LoginPage() {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const location = useLocation();
  const { login, loginPending, loginError, resetLoginError } = useAuth();
  const accessToken = authStore.useStore((s) => s.accessToken);
  const theme = themeStore.useStore((s) => s.theme);

  const loginSchema = useMemo(
    () =>
      z.object({
        email: z.string().min(1, t("validation.emailRequired")).email(t("validation.emailInvalid")),
        password: z.string().min(1, t("validation.passwordRequired")),
      }),
    [t],
  );

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

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

  const redirectTo = (location.state as { from?: { pathname: string } } | null)?.from?.pathname ?? "/";

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

  const onSubmit = async (data: LoginForm) => {
    try {
      await login(data);
      navigate(redirectTo, { replace: true });
    } catch {
      // Error surfaced via loginError 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("app.name")}</h1>
          <p className="mt-1 text-sm text-slate-500 dark:text-slate-400">{t("auth.signInSubtitle")}</p>
        </div>

        <form onSubmit={handleSubmit(onSubmit)} className="card space-y-5 p-6 sm:p-8" noValidate>
          {loginError && (
            <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>{loginError}</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="password" className="mb-1.5 block text-sm font-medium">
              {t("auth.password")}
            </label>
            <input
              id="password"
              type="password"
              autoComplete="current-password"
              className="input"
              placeholder="••••••••"
              {...register("password")}
            />
            {errors.password && (
              <p className="mt-1.5 text-sm text-red-600">{errors.password.message}</p>
            )}
          </div>

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

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