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 } from "react-router-dom";
import { useSignUp } from "../hooks/auth";
import { DEFAULT_SIGNUP_BILLING_INTENT, type SignupBillingIntent } from "../lib/billing";

export function SignUpV2Page() {
  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
  );

  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 nextErrors: Record<string, string> = {};

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

    if (formData.password !== formData.confirmPassword) {
      nextErrors.confirmPassword = t("auth:signup.errors.passwordMatch");
    }

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

    if (!termsAccepted) {
      nextErrors.terms = t("auth:signup.errors.termsRequired");
    }

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

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

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

    setErrors({});
    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="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,640px)_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-lg mx-auto">
            <div className="mb-6 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-5">
              <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:signup.title")}</h1>
            <p className="text-sm text-muted-foreground mb-7">
              {t("auth:signup.alreadyAccount")}{" "}
              <Link to="/login-v2" className="text-[#804EEC] hover:text-[#6f3fd4] font-semibold">
                {t("auth:signup.loginLink")}
              </Link>
            </p>

            <form className="space-y-4" onSubmit={onSubmit}>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="first_name">
                    {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")}
                    className="h-11"
                  />
                  {errors?.first_name && <FieldError errors={[{ message: errors.first_name }]} />}
                </div>

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

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

              <div className="space-y-2">
                <Label htmlFor="confirmPassword">
                  {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")}
                  className="h-11"
                />
                {errors?.confirmPassword && (
                  <FieldError errors={[{ message: errors.confirmPassword }]} />
                )}
              </div>

              <div className="space-y-2">
                <Label>Plan</Label>
                <div className="grid gap-2">
                  <button
                    type="button"
                    onClick={() => setBillingIntent("solo")}
                    className={`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={`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={`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-1 h-4 w-4 rounded border border-border bg-background"
                    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 h-11 bg-[#804EEC] hover:bg-[#6f3fd4] text-white"
                type="submit"
              >
                {isPending ? t("auth:common.creatingAccount") : t("auth:signup.signupButton")}
              </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>
        </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:signup.asideTitle")}</h2>
            <p className="text-center text-muted-foreground mb-8">
              {t("auth:signup.asideDescription")}
            </p>

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