import { useState, useCallback, useRef, type FormEvent } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { motion } from 'framer-motion';
import { User, Mail, Lock, ArrowRight, Crosshair, BarChart3, Server, Users } from 'lucide-react';
import { Input } from '@/components/ui/Input';
import { Button } from '@/components/ui/Button';
import { useToast } from '@/components/ui/Toast';
import { useAuthStore } from '@/stores/authStore';
import { authAPI } from '@/api/client';
import { cn } from '@/lib/cn';

function getPasswordStrength(password: string): number {
  let score = 0;
  if (password.length >= 8) score++;
  if (password.length >= 12) score++;
  if (/[a-z]/.test(password) && /[A-Z]/.test(password)) score++;
  if (/\d/.test(password)) score++;
  if (/[^a-zA-Z0-9]/.test(password)) score++;
  return Math.min(score, 4);
}

const strengthLabels = ['', 'Weak', 'Fair', 'Good', 'Strong'];
const strengthColors = ['', 'bg-red-500', 'bg-amber-500', 'bg-blue-500', 'bg-emerald-500'];
const strengthTextColors = ['', 'text-red-400', 'text-amber-400', 'text-blue-400', 'text-emerald-400'];

const stagger = {
  initial: {},
  animate: { transition: { staggerChildren: 0.05, delayChildren: 0.08 } },
};
const item = {
  initial: { opacity: 0, y: 16 },
  animate: { opacity: 1, y: 0, transition: { type: 'spring' as const, stiffness: 300, damping: 24 } },
};

const highlights = [
  { icon: Crosshair, title: 'Elo Matchmaking', desc: 'Fair, balanced games every time' },
  { icon: BarChart3, title: 'Deep Analytics', desc: 'Track every stat that matters' },
  { icon: Server, title: 'Instant Servers', desc: 'Auto-deployed game servers' },
  { icon: Users, title: '3,200+ Players', desc: 'Growing competitive community' },
];

