'use client';

import React, { useState } from 'react';
import { useRouter } from 'next/navigation';
import { motion } from 'framer-motion';
import { FiUser, FiLock } from 'react-icons/fi';
import Input from '@/components/ui/Input';
import Button from '@/components/ui/Button';
import { useAuthStore } from '@/stores/authStore';
import toast from 'react-hot-toast';
import LoginBackgroundCollage from '@/components/auth/LoginBackgroundCollage';

export default function LoginPage() {
  const router = useRouter();
  const { login, isLoading, error, clearError } = useAuthStore();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

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

    if (!email.trim() || !password.trim()) {
      toast.error('Por favor, completa todos los campos');
      return;
    }

    try {
      await login(email, password);
      toast.success('¡Bienvenido de vuelta!');
      router.push('/home');
    } catch {
      // Error is handled by store
    }
  };

  return (
    <div className="relative flex items-center justify-center px-4 py-12 min-h-screen bg-dark overflow-hidden">
      {/* Dynamic Movie Collage Background (TMDB) */}
      <LoginBackgroundCollage />

      {/* Background Glows (Logo Palette: Magenta & Cyan) */}
      <div className="absolute top-1/4 left-1/3 -translate-x-1/2 -translate-y-1/2 w-80 h-80 rounded-full bg-primary/10 blur-[130px] pointer-events-none" />
      <div className="absolute bottom-1/4 right-1/3 translate-x-1/2 translate-y-1/2 w-80 h-80 rounded-full bg-accent/15 blur-[130px] pointer-events-none" />

      <motion.div
        initial={{ opacity: 0, y: 30, scale: 0.95 }}
        animate={{ opacity: 1, y: 0, scale: 1 }}
        transition={{ duration: 0.6, ease: [0.22, 1, 0.36, 1] }}
        className="w-full max-w-md relative z-10"
      >
        {/* Glassmorphism card */}
        <div className="bg-black/30 backdrop-blur-xl border border-white/[0.08] rounded-2xl p-8 shadow-2xl shadow-black/70">
          {/* Logo */}
          <motion.div
            initial={{ opacity: 0, y: -10 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.2 }}
            className="flex flex-col items-center mb-8"
          >
            <div className="flex items-center justify-center max-w-[160px] mb-3">
              <img
                src="/logo.png"
                alt="Cat Tv"
                className="w-full h-auto object-contain select-none"
              />
            </div>
            <p className="text-white/60 text-xs font-bold tracking-widest uppercase select-none">
              TV en vivo, donde estés
            </p>
          </motion.div>

          {/* Form */}
          <form onSubmit={handleSubmit} className="space-y-5">
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: 0.3 }}
            >
              <Input
                label="Usuario"
                type="text"
                placeholder="Tu usuario de IPTV"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                icon={<FiUser size={18} />}
                autoComplete="username"
              />
            </motion.div>

            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: 0.4 }}
            >
              <Input
                label="Contraseña"
                type="password"
                placeholder="••••••••"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                icon={<FiLock size={18} />}
                autoComplete="current-password"
              />
            </motion.div>

            {/* Error message */}
            {error && (
              <motion.div
                initial={{ opacity: 0, height: 0 }}
                animate={{ opacity: 1, height: 'auto' }}
                className="bg-red-500/10 border border-red-500/20 rounded-lg p-3"
              >
                <p className="text-red-400 text-sm text-center">{error}</p>
              </motion.div>
            )}

            <motion.div
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.5 }}
            >
              <Button
                type="submit"
                variant="primary"
                size="lg"
                fullWidth
                loading={isLoading}
                className="mt-2 shadow-lg shadow-primary/20"
              >
                Entrar
              </Button>
            </motion.div>
          </form>

          {/* Links */}
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ delay: 0.6 }}
            className="mt-6 text-center"
          >
            <a
              href="#"
              className="text-sm text-white/40 hover:text-primary transition-colors duration-300"
            >
              ¿Olvidaste tu contraseña?
            </a>
          </motion.div>
        </div>

        {/* Bottom text */}
        <motion.p
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ delay: 0.7 }}
          className="text-center text-white/20 text-xs mt-6"
        >
          Cat Tv © {new Date().getFullYear()} — Todos los derechos reservados
        </motion.p>
      </motion.div>
    </div>
  );
}
