import { useState } from 'react';
import { publicAuthService } from '../services/authService';
import { usePublicAuthStore } from '../store/publicAuthStore';
import { useNavigate } from 'react-router-dom';
import { motion } from 'framer-motion';
import { Mail, Lock, User, ArrowRight, ShieldCheck } from 'lucide-react';

export default function LoginPage() {
  const setUser = usePublicAuthStore(state => state.setUser);
  const [isLogin, setIsLogin] = useState(true);
  const [formData, setFormData] = useState({ username: '', email: '', password: '' });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [showMfa, setShowMfa] = useState(false);
  const [mfaCode, setMfaCode] = useState('');

  const navigate = useNavigate();

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError('');

    try {
      if (isLogin) {
        const res = await publicAuthService.login(formData.username, formData.password);
        if (res.success) {
          if (res.requiresMfa) {
            setShowMfa(true);
          } else {
            setUser({ username: formData.username });
            navigate('/');
          }
        } else {
          setError(res.errorMessage || 'Error al iniciar sesión');
        }
      } else {
        const res = await publicAuthService.register(formData.username, formData.email, formData.password);
        if (res.success) {
          setIsLogin(true);
          setError('Registro exitoso. Por favor inicie sesión.');
        } else {
          setError(res.errorMessage || 'Error al registrarse');
        }
      }
    } catch {
      setError('Error de conexión');
    } finally {
      setLoading(false);
    }
  };

  if (showMfa) {
    return (
      <div className="min-h-screen bg-slate-50 flex items-center justify-center p-6 font-display">
        <motion.div
          initial={{ opacity: 0, scale: 0.95 }}
          animate={{ opacity: 1, scale: 1 }}
          className="bg-white w-full max-w-md p-10 rounded-[2.5rem] shadow-2xl border border-slate-100"
        >
          <div className="text-center mb-8">
            <div className="bg-blue-600 w-16 h-16 rounded-3xl flex items-center justify-center text-white mx-auto shadow-xl shadow-blue-500/20 mb-6">
              <ShieldCheck size={32} />
            </div>
            <h1 className="text-3xl font-black text-slate-900 tracking-tight">Verificación MFA</h1>
            <p className="text-slate-500 font-bold uppercase tracking-widest text-[10px] mt-2">Ingrese el código de su aplicación de autenticación</p>
          </div>

          <div className="space-y-6">
            <input
              type="text"
              placeholder="000000"
              value={mfaCode}
              onChange={(e) => setMfaCode(e.target.value)}
              className="w-full text-center text-4xl font-black tracking-[0.5em] py-6 bg-slate-50 border-none rounded-3xl focus:ring-4 focus:ring-blue-100 outline-none transition-all"
              maxLength={6}
            />
            <button
              className="w-full bg-slate-900 text-white font-black uppercase tracking-widest py-5 rounded-3xl shadow-xl hover:bg-black transition-all"
              onClick={() => navigate('/')} // En un flujo real llamaríamos a verifyMfa
            >
              Verificar Identidad
            </button>
          </div>
        </motion.div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-[#f8fafc] flex items-center justify-center p-6 font-display">
      <div className="w-full max-w-5xl bg-white rounded-[3rem] shadow-2xl overflow-hidden flex flex-col md:flex-row border border-slate-100">

        {/* Lado Izquierdo: Visual & Branding */}
        <div className="md:w-1/2 bg-slate-900 p-12 flex flex-col justify-between text-white relative overflow-hidden">
          <div className="absolute top-0 right-0 w-64 h-64 bg-blue-600/20 rounded-full -mr-32 -mt-32 blur-3xl"></div>

          <div className="relative z-10">
            <div className="bg-blue-600 w-12 h-12 rounded-2xl flex items-center justify-center mb-8 shadow-lg shadow-blue-500/20">
              <ShieldCheck size={24} />
            </div>
            <h2 className="text-5xl font-black tracking-tighter leading-none mb-6">
              Vende y compra con total confianza.
            </h2>
            <p className="text-slate-400 font-medium text-lg leading-relaxed">
              Únete a la comunidad de clasificados más grande de la región. Seguridad verificada y contacto directo.
            </p>
          </div>

          <div className="flex gap-8 relative z-10">
            <div className="flex flex-col">
              <span className="text-2xl font-black tracking-tight">25k+</span>
              <span className="text-[10px] text-slate-500 font-bold uppercase tracking-widest">Avisos activos</span>
            </div>
            <div className="flex flex-col">
              <span className="text-2xl font-black tracking-tight">10k+</span>
              <span className="text-[10px] text-slate-500 font-bold uppercase tracking-widest">Usuarios verificados</span>
            </div>
          </div>
        </div>

        {/* Lado Derecho: Formulario */}
        <div className="md:w-1/2 p-12 lg:p-16">
          <div className="flex justify-between items-center mb-12">
            <div>
              <h1 className="text-3xl font-black text-slate-900 tracking-tight">
                {isLogin ? '¡Hola de nuevo!' : 'Crea tu cuenta'}
              </h1>
              <p className="text-xs font-bold text-slate-400 uppercase tracking-widest mt-1">
                {isLogin ? 'Accede a tu panel personal' : 'Registrarse es gratis y rápido'}
              </p>
            </div>
          </div>

          <form onSubmit={handleSubmit} className="space-y-6">
            <div className="space-y-2">
              <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest ml-4">Nombre de usuario</label>
              <div className="relative">
                <User className="absolute left-5 top-1/2 -translate-y-1/2 text-slate-400" size={18} />
                <input
                  type="text"
                  required
                  value={formData.username}
                  onChange={(e) => setFormData({ ...formData, username: e.target.value })}
                  className="w-full pl-14 pr-6 py-5 bg-slate-50 border-none rounded-3xl focus:ring-4 focus:ring-blue-100 outline-none transition-all font-medium"
                  placeholder="ej: juanperez"
                />
              </div>
            </div>

            {!isLogin && (
              <div className="space-y-2">
                <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest ml-4">Correo Electrónico</label>
                <div className="relative">
                  <Mail className="absolute left-5 top-1/2 -translate-y-1/2 text-slate-400" size={18} />
                  <input
                    type="email"
                    required
                    value={formData.email}
                    onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                    className="w-full pl-14 pr-6 py-5 bg-slate-50 border-none rounded-3xl focus:ring-4 focus:ring-blue-100 outline-none transition-all font-medium"
                    placeholder="tu@email.com"
                  />
                </div>
              </div>
            )}

            <div className="space-y-2">
              <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest ml-4">Contraseña</label>
              <div className="relative">
                <Lock className="absolute left-5 top-1/2 -translate-y-1/2 text-slate-400" size={18} />
                <input
                  type="password"
                  required
                  value={formData.password}
                  onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                  className="w-full pl-14 pr-6 py-5 bg-slate-50 border-none rounded-3xl focus:ring-4 focus:ring-blue-100 outline-none transition-all font-medium"
                  placeholder="••••••••"
                />
              </div>
            </div>

            {error && (
              <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="p-4 bg-rose-50 rounded-2xl text-rose-600 text-xs font-bold border border-rose-100">
                {error}
              </motion.div>
            )}

            <button
              type="submit"
              disabled={loading}
              className="w-full bg-blue-600 text-white font-black uppercase tracking-widest py-5 rounded-3xl shadow-xl shadow-blue-500/30 hover:bg-blue-700 hover:-translate-y-1 active:translate-y-0 transition-all flex items-center justify-center gap-3 group"
            >
              {loading ? 'Cargando...' : isLogin ? 'Entrar' : 'Registrarme'}
              <ArrowRight size={20} className="group-hover:translate-x-1 transition-transform" />
            </button>
          </form>

          {/* Divisor */}
          <div className="my-10 flex items-center gap-4 text-slate-300">
            <div className="flex-1 h-px bg-slate-100"></div>
            <span className="text-[10px] font-black uppercase tracking-widest px-2">O continuar con</span>
            <div className="flex-1 h-px bg-slate-100"></div>
          </div>

          {/* Google Login Placeholder Button */}
          <button className="w-full bg-white text-slate-900 border-2 border-slate-100 font-bold py-5 rounded-3xl flex items-center justify-center gap-4 hover:bg-slate-50 transition-all shadow-sm">
            <img src="https://www.svgrepo.com/show/475656/google-color.svg" className="w-6 h-6" alt="Google" />
            Sign in with Google
          </button>

          <div className="mt-12 text-center">
            <button
              onClick={() => setIsLogin(!isLogin)}
              className="text-[10px] font-black uppercase tracking-widest text-slate-400 hover:text-blue-600 transition-colors"
            >
              {isLogin ? '¿No tienes cuenta? Regístrate aquí' : '¿Ya tienes cuenta? Inicia sesión'}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
