"use client";

import React, { useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { signInWithGoogle, registerUser } from "@/lib/auth";
import { GradientText } from "@/components/ui/gradient-text";
import { Eye, EyeOff } from "lucide-react";

export default function SignupPage() {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [inviteCode, setInviteCode] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [formError, setFormError] = useState("");
  const [passwordError, setPasswordError] = useState("");
  const [confirmPasswordError, setConfirmPasswordError] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [agreeToTerms, setAgreeToTerms] = useState(true);
  const router = useRouter();

  /** Password validation function with English prompts */
  const validatePassword = (password: string): string => {
    if (password.length < 8) {
      return "Password must be at least 8 characters";
    }
    if (password.length > 18) {
      return "Password cannot exceed 18 characters";
    }
    if (!/^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d!@#$%^*&]{8,18}$/.test(password)) {
      return "Password must contain both letters and numbers";
    }
    return "";
  };

  /** Handle Terms of Service click */
  const handleTermsClick = () => {
    window.open("/Terms", "_blank");
  };

  /** Handle Privacy Policy click */
  const handlePrivacyClick = () => {
    window.open("/Privacy", "_blank");
  };

  /** 处理密码输入变化 */
  const handlePasswordChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newPassword = e.target.value;
    setPassword(newPassword);

    if (newPassword) {
      const error = validatePassword(newPassword);
      setPasswordError(error);
    } else {
      setPasswordError("");
    }

    // 如果确认密码已输入，重新验证确认密码
    if (confirmPassword) {
      if (newPassword !== confirmPassword) {
        setConfirmPasswordError("Passwords do not match");
      } else {
        setConfirmPasswordError("");
      }
    }
  };

  /** 处理确认密码输入变化 */
  const handleConfirmPasswordChange = (
    e: React.ChangeEvent<HTMLInputElement>
  ) => {
    const newConfirmPassword = e.target.value;
    setConfirmPassword(newConfirmPassword);

    if (newConfirmPassword) {
      if (password !== newConfirmPassword) {
        setConfirmPasswordError("Passwords do not match");
      } else {
        setConfirmPasswordError("");
      }
    } else {
      setConfirmPasswordError("");
    }
  };

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    // 验证密码
    const passwordValidationError = validatePassword(password);
    if (passwordValidationError) {
      setPasswordError(passwordValidationError);
      return;
    }

    // 验证确认密码
    if (password !== confirmPassword) {
      setConfirmPasswordError("Passwords do not match");
      return;
    }

    // 验证是否同意条款
    if (!agreeToTerms) {
      setFormError("Please agree to the Terms of Service and Privacy Policy");
      return;
    }

    setIsSubmitting(true);
    setFormError("");

    try {
      // Use new registration API
      await registerUser({
        userName: name,
        email,
        password,
        inviteCode: inviteCode || undefined,
      });

      // Redirect to login page after successful registration
      router.push("/login?registered=true");
    } catch (error: any) {
      console.error("Signup error:", error);
      setFormError(error.message||error.msg || "Registration failed, please try again");
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="min-h-screen relative overflow-hidden">
      {/* 背景视频 */}
      <video
        autoPlay
        loop
        muted
        playsInline
        className="absolute inset-0 w-full h-full object-cover"
        data-alt="background-video"
      >
        <source src="/assets/login.mp4" type="video/mp4" />
      </video>

      {/* 视频遮罩层 */}
      <div
        className="absolute inset-0 bg-black/20"
        data-alt="video-overlay"
      ></div>

      {/* Logo */}
      <div
        className="absolute top-8 left-8 z-50"
        data-alt="logo-container"
        onClick={() => router.push("/")}
      >
        <span className="logo-heart cursor-pointer">
          <GradientText
            text="MovieFlow"
            startPercentage={30}
            endPercentage={70}
          />
        </span>
        {/* beta标签 */}
        <span className="inline-flex items-center px-1.5 py-0.5 text-[8px] font-semibold tracking-wider text-[rgb(212 202 202)] border border-[rgba(106,244,249,0.2)] rounded-full shadow-[0_0_10px_rgba(106,244,249,0.1)]">
          Beta
        </span>
      </div>

      {/* 注册框 - 居中显示 */}
      <div className="relative bottom-4 z-10 flex items-center justify-center min-h-screen p-4">
        <div className="max-w-md w-full bg-black/40 backdrop-blur-lg border border-white/20 rounded-2xl p-6 shadow-2xl">
          <div className="text-center mb-4">
            <h2 className="text-2xl font-bold text-white mb-2">
              Sign Up, for free
            </h2>
            <p className="text-gray-300">Create your account to get started</p>
          </div>

          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-white mb-1">
                Email
              </label>
              <input
                type="email"
                placeholder="your@email.com"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                required
                className="w-full px-4 py-3 rounded-lg bg-black/30 border border-white/20 text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-white mb-1">
                Name
              </label>
              <input
                type="text"
                placeholder="Your name"
                value={name}
                onChange={(e) => setName(e.target.value)}
                required
                className="w-full px-4 py-3 rounded-lg bg-black/30 border border-white/20 text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-white mb-1">
                Password
              </label>
              <div className="relative">
                <input
                  type={showPassword ? "text" : "password"}
                  placeholder="8-18 characters, letters, numbers and !@#$%^*&"
                  value={password}
                  onChange={handlePasswordChange}
                  required
                  className={`w-full px-4 py-3 pr-12 rounded-lg bg-black/30 border text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent ${
                    passwordError ? "border-red-500/50" : "border-white/20"
                  }`}
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-white transition-colors"
                  data-alt="toggle-password-visibility"
                >
                  {showPassword ? <EyeOff size={20} /> : <Eye size={20} />}
                </button>
              </div>

              <div>
                <label className="block text-sm font-medium text-white mb-1 mt-3">
                  Confirm Password
                </label>
                <div className="relative">
                  <input
                    type={showConfirmPassword ? "text" : "password"}
                    placeholder="Confirm your password"
                    value={confirmPassword}
                    onChange={handleConfirmPasswordChange}
                    required
                    className={`w-full px-4 py-3 pr-12 rounded-lg bg-black/30 border text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent ${
                      confirmPasswordError
                        ? "border-red-500/50"
                        : "border-white/20"
                    }`}
                  />
                  <button
                    type="button"
                    onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                    className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-white transition-colors"
                    data-alt="toggle-confirm-password-visibility"
                  >
                    {showConfirmPassword ? (
                      <EyeOff size={20} />
                    ) : (
                      <Eye size={20} />
                    )}
                  </button>
                </div>
              </div>

              {passwordError && (
                <p className="mt-1 text-sm text-red-400">{passwordError}</p>
              )}
              {confirmPasswordError && (
                <p className="mt-1 text-sm text-red-400">
                  {confirmPasswordError}
                </p>
              )}
              {password && !passwordError && (
                <p className="mt-1 text-sm text-green-400">
                  ✓ Password format is correct
                </p>
              )}
              {confirmPassword && !confirmPasswordError && (
                <p className="mt-1 text-sm text-green-400">✓ Passwords match</p>
              )}
            </div>

            <div>
              <label className="block text-sm font-medium text-white mb-1">
                Invite Code
              </label>
              <input
                type="text"
                placeholder="Enter invite code if you have one"
                value={inviteCode}
                onChange={(e) => setInviteCode(e.target.value)}
                className="w-full px-4 py-3 rounded-lg bg-black/30 border border-white/20 text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent"
              />
            </div>

            <div className="flex items-start space-x-3">
              <label
                htmlFor="agreeToTerms"
                className="text-sm text-gray-300 leading-relaxed"
                data-alt="terms-privacy-info"
              >
                By clicking “Sign Up”, you agree to our{' '}
                <button
                  type="button"
                  onClick={handleTermsClick}
                  className="text-purple-400 hover:text-purple-300 underline"
                  data-alt="terms-link"
                >
                  Terms of Service
                </button>{' '}
                and acknowledge that you have read and understand our{' '}
                <button
                  type="button"
                  onClick={handlePrivacyClick}
                  className="text-purple-400 hover:text-purple-300 underline"
                  data-alt="privacy-link"
                >
                  Privacy Policy
                </button>
              </label>
            </div>

            {formError && (
              <div className="bg-red-500/20 text-red-300 p-3 rounded-lg border border-red-500/20">
                {formError}
              </div>
            )}

            <div className="flex gap-4 mt-6">
              <Link
                href="/login"
                className="flex-1 py-3 text-center border border-white/20 rounded-lg text-white hover:bg-white/10 transition-colors"
              >
                Back to login
              </Link>
              <button
                type="submit"
                disabled={
                  isSubmitting ||
                  !!passwordError ||
                  !!confirmPasswordError ||
                  !password ||
                  !confirmPassword
                }
                className="flex-1 py-3 rounded-lg cursor-pointer bg-[#C039F6] hover:bg-[#C039F6]/80 text-white font-medium transition-colors disabled:opacity-70 disabled:cursor-not-allowed"
              >
                {isSubmitting ? "Signing up..." : "Sign Up"}
              </button>
            </div>
          </form>

          {/* <div className="my-6 relative flex items-center">
            <div className="flex-grow border-t border-gray-500/30"></div>
            <span className="flex-shrink mx-4 text-gray-400">or</span>
            <div className="flex-grow border-t border-gray-500/30"></div>
          </div>

          <button
            onClick={handleGoogleSignIn}
            className="w-full flex items-center justify-center gap-3 py-3 border border-white/20 rounded-lg text-white hover:bg-white/5 transition-colors bg-black/30"
          >
            <img src="https://www.gstatic.com/firebasejs/ui/2.0.0/images/auth/google.svg" className="w-5 h-5" alt="Google" />
            Continue with Google
          </button> */}

          <div className="text-center mt-4">
            <p style={{ color: "rgba(255, 255, 255, 0.6)" }}>
              Already have an account?{" "}

            </p>
          </div>
        </div>
      </div>
    </div>
  );
}
