import { useState, type FormEvent } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { motion } from 'framer-motion';
import { Mail, Lock, ArrowRight, Zap, Shield, Trophy } 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';

const stagger = {
  initial: {},
  animate: { transition: { staggerChildren: 0.06, delayChildren: 0.1 } },
};

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

const brandFeatures = [
  { icon: Zap, text: 'Instant matchmaking' },
  { icon: Shield, text: 'Anti-cheat protected' },
  { icon: Trophy, text: 'Ranked leaderboards' },
];

export default function Login() {
  const navigate = useNavigate();
  const { toast } = useToast();
  const login = useAuthStore((s) => s.login);
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [errors, setErrors] = useState<{ email?: string; password?: string }>({});

  async function handleSubmit(e: FormEvent) {
    e.preventDefault();
    setErrors({});
    const errs: { email?: string; password?: string } = {};
    if (!email) errs.email = 'Email is required';
    if (!password) errs.password = 'Password is required';
    if (Object.keys(errs).length > 0) { setErrors(errs); return; }

    setLoading(true);
    try {
      const { data } = await authAPI.login({ email, password });
      login(data.access_token ?? data.token, data.refresh_token ?? null, data.user);
      toast('Welcome back!', 'success');
      navigate('/dashboard');
    } catch (err: any) {
      const msg = err.response?.data?.error || 'Invalid credentials';
      toast(msg, 'error');
      setErrors({ password: msg });
    } 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 grid-bg opacity-15" />
        <div
          className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-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-[20%] left-[10%] w-[300px] h-[300px] 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">
              Welcome
              <br />
              <span className="text-gradient">back.</span>
            </h2>
            <p className="text-[#5a5a72] text-base font-medium leading-relaxed mb-12 max-w-sm">
              Pick up where you left off. Your rank, your stats, your matches, all waiting for you.
            </p>
          </motion.div>

          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ delay: 0.3 }}
            className="space-y-4"
          >
            {brandFeatures.map((f, i) => (
              <motion.div
                key={f.text}
                initial={{ opacity: 0, x: -16 }}
                animate={{ opacity: 1, x: 0 }}
                transition={{ delay: 0.35 + i * 0.08 }}
                className="flex items-center gap-3"
              >
                <div className="w-8 h-8 rounded-lg bg-[#ff6b2c]/8 border border-[#ff6b2c]/15 flex items-center justify-center flex-shrink-0">
                  <f.icon className="w-3.5 h-3.5 text-[#ff6b2c]" />
                </div>
                <span className="text-sm text-[#a0a0b8] font-medium">{f.text}</span>
              </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 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">
                Sign in
              </h1>
              <p className="text-[#5a5a72] text-sm mt-2 font-medium">
                Enter your credentials to continue
              </p>
            </motion.div>

            <form onSubmit={handleSubmit} className="space-y-4">
              <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="current-password"
                />
              </motion.div>

              <motion.div variants={item} className="pt-2">
                <Button type="submit" loading={loading} className="w-full" size="lg">
                  Sign In
                  <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="/register"
                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"
              >
                Create a new account
                <ArrowRight className="w-3.5 h-3.5" />
              </Link>
            </motion.div>
          </motion.div>
        </motion.div>
      </div>
    </div>
  );
}