export default function Register() {
  const navigate = useNavigate();
  const { toast } = useToast();
  const login = useAuthStore((s) => s.login);
  const [username, setUsername] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [usernameAvailable, setUsernameAvailable] = useState<boolean | null>(null);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const debounceRef = useRef<ReturnType<typeof setTimeout>>(undefined);

  const checkUsername = useCallback((value: string) => {
    if (debounceRef.current) clearTimeout(debounceRef.current);
    if (value.length < 3) { setUsernameAvailable(null); return; }
    debounceRef.current = setTimeout(() => { setUsernameAvailable(true); }, 500);
  }, []);

  const strength = getPasswordStrength(password);
  const passwordsMatch = confirmPassword.length > 0 && password === confirmPassword;

  async function handleSubmit(e: FormEvent) {
    e.preventDefault();
    const errs: Record<string, string> = {};
    if (username.length < 3) errs.username = 'Username must be at least 3 characters';
    if (!email.includes('@')) errs.email = 'Enter a valid email address';
    if (password.length < 8) errs.password = 'Password must be at least 8 characters';
    if (password !== confirmPassword) errs.confirmPassword = 'Passwords do not match';
    if (Object.keys(errs).length > 0) { setErrors(errs); return; }
    setErrors({});
    setLoading(true);

    try {
      const { data } = await authAPI.register({ username, email, password });
      login(data.access_token ?? data.token, data.refresh_token ?? null, data.user);
      toast('Account created! Welcome to tapper.', 'success');
      navigate('/dashboard');
    } catch (err: any) {
      const msg = err.response?.data?.error || 'Registration failed';
      toast(msg, 'error');
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="min-h-screen bg-bg-base flex relative overflow-hidden">
      <div className="hidden lg:flex lg:w-[45%] xl:w-[50%] relative items-center justify-center overflow-hidden">
        <div className="absolute inset-0 bg-[#080810]" />
        <div className="absolute inset-0 dot-grid opacity-20" />
        <div
          className="absolute top-[30%] left-1/2 -translate-x-1/2 w-[600px] h-[600px] rounded-full pointer-events-none"
          style={{ background: 'radial-gradient(circle, rgba(255,107,44,0.1) 0%, transparent 55%)' }}
        />
        <div
          className="absolute bottom-[15%] right-[10%] w-[350px] h-[350px] rounded-full pointer-events-none"
          style={{ background: 'radial-gradient(circle, rgba(99,102,241,0.06) 0%, transparent 55%)' }}
        />

        <div className="relative z-10 px-12 xl:px-20 max-w-lg">
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6 }}
          >
            <Link to="/" className="inline-block mb-16">
              <span className="text-2xl font-black tracking-tight text-[#f0f0f5] font-display">
                tapper<span className="text-[#ff6b2c]">.</span>
              </span>
            </Link>
          </motion.div>

          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6, delay: 0.1 }}
          >
            <h2 className="heading-display text-4xl xl:text-5xl text-[#f0f0f5] mb-4">
              Join the
              <br />
              <span className="text-gradient">competition.</span>
            </h2>
            <p className="text-[#5a5a72] text-base font-medium leading-relaxed mb-12 max-w-sm">
              Create your account and start competing in skill-based CS2 matches. Free to play, forever.
            </p>
          </motion.div>

          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ delay: 0.3 }}
            className="grid grid-cols-2 gap-3"
          >
            {highlights.map((h, i) => (
              <motion.div
                key={h.title}
                initial={{ opacity: 0, y: 12 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.35 + i * 0.06 }}
                className="p-4 rounded-xl bg-white/[0.02] border border-[#1a1a2a]/60 group hover:border-[#28283c] transition-colors"
              >
                <h.icon className="w-4 h-4 text-[#ff6b2c] mb-2.5" />
                <p className="text-xs font-bold text-[#f0f0f5] mb-0.5">{h.title}</p>
                <p className="text-[10px] text-[#5a5a72] font-medium">{h.desc}</p>
              </motion.div>
            ))}
          </motion.div>
        </div>

        <div className="absolute right-0 top-0 bottom-0 w-px bg-gradient-to-b from-transparent via-[#1a1a2a] to-transparent" />
      </div>

      <div className="flex-1 flex items-center justify-center px-4 sm:px-8 py-12 relative">
        <div className="lg:hidden absolute inset-0 pointer-events-none">
          <div
            className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[500px] h-[500px] rounded-full"
            style={{ background: 'radial-gradient(ellipse, rgba(255,107,44,0.06) 0%, transparent 60%)' }}
          />
        </div>

        <motion.div
          initial={{ opacity: 0, y: 30 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ type: 'spring', stiffness: 200, damping: 24 }}
          className="relative w-full max-w-[400px]"
        >
          <div className="lg:hidden mb-10 text-center">
            <Link to="/" className="inline-block">
              <span className="text-2xl font-black tracking-tight text-[#f0f0f5] font-display">
                tapper<span className="text-[#ff6b2c]">.</span>
              </span>
            </Link>
          </div>

          <motion.div variants={stagger} initial="initial" animate="animate">
            <motion.div variants={item} className="mb-8">
              <h1 className="text-2xl sm:text-3xl font-extrabold tracking-tight text-[#f0f0f5] font-display">
                Create account
              </h1>
              <p className="text-[#5a5a72] text-sm mt-2 font-medium">
                Set up your player profile
              </p>
            </motion.div>

            <form onSubmit={handleSubmit} className="space-y-4">
              <motion.div variants={item}>
                <Input
                  label="Username"
                  icon={<User className="w-4 h-4" />}
                  value={username}
                  onChange={(e) => { setUsername(e.target.value); checkUsername(e.target.value); }}
                  error={errors.username}
                  success={usernameAvailable === true}
                  autoComplete="username"
                />
              </motion.div>

              <motion.div variants={item}>
                <Input
                  label="Email"
                  type="email"
                  icon={<Mail className="w-4 h-4" />}
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  error={errors.email}
                  autoComplete="email"
                />
              </motion.div>

              <motion.div variants={item}>
                <Input
                  label="Password"
                  type="password"
                  icon={<Lock className="w-4 h-4" />}
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  error={errors.password}
                  autoComplete="new-password"
                />
                {password.length > 0 && (
                  <motion.div
                    initial={{ opacity: 0, height: 0 }}
                    animate={{ opacity: 1, height: 'auto' }}
                    className="mt-3 space-y-1.5"
                  >
                    <div className="flex gap-1">
                      {[1, 2, 3, 4].map((level) => (
                        <motion.div
                          key={level}
                          initial={{ scaleX: 0 }}
                          animate={{ scaleX: strength >= level ? 1 : 0.3 }}
                          className={cn(
                            'flex-1 h-1 rounded-full origin-left transition-colors duration-300',
                            strength >= level ? strengthColors[strength] : 'bg-[#1a1a2a]'
                          )}
                        />
                      ))}
                    </div>
                    <p className={cn('text-[10px] font-bold uppercase tracking-wider', strengthTextColors[strength])}>
                      {strengthLabels[strength]}
                    </p>
                  </motion.div>
                )}
              </motion.div>

              <motion.div variants={item}>
                <Input
                  label="Confirm Password"
                  type="password"
                  icon={<Lock className="w-4 h-4" />}
                  value={confirmPassword}
                  onChange={(e) => setConfirmPassword(e.target.value)}
                  error={errors.confirmPassword}
                  success={passwordsMatch}
                  autoComplete="new-password"
                />
              </motion.div>

              <motion.div variants={item} className="pt-2">
                <Button type="submit" loading={loading} className="w-full" size="lg">
                  Create Account
                  <ArrowRight className="w-4 h-4" />
                </Button>
              </motion.div>
            </form>

            <motion.div variants={item} className="flex items-center gap-4 my-8">
              <div className="flex-1 h-px bg-[#1a1a2a]" />
              <span className="text-[10px] font-bold text-[#3a3a4e] uppercase tracking-[0.15em]">or</span>
              <div className="flex-1 h-px bg-[#1a1a2a]" />
            </motion.div>

            <motion.div variants={item}>
              <Link
                to="/login"
                className="w-full inline-flex items-center justify-center gap-2 px-7 py-3.5 text-sm font-bold text-[#a0a0b8] bg-[#0d0d14] border border-[#1a1a2a] rounded-xl hover:bg-[#111119] hover:border-[#28283c] hover:text-[#f0f0f5] transition-all duration-200"
              >
                Sign in to existing account
                <ArrowRight className="w-3.5 h-3.5" />
              </Link>
            </motion.div>

            <motion.p variants={item} className="text-[10px] text-[#3a3a4e] mt-6 text-center font-medium leading-relaxed">
              By creating an account you agree to our Terms of Service and Privacy Policy.
            </motion.p>
          </motion.div>
        </motion.div>
      </div>
    </div>
  );
}
