import { AnimatedBackground } from "@ui/components/AnimatedBackground";
import { LoginWithGoogle } from "@ui/components/BrandButtons/LoginWithGoogle";
import { useTheme } from "@ui/contexts/ThemeContext";
import { useSignUp } from "@ui/hooks/auth";
import { Button } from "@ui/ui-library/button";
import { FieldError, Input, Label, TextField } from "@ui/ui-library/field";
import { Form } from "@ui/ui-library/form";
import { Text } from "@ui/ui-library/text";
import { MonitorIcon, MoonIcon, SunIcon } from "lucide-react";
import { useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { twMerge } from "tailwind-merge";

export function SignUpPage() {
  const navigate = useNavigate();
  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: "",
  });

  // 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 = "Le mot de passe doit contenir au moins 8 caractères";
    }

    // Password match validation
    if (formData.password !== formData.confirmPassword) {
      errors.confirmPassword = "Les mots de passe ne correspondent pas";
    }

    // Email validation
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(formData.email)) {
      errors.email = "Veuillez entrer une adresse email valide";
    }

    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,
    });
  };

  return (
    <div
      className="min-h-screen flex items-center justify-center bg-gradient-to-br from-purple-100 via-purple-50 to-white dark:bg-gradient-to-br dark:from-gray-900 dark:via-slate-900 dark:via-gray-800 dark:to-slate-800 animate-gradient-x bg-[length:400%_400%] relative overflow-hidden"
      onClick={() => navigate("/")}
    >
      <AnimatedBackground />
      <div
        className={twMerge(
          "w-full max-w-xl rounded-2xl animate-border-light",
          "shadow-2xl shadow-purple-500/10 dark:shadow-black/30"
        )}
        onClick={(e) => e.stopPropagation()}
      >
        <div className="relative w-full h-full p-6 bg-white/80 dark:bg-slate-900/80 backdrop-blur-md rounded-2xl border border-purple-200 dark:border-purple-400/30 z-10">
          <div className="mb-4 flex items-center justify-between">
            <a
              href="https://www.xtablo.com"
              className="inline-flex items-center text-sm text-slate-600 dark:text-slate-400 hover:text-slate-800 dark:hover:text-slate-200 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>
              Retour à l&apos;accueil
            </a>

            {/* Theme Toggle */}
            <Button
              variant="plain"
              isIconOnly
              onPress={toggleTheme}
              className="text-slate-500 hover:text-slate-700 dark:text-slate-400 dark:hover:text-slate-200 p-2"
              aria-label={`Changer le thème (actuellement: ${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-slate-900 dark:text-white mb-6 text-center">
            Créer un compte Xtablo
          </h1>

          <div className="space-y-3 flex flex-col items-center">
            <Form className="space-y-3 w-full" onSubmit={onSubmit} validationErrors={errors}>
              <div className="grid grid-cols-2 gap-3">
                <TextField isRequired name="first_name">
                  <Label className="text-sm">
                    Prénom <span className="text-red-500">*</span>
                  </Label>
                  <Input
                    type="text"
                    value={formData.first_name}
                    onChange={(e) => setFormData({ ...formData, first_name: e.target.value })}
                    required
                  />
                  <FieldError />
                </TextField>
                <TextField isRequired name="last_name">
                  <Label className="text-sm">
                    Nom <span className="text-red-500">*</span>
                  </Label>
                  <Input
                    type="text"
                    value={formData.last_name}
                    onChange={(e) => setFormData({ ...formData, last_name: e.target.value })}
                    required
                  />
                  <FieldError />
                </TextField>
              </div>

              {/* <TextField isRequired name="business_name">
                <Label>
                  Nom de l&apos;entreprise{" "}
                  <span className="text-red-500">*</span>
                </Label>
                <Input
                  type="text"
                  value={formData.business_name}
                  onChange={(e) =>
                    setFormData({ ...formData, business_name: e.target.value })
                  }
                  required
                />
                <FieldError />
              </TextField> */}

              <TextField isRequired name="email">
                <Label className="text-sm">
                  Email professionnel <span className="text-red-500">*</span>
                </Label>
                <Input
                  type="email"
                  value={formData.email}
                  onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                  required
                />
                <FieldError />
              </TextField>

              <TextField isRequired name="password">
                <Label className="text-sm">
                  Mot de passe <span className="text-red-500">*</span>
                </Label>
                <Input
                  type="password"
                  value={formData.password}
                  onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                  required
                />
                <FieldError />
                {!errors.password && (
                  <Text slot="description" className="text-red-500">
                    {errors.password}
                  </Text>
                )}
              </TextField>

              <TextField isRequired name="confirmPassword">
                <Label className="text-sm">
                  Confirmer le mot de passe <span className="text-red-500">*</span>
                </Label>
                <Input
                  type="password"
                  value={formData.confirmPassword}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      confirmPassword: e.target.value,
                    })
                  }
                  required
                />
                <FieldError />
              </TextField>

              <TextField className="flex items-start">
                <Input
                  type="checkbox"
                  id="terms"
                  className="mt-1 mr-2 h-4 w-4 text-blue-600 focus:ring-blue-500 border-slate-300 rounded"
                  required
                />
                <Label htmlFor="terms" className="text-xs text-slate-600 dark:text-slate-300">
                  J&apos;accepte les{" "}
                  <a
                    href="#"
                    className="text-black hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-300"
                  >
                    conditions d&apos;utilisation
                  </a>{" "}
                  et la{" "}
                  <a
                    href="#"
                    className="text-black hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-300"
                  >
                    politique de confidentialité
                  </a>
                </Label>
              </TextField>

              <Button
                className={twMerge(
                  "w-full bg-black border-black text-white dark:bg-black dark:border-black dark:text-white",
                  "hover:bg-gray-800 dark:hover:bg-gray-800 transition-colors"
                )}
                type="submit"
                isPending={isPending}
                pendingLabel="Création du compte..."
              >
                {isPending ? "Création du compte..." : "Créer mon compte"}
              </Button>
            </Form>

            <div className="relative my-4">
              <div className="absolute inset-0 flex items-center">
                <div className="w-full border-t border-slate-200 dark:border-slate-700"></div>
              </div>
              <div className="relative flex justify-center text-sm">
                <span
                  className={twMerge(
                    "px-3 py-1 bg-white dark:bg-slate-800",
                    "text-slate-500 dark:text-slate-400",
                    "text-xs font-medium",
                    "rounded-full",
                    "relative z-10",
                    "before:absolute before:w-[100px] before:h-[1px] before:bg-slate-300 dark:before:bg-slate-600 before:left-[-110px] before:top-1/2",
                    "after:absolute after:w-[100px] after:h-[1px] after:bg-slate-300 dark:after:bg-slate-600 after:right-[-110px] after:top-1/2"
                  )}
                >
                  Ou continuer avec
                </span>
              </div>
            </div>

            <LoginWithGoogle />

            <p className="text-center text-xs text-slate-600 dark:text-slate-400">
              Déjà un compte ?{" "}
              <Link to="/login">
                <a className="text-black hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-300 font-medium text-sm px-2 py-1 rounded border-gray-300 dark:border-slate-600 hover:bg-gray-50 dark:hover:bg-slate-700 transition-colors">
                  Se connecter
                </a>
              </Link>
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}
