import { LoginWithGoogle } from "@ui/components/BrandButtons/LoginWithGoogle";
import { AuthCardShell, AuthEmailPasswordForm } from "@xtablo/auth-ui";
import { useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Link, useSearchParams } from "react-router-dom";
import { AnimatedBackground } from "src/components/AnimatedBackground";
import { twMerge } from "tailwind-merge";
import { useLoginEmail } from "../hooks/auth";

export function LoginPage() {
  const [searchParams] = useSearchParams();
  const emailParam = searchParams.get("email");
  const { t } = useTranslation(["auth", "common"]);
  const redirectUrl = localStorage.getItem("redirectUrl");
  const {
    mutate: login,
    isPending,
    errors,
  } = useLoginEmail({
    redirectUrl: redirectUrl ?? null,
  });

  const [formData, setFormData] = useState({
    email: emailParam ?? "",
    password: "",
  });

  // 3D Parallax effect
  const cardRef = useRef<HTMLDivElement>(null);
  const [transform, setTransform] = useState("");
  const [isHovered, setIsHovered] = useState(false);

  const handleMouseMove = (e: React.MouseEvent<HTMLDivElement>) => {
    if (!cardRef.current) return;

    const card = cardRef.current;
    const rect = card.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;

    const centerX = rect.width / 2;
    const centerY = rect.height / 2;

    const rotateX = ((y - centerY) / centerY) * -1; // Max 1 degree tilt
    const rotateY = ((x - centerX) / centerX) * 1;

    setTransform(
      `perspective(1000px) rotateX(${rotateX}deg) rotateY(${rotateY}deg) scale3d(1.002, 1.002, 1.002)`
    );
    setIsHovered(true);
  };

  const handleMouseLeave = () => {
    setTransform("");
    setIsHovered(false);
  };

  const onSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    login({
      email: formData.email,
      password: formData.password,
    });
  };

  return (
    <AuthCardShell
      title={t("auth:login.title")}
      background={<AnimatedBackground />}
      topLeft={
        <a
          href="https://www.xtablo.com"
          className="inline-flex items-center text-sm text-muted-foreground hover:text-foreground transition-colors"
        >
          <svg className="mr-2 h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M15 19l-7-7 7-7"
            />
          </svg>
          {t("auth:common.backHome")}
        </a>
      }
      showThemeToggle
      wrapperClassName="transition-transform duration-200 ease-out will-change-transform"
      wrapperStyle={{ transform }}
      onWrapperMouseMove={handleMouseMove}
      onWrapperMouseLeave={handleMouseLeave}
      isHovered={isHovered}
    >
      <div className="mb-6 text-center">
        <Link
          to="/login-v2"
          className="inline-flex items-center text-sm text-[#804EEC] hover:text-[#6f3fd4] font-medium transition-colors"
        >
          {t("auth:login.newExperienceLink")}
        </Link>
      </div>

      <div className="space-y-4 flex flex-col items-center">
        <AuthEmailPasswordForm
          email={formData.email}
          password={formData.password}
          onEmailChange={(email: string) => setFormData({ ...formData, email })}
          onPasswordChange={(password: string) => setFormData({ ...formData, password })}
          onSubmit={onSubmit}
          submitLabel={isPending ? t("auth:common.connecting") : t("auth:login.loginButton")}
          emailLabel={`${t("common:labels.email")} *`}
          passwordLabel={`${t("common:labels.password")} *`}
          emailPlaceholder={t("auth:login.emailPlaceholder")}
          passwordPlaceholder={t("auth:login.passwordPlaceholder")}
          emailError={errors?.email}
          passwordError={errors?.password}
          extraContent={
            <div className="flex items-center justify-end">
              <Link
                to="/reset-password"
                className="text-sm text-purple-600 hover:text-purple-500 dark:text-purple-400 dark:hover:text-purple-300 transition-colors"
              >
                {t("auth:login.forgotPassword")}
              </Link>
            </div>
          }
        />

        <div className="relative my-6">
          <div className="absolute inset-0 flex items-center">
            <div className="w-full border-t border-border"></div>
          </div>
          <div className="relative flex justify-center text-sm">
            <span
              className={twMerge(
                "px-4 py-1 bg-background",
                "text-muted-foreground",
                "text-sm font-medium",
                "rounded-full",
                "relative z-10",
                "before:absolute before:w-[100px] before:h-px before:bg-border before:left-[-110px] before:top-1/2",
                "after:absolute after:w-[100px] after:h-px after:bg-border after:right-[-110px] after:top-1/2"
              )}
            >
              {t("auth:common.orContinue")}
            </span>
          </div>
        </div>

        <LoginWithGoogle />

        <p className="text-center text-sm text-muted-foreground">
          {t("auth:login.noAccount")}{" "}
          <Link
            to="/signup"
            className="text-foreground hover:text-foreground/80 font-medium text-sm px-2 py-1 rounded hover:bg-muted transition-colors"
          >
            {t("auth:login.signupLink")}
          </Link>
        </p>
      </div>
    </AuthCardShell>
  );
}
