import { LoginWithGoogle } from "@ui/components/BrandButtons/LoginWithGoogle";
import { useTheme } from "@xtablo/shared/contexts/ThemeContext";
import { Button } from "@xtablo/ui/components/button";
import { FieldError } from "@xtablo/ui/components/field";
import { Input } from "@xtablo/ui/components/input";
import { Label } from "@xtablo/ui/components/label";
import { MonitorIcon, MoonIcon, SunIcon } from "lucide-react";
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);
  };

  // Theme
  const { theme, setTheme } = useTheme();

  const toggleTheme = () => {
    if (theme === "light") {
      setTheme("dark");
    } else if (theme === "dark") {
      setTheme("system");
    } else {
      setTheme("light");
    }
  };

  const getThemeIcon = () => {
    switch (theme) {
      case "light":
        return <SunIcon className="w-5 h-5" />;
      case "dark":
        return <MoonIcon className="w-5 h-5" />;
      case "system":
        return <MonitorIcon className="w-5 h-5" />;
      default:
        return <SunIcon className="w-5 h-5" />;
    }
  };

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

  return (
    <div className="min-h-screen flex items-center justify-center bg-linear-to-br from-primary/10 via-background to-secondary/5 animate-gradient-x bg-size-[400%_400%] relative overflow-hidden">
      <AnimatedBackground />
      <div
        ref={cardRef}
        className={twMerge(
          "w-full max-w-lg rounded-2xl relative",
          "transition-transform duration-200 ease-out will-change-transform"
        )}
        style={{ transform }}
        onMouseMove={handleMouseMove}
        onMouseLeave={handleMouseLeave}
        onClick={(e) => e.stopPropagation()}
      >
        {/* Glow effect behind the card */}
        <div className="absolute inset-0 rounded-2xl bg-linear-to-br from-primary/10 via-primary/5 to-secondary/10 blur-xl -z-10"></div>

        <div
          className={twMerge(
            "relative w-full h-full p-8 bg-card/80 backdrop-blur-md rounded-2xl border border-border z-10 transition-shadow duration-200",
            isHovered
              ? "shadow-[0_15px_35px_rgba(0,0,0,0.15)] dark:shadow-[0_15px_35px_rgba(0,0,0,0.3)]"
              : "shadow-xl shadow-black/10 dark:shadow-black/25"
          )}
        >
          <div className="mb-6 flex items-center justify-between">
            <a
              href="https://www.xtablo.com"
              className="inline-flex items-center text-sm text-muted-foreground hover:text-foreground transition-colors"
            >
              <svg className="w-4 h-4 mr-2" 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>

            {/* Theme Toggle */}
            <Button
              variant="ghost"
              size="icon"
              onClick={toggleTheme}
              className="text-muted-foreground hover:text-foreground p-2"
              aria-label={t("auth:common.themeToggle", { theme })}
            >
              {getThemeIcon()}
            </Button>
          </div>

          {/* Xtablo Icon */}
          <div className="flex justify-center mb-6">
            <img
              src="/logo_dark.png"
              alt="Xtablo"
              className="w-16 h-16 object-contain block dark:hidden"
            />
            <img
              src="/logo_white.png"
              alt="Xtablo"
              className="w-16 h-16 object-contain hidden dark:block"
            />
          </div>

          <h1 className="text-3xl font-bold text-foreground mb-8 text-center">
            {t("auth:login.title")}
          </h1>

          <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">
            <form className="space-y-4 w-95 max-w-md mx-auto" onSubmit={onSubmit}>
              <div className="space-y-2">
                <Label htmlFor="email">
                  {t("common:labels.email")} <span className="text-red-500">*</span>
                </Label>
                <Input
                  id="email"
                  name="email"
                  type="email"
                  value={formData.email}
                  onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                  required
                  placeholder={t("auth:login.emailPlaceholder")}
                />
                {errors?.email && <FieldError errors={[{ message: errors.email }]} />}
              </div>

              <div className="space-y-2">
                <Label htmlFor="password">
                  {t("common:labels.password")} <span className="text-red-500">*</span>
                </Label>
                <Input
                  id="password"
                  name="password"
                  type="password"
                  value={formData.password}
                  onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                  required
                  placeholder={t("auth:login.passwordPlaceholder")}
                />
                {errors?.password && <FieldError errors={[{ message: errors.password }]} />}
              </div>

              <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>

              <Button className="w-full" type="submit">
                {isPending ? t("auth:common.connecting") : t("auth:login.loginButton")}
              </Button>
            </form>

            <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>
        </div>
      </div>
    </div>
  );
}
