import { AnimatedBackground } from "@ui/components/AnimatedBackground";
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 { ArrowLeftIcon, MonitorIcon, MoonIcon, SparklesIcon, SunIcon } from "lucide-react";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { Link, useSearchParams } from "react-router-dom";
import { useLoginEmail } from "../hooks/auth";

export function LoginV2Page() {
  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: "",
  });

  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="relative min-h-screen overflow-hidden bg-background text-foreground">
      <AnimatedBackground />

      <div className="relative z-10 min-h-screen md:grid md:grid-cols-[minmax(0,560px)_1fr]">
        <main className="flex min-h-screen items-center px-6 py-10 md:px-10 lg:px-14">
          <div className="w-full max-w-md mx-auto">
            <div className="mb-7 flex items-center justify-between">
              <a
                href="https://www.xtablo.com"
                className="inline-flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors"
              >
                <ArrowLeftIcon className="w-4 h-4" />
                {t("auth:common.backHome")}
              </a>

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

            <div className="mb-6">
              <img src="/logo_dark.png" alt="Xtablo" className="h-10 w-auto block dark:hidden" />
              <img src="/logo_white.png" alt="Xtablo" className="h-10 w-auto hidden dark:block" />
            </div>

            <h1 className="text-3xl font-bold tracking-tight mb-2">{t("auth:login.title")}</h1>
            <p className="text-sm text-muted-foreground mb-8">
              {t("auth:login.noAccount")}{" "}
              <Link to="/signup-v2" className="text-[#804EEC] hover:text-[#6f3fd4] font-semibold">
                {t("auth:login.signupLink")}
              </Link>
            </p>

            <form className="space-y-4" 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")}
                  className="h-11"
                />
                {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")}
                  className="h-11"
                />
                {errors?.password && <FieldError errors={[{ message: errors.password }]} />}
              </div>

              <div className="flex items-center justify-end">
                <Link
                  to="/reset-password"
                  className="text-sm text-[#804EEC] hover:text-[#6f3fd4] transition-colors"
                >
                  {t("auth:login.forgotPassword")}
                </Link>
              </div>

              <Button
                className="w-full h-11 bg-[#804EEC] hover:bg-[#6f3fd4] text-white"
                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 className="relative flex justify-center">
                <span className="px-3 bg-background text-xs text-muted-foreground">
                  {t("auth:common.orContinue")}
                </span>
              </div>
            </div>

            <LoginWithGoogle />

            <div className="mt-10 text-xs text-muted-foreground space-y-2">
              <p>
                © {new Date().getFullYear()} Xtablo. {t("auth:common.backHome")}
              </p>
              <p className="flex gap-3">
                <Link
                  to="/legal-notice"
                  target="_blank"
                  className="hover:text-foreground transition-colors"
                >
                  {t("auth:signup.termsLink")}
                </Link>
                <span>|</span>
                <Link
                  to="/privacy-policy"
                  target="_blank"
                  className="hover:text-foreground transition-colors"
                >
                  {t("auth:signup.privacyLink")}
                </Link>
              </p>
            </div>
          </div>
        </main>

        <aside className="hidden md:flex min-h-screen items-center justify-center px-8 lg:px-14 border-l border-border bg-gradient-to-br from-[#F5F0FF] via-[#ECE4FF] to-[#DCCEFF] dark:from-[#201933] dark:via-[#271F3E] dark:to-[#2F2548]">
          <div className="relative w-full max-w-xl rounded-3xl border border-white/50 dark:border-white/10 bg-white/80 dark:bg-[#171224]/85 backdrop-blur-sm shadow-2xl p-10">
            <SparklesIcon className="absolute top-5 left-5 w-5 h-5 text-[#804EEC] opacity-70" />
            <SparklesIcon className="absolute top-5 right-5 w-5 h-5 text-[#804EEC] opacity-70" />
            <SparklesIcon className="absolute bottom-5 left-5 w-5 h-5 text-[#804EEC] opacity-70" />
            <SparklesIcon className="absolute bottom-5 right-5 w-5 h-5 text-[#804EEC] opacity-70" />

            <div className="flex justify-center mb-6">
              <div className="w-20 h-20 rounded-full border border-border bg-card flex items-center justify-center shadow-sm">
                <img
                  src="/logo_dark.png"
                  alt="Xtablo"
                  className="w-12 h-12 object-contain block dark:hidden"
                />
                <img
                  src="/logo_white.png"
                  alt="Xtablo"
                  className="w-12 h-12 object-contain hidden dark:block"
                />
              </div>
            </div>

            <h2 className="text-2xl font-bold text-center mb-3">{t("auth:login.asideTitle")}</h2>
            <p className="text-center text-muted-foreground mb-8">
              {t("auth:login.asideDescription")}
            </p>

            <div className="space-y-3 mb-8">
              <div className="rounded-xl border border-border/70 bg-background/80 px-4 py-3 text-sm">
                {t("auth:login.feature1")}
              </div>
              <div className="rounded-xl border border-border/70 bg-background/80 px-4 py-3 text-sm">
                {t("auth:login.feature2")}
              </div>
              <div className="rounded-xl border border-border/70 bg-background/80 px-4 py-3 text-sm">
                {t("auth:login.feature3")}
              </div>
            </div>

            <Link
              to="/signup-v2"
              className="inline-flex w-full items-center justify-center rounded-xl bg-[#804EEC] px-5 py-3 text-sm font-semibold text-white hover:bg-[#6f3fd4] transition-colors"
            >
              {t("auth:login.signupLink")}
            </Link>
          </div>
        </aside>
      </div>
    </div>
  );
}
