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 { MonitorIcon, MoonIcon, SunIcon } from "lucide-react";
import { useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router-dom";
import { twMerge } from "tailwind-merge";
import { useSignUp } from "../hooks/auth";
import { DEFAULT_SIGNUP_BILLING_INTENT, type SignupBillingIntent } from "../lib/billing";

export function SignUpPage() {
  const { t } = useTranslation(["auth", "common"]);
  const redirectUrl = localStorage.getItem("redirectUrl");
  const { mutate: signUp, isPending } = useSignUp({
    redirectUrl: redirectUrl ?? null,
  });
  const [errors, setErrors] = useState<Record<string, string>>({});

  const [formData, setFormData] = useState({
    email: "",
    password: "",
    confirmPassword: "",
    username: "",
    first_name: "",
    last_name: "",
    business_name: "",
  });
  const [termsAccepted, setTermsAccepted] = useState(false);
  const [billingIntent, setBillingIntent] = useState<SignupBillingIntent>(
    DEFAULT_SIGNUP_BILLING_INTENT
  );

  // 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 validateForm = () => {
    const errors: Record<string, string> = {};

    // // Business name validation
    // if (formData.business_name.length < 3) {
    //   errors.business_name =
    //     "Le nom de l'entreprise doit contenir au moins 3 caractères";
    // }

    // Password length validation
    if (formData.password.length < 8) {
      errors.password = t("auth:signup.errors.passwordLength");
    }

    // Password match validation
    if (formData.password !== formData.confirmPassword) {
      errors.confirmPassword = t("auth:signup.errors.passwordMatch");
    }

    // Email validation
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(formData.email)) {
      errors.email = t("auth:signup.errors.invalidEmail");
    }

    // Terms acceptance validation
    if (!termsAccepted) {
      errors.terms = t("auth:signup.errors.termsRequired");
    }

    return Object.keys(errors).length === 0 ? null : errors;
  };

  const onSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    const validationErrors = validateForm();
    if (validationErrors) {
      setErrors(validationErrors);
      return;
    }

    signUp({
      email: formData.email,
      password: formData.password,
      first_name: formData.first_name,
      last_name: formData.last_name,
      confirm_password: formData.confirmPassword,
      business_name: formData.business_name,
      billing_intent: billingIntent,
    });
  };

  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-xl rounded-2xl relative",
          "transition-transform duration-200 ease-out will-change-transform"
        )}
        style={{ transform }}
        onMouseMove={handleMouseMove}
        onMouseLeave={handleMouseLeave}
      >
        {/* 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-6 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-4 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-4">
            <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>

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

          <div className="space-y-3 flex flex-col items-center">
            <form className="space-y-3 w-full" onSubmit={onSubmit}>
              <div className="grid grid-cols-2 gap-3">
                <div className="space-y-2">
                  <Label htmlFor="first_name" className="text-sm">
                    {t("auth:signup.firstName")} <span className="text-red-500">*</span>
                  </Label>
                  <Input
                    id="first_name"
                    name="first_name"
                    type="text"
                    value={formData.first_name}
                    onChange={(e) => setFormData({ ...formData, first_name: e.target.value })}
                    required
                    placeholder={t("auth:signup.firstNamePlaceholder")}
                  />
                  {errors?.first_name && <FieldError errors={[{ message: errors.first_name }]} />}
                </div>
                <div className="space-y-2">
                  <Label htmlFor="last_name" className="text-sm">
                    {t("auth:signup.lastName")} <span className="text-red-500">*</span>
                  </Label>
                  <Input
                    id="last_name"
                    name="last_name"
                    type="text"
                    value={formData.last_name}
                    onChange={(e) => setFormData({ ...formData, last_name: e.target.value })}
                    required
                    placeholder={t("auth:signup.lastNamePlaceholder")}
                  />
                  {errors?.last_name && <FieldError errors={[{ message: errors.last_name }]} />}
                </div>
              </div>

              {/* <div className="space-y-2">
                <Label htmlFor="business_name">
                  Nom de l&apos;entreprise{" "}
                  <span className="text-red-500">*</span>
                </Label>
                <Input
                  id="business_name"
                  name="business_name"
                  type="text"
                  value={formData.business_name}
                  onChange={(e) =>
                    setFormData({ ...formData, business_name: e.target.value })
                  }
                  required
                />
                {errors?.business_name && (
                  <FieldError errors={[{ message: errors.business_name }]} />
                )}
              </div> */}

              <div className="space-y-2">
                <Label htmlFor="email" className="text-sm">
                  {t("auth:signup.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:signup.emailPlaceholder")}
                />
                {errors?.email && <FieldError errors={[{ message: errors.email }]} />}
              </div>

              <div className="space-y-2">
                <Label htmlFor="password" className="text-sm">
                  {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:signup.passwordPlaceholder")}
                />
                {errors?.password && <FieldError errors={[{ message: errors.password }]} />}
              </div>

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

              <div className="space-y-2">
                <Label className="text-sm">Plan</Label>
                <div className="grid gap-2">
                  <button
                    type="button"
                    onClick={() => setBillingIntent("solo")}
                    className={twMerge(
                      "w-full rounded-md border p-3 text-left transition-colors",
                      billingIntent === "solo"
                        ? "border-primary bg-primary/10"
                        : "border-border hover:bg-muted/40"
                    )}
                  >
                    <p className="text-sm font-medium">Solo (9.99€/mois)</p>
                    <p className="text-xs text-muted-foreground">
                      Pour les indépendants et petites équipes.
                    </p>
                  </button>
                  <button
                    type="button"
                    onClick={() => setBillingIntent("team")}
                    className={twMerge(
                      "w-full rounded-md border p-3 text-left transition-colors",
                      billingIntent === "team"
                        ? "border-primary bg-primary/10"
                        : "border-border hover:bg-muted/40"
                    )}
                  >
                    <p className="text-sm font-medium">Team (29€/mois)</p>
                    <p className="text-xs text-muted-foreground">
                      Collaboration avancée pour votre organisation.
                    </p>
                  </button>
                  <button
                    type="button"
                    onClick={() => setBillingIntent("founder")}
                    className={twMerge(
                      "w-full rounded-md border p-3 text-left transition-colors",
                      billingIntent === "founder"
                        ? "border-primary bg-primary/10"
                        : "border-border hover:bg-muted/40"
                    )}
                  >
                    <p className="text-sm font-medium">Founder (99€/an)</p>
                    <p className="text-xs text-muted-foreground">
                      Paiement immédiat après la création du compte.
                    </p>
                  </button>
                </div>
              </div>

              <div className="space-y-2">
                <div className="flex items-start gap-2">
                  <Input
                    type="checkbox"
                    id="terms"
                    name="terms"
                    checked={termsAccepted}
                    onChange={(e) => setTermsAccepted(e.target.checked)}
                    className="mt-0.5 h-4 w-4 rounded shrink-0"
                    required
                  />
                  <Label htmlFor="terms" className="text-xs text-muted-foreground leading-relaxed">
                    {t("auth:signup.termsAccept")}{" "}
                    <Link
                      to="/legal-notice"
                      target="_blank"
                      className="text-foreground hover:text-foreground/80 underline"
                    >
                      {t("auth:signup.termsLink")}
                    </Link>{" "}
                    {t("auth:signup.termsAnd")}{" "}
                    <Link
                      to="/privacy-policy"
                      target="_blank"
                      className="text-foreground hover:text-foreground/80 underline"
                    >
                      {t("auth:signup.privacyLink")}
                    </Link>
                  </Label>
                </div>
                {errors?.terms && <FieldError errors={[{ message: errors.terms }]} />}
              </div>

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

            <div className="relative my-4">
              <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-3 py-1 bg-background",
                    "text-muted-foreground",
                    "text-xs 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-xs text-muted-foreground">
              {t("auth:signup.alreadyAccount")}{" "}
              <Link
                to="/login"
                className="text-foreground hover:text-foreground/80 font-medium text-sm px-2 py-1 rounded hover:bg-muted transition-colors"
              >
                {t("auth:signup.loginLink")}
              </Link>
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}
