import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Truck, ShieldCheck, ArrowRight, Eye, EyeOff, Mail, Lock, Zap } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { useAuthContext } from '@/components/shared/AuthProvider';
import { useDocumentMetadata } from '@/hooks/useDocumentMetadata';

/**
 * LoginPage V2 - Fleet Environment (Frota)
 * Standardized dual-panel layout based on the Financial model.
 */
export const LoginPage = () => {
  useDocumentMetadata('Login | Pralog Frota', 'fleet');
  const [showPassword, setShowPassword] = useState(false);
  const [view, setView] = useState('login'); // 'login' | 'recovery'
  const [formData, setFormData] = useState({ email: '', password: '' });
  const { login, error, loading, user } = useAuthContext();
  const navigate = useNavigate();

  // Removido o redirecionamento automático para priorizar o fluxo explícito
  /*
  useEffect(() => {
    if (user) {
      navigate('/fleet-v2');
    }
  }, [user, navigate]);
  */

  const togglePasswordVisibility = () => setShowPassword(!showPassword);

  const handleLogin = async (e) => {
    e.preventDefault();
    const success = await login({ email: formData.email, password: formData.password }, 'fleet');
    if (success) {
      navigate('/fleet-v2');
    }
  };

  const handleChange = (e) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  };

  return (
    <div className="min-h-screen flex flex-col md:flex-row bg-slate-50 font-inter overflow-hidden">
      
      {/* Visual Panel - Standardized Premium Style */}
      <div className="hidden md:flex flex-1 bg-emerald-600 relative overflow-hidden items-center justify-center font-inter">
        {/* Animated Background Elements */}
        <div className="absolute inset-0 bg-gradient-to-br from-emerald-600 via-emerald-500 to-emerald-800 opacity-40" />
        <div className="absolute -top-[10%] -left-[10%] w-[60%] h-[60%] bg-white/5 rounded-full blur-[120px] animate-pulse" />
        <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-full h-full bg-[url('https://grainy-gradients.vercel.app/noise.svg')] opacity-20 contrast-150" />
        
        <div className="relative z-10 text-center p-12 max-w-lg">
          <motion.div 
            initial={{ opacity: 0, scale: 0.8 }}
            animate={{ opacity: 1, scale: 1 }}
            transition={{ duration: 0.8 }}
            className="mb-10 flex justify-center"
          >
            <div className="w-28 h-28 bg-white/10 backdrop-blur-xl rounded-[2.5rem] flex items-center justify-center shadow-[0_0_50px_rgba(255,255,255,0.1)] border border-white/20 ring-1 ring-white/10">
              <Truck className="w-14 h-14 text-white drop-shadow-[0_0_15px_rgba(255,255,255,0.5)]" />
            </div>
          </motion.div>
          
          <motion.div
            initial={{ opacity: 0, y: 30 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.3, duration: 0.8 }}
            className="space-y-4"
          >
            <h1 className="text-7xl font-black text-white mb-2 tracking-tighter leading-none">
              Pralog<span className="text-emerald-100">Frota</span>
            </h1>
            <div className="h-1.5 w-24 bg-emerald-300 mx-auto rounded-full mb-6 shadow-[0_0_15px_rgba(110,231,183,0.5)]" />
            <p className="text-xl text-emerald-50 font-medium tracking-tight opacity-80 leading-relaxed">
              Gestão inteligente de frotas e ativos em uma plataforma de alto desempenho.
            </p>
          </motion.div>
          
          {/* Subtle metrics simulation or branding decoration */}
          <div className="mt-16 grid grid-cols-2 gap-4">
            <div className="p-4 bg-white/5 backdrop-blur-md rounded-2xl border border-white/10 text-left">
              <div className="text-[0.6rem] font-black uppercase tracking-[0.2em] text-emerald-100 opacity-60 mb-1">Status</div>
              <div className="text-sm font-bold text-white flex items-center gap-2">
                <div className="w-2 h-2 rounded-full bg-white animate-pulse" /> Operacional
              </div>
            </div>
            <div className="p-4 bg-white/5 backdrop-blur-md rounded-2xl border border-white/10 text-left">
              <div className="text-[0.6rem] font-black uppercase tracking-[0.2em] text-emerald-100 opacity-60 mb-1">Versão</div>
              <div className="text-sm font-bold text-white">2.5.0 Premium</div>
            </div>
          </div>
        </div>
      </div>

      {/* Form Panel - Premium Standardized */}
      <div className="flex-1 flex items-center justify-center p-8 bg-white z-10 lg:rounded-l-[3.5rem] shadow-[-20px_0_50px_rgba(0,0,0,0.05)]">
        <div className="w-full max-w-md space-y-10">
          
          <AnimatePresence mode="wait">
            {view === 'login' ? (
              <motion.div
                key="login"
                initial={{ opacity: 0, x: 20 }}
                animate={{ opacity: 1, x: 0 }}
                exit={{ opacity: 0, x: -20 }}
                transition={{ duration: 0.5 }}
                className="space-y-8"
              >
                <div className="text-center md:text-left space-y-2">
                  <motion.div
                    initial={{ opacity: 0, scale: 0.9 }}
                    animate={{ opacity: 1, scale: 1 }}
                    className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-emerald-500/10 text-emerald-600 text-[0.65rem] font-black uppercase tracking-widest mb-4 border border-emerald-500/20"
                  >
                    <Zap size={14} className="fill-emerald-500" /> Sistema de Frota
                  </motion.div>
                  <h2 className="text-4xl font-black text-slate-900 tracking-tight leading-tight">Painel de Acesso</h2>
                  <p className="text-slate-500 font-medium font-inter">Insira suas credenciais corporativas para entrar.</p>
                </div>

                <form onSubmit={handleLogin} className="space-y-6">
                  <div className="space-y-4">
                    {/* Email Input */}
                    <div className="space-y-2 group font-inter">
                      <label className="text-[0.7rem] font-bold uppercase tracking-widest text-slate-500 ml-1 group-focus-within:text-emerald-600 transition-colors">
                        Usuário / E-mail
                      </label>
                      <div className="relative">
                        <div className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400 group-focus-within:text-emerald-500 transition-colors">
                          <Mail size={18} />
                        </div>
                        <input 
                          type="email" 
                          name="email"
                          value={formData.email}
                          onChange={handleChange}
                          placeholder="admin@pralog.com"
                          className="w-full pl-12 pr-4 py-4 bg-slate-50 border-none rounded-2xl ring-1 ring-slate-200 focus:ring-2 focus:ring-emerald-500 outline-none transition-all text-slate-900 font-medium shadow-sm"
                          required
                        />
                      </div>
                    </div>

                    {/* Password Input */}
                    <div className="space-y-2 group font-inter">
                      <div className="flex justify-between items-center ml-1">
                        <label className="text-[0.7rem] font-bold uppercase tracking-widest text-slate-500 group-focus-within:text-emerald-600 transition-colors">
                          Senha de Segurança
                        </label>
                      </div>
                      <div className="relative">
                        <div className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400 group-focus-within:text-emerald-500 transition-colors">
                          <Lock size={18} />
                        </div>
\                        <input 
                          type={showPassword ? "text" : "password"} 
                          name="password"
                          value={formData.password}
                          onChange={handleChange}
                          placeholder="••••••••"
                          className="w-full pl-12 pr-12 py-4 bg-slate-50 border-none rounded-2xl ring-1 ring-slate-200 focus:ring-2 focus:ring-emerald-500 outline-none transition-all text-slate-900 font-medium shadow-sm"
                          required
                        />
                        <button 
                          type="button"
                          onClick={togglePasswordVisibility}
                          className="absolute right-4 top-1/2 -translate-y-1/2 text-slate-400 hover:text-emerald-600 transition-colors disabled:opacity-50"
                        >
                          {showPassword ? <EyeOff size={20} /> : <Eye size={20} />}
                        </button>
                      </div>
                    </div>
                  </div>

                  <div className="flex items-center justify-between px-1 font-inter">
                    <label className="flex items-center gap-2 cursor-pointer group">
                      <input type="checkbox" className="w-4 h-4 rounded border-slate-300 text-emerald-600 focus:ring-emerald-500 cursor-pointer bg-slate-50" />
                      <span className="text-xs text-slate-500 group-hover:text-slate-900 font-bold transition-colors">Manter conectado</span>
                    </label>
                    <button 
                      type="button" 
                      onClick={() => setView('recovery')}
                      className="text-xs font-black text-emerald-600 hover:text-emerald-700 transition-colors uppercase tracking-widest"
                    >
                      Esqueceu a senha?
                    </button>
                  </div>

                  {error && (
                    <motion.div 
                      initial={{ opacity: 0, y: -10 }}
                      animate={{ opacity: 1, y: 0 }}
                      className="p-4 bg-destructive/10 border border-destructive/20 rounded-2xl text-destructive text-[0.7rem] font-bold flex items-center gap-3 uppercase tracking-tight"
                    >
                      <Zap size={16} className="fill-destructive" /> {error}
                    </motion.div>
                  )}

                  <button 
                    type="submit"
                    disabled={loading}
                    className="group w-full py-5 bg-emerald-600 hover:bg-emerald-700 text-white font-black rounded-2xl shadow-xl shadow-emerald-500/20 transform active:scale-[0.98] transition-all flex items-center justify-center gap-3 text-sm uppercase tracking-[0.2em] font-inter"
                  >
                    {loading ? (
                       <div className="flex items-center gap-3">
                         <div className="w-5 h-5 border-3 border-white/30 border-t-white rounded-full animate-spin" />
                         <span>Validando</span>
                       </div>
                    ) : (
                      <>
                        Entrar no Painel <ArrowRight size={20} className="group-hover:translate-x-1 transition-transform" />
                      </>
                    )}
                  </button>
                </form>
              </motion.div>
            ) : (
              <motion.div
                key="recovery"
                initial={{ opacity: 0, x: 20 }}
                animate={{ opacity: 1, x: 0 }}
                exit={{ opacity: 0, x: -20 }}
                transition={{ duration: 0.5 }}
                className="space-y-8"
              >
                <div className="text-center md:text-left space-y-2">
                  <h2 className="text-4xl font-black text-slate-900 tracking-tight leading-tight">Recuperar Acesso</h2>
                  <p className="text-slate-500 font-medium">Informe seu e-mail corporativo para receber as instruções.</p>
                </div>

                <form className="space-y-6">
                  <div className="space-y-2 group">
                    <label className="text-[0.7rem] font-bold uppercase tracking-widest text-slate-500 ml-1 group-focus-within:text-emerald-600 transition-colors">
                      E-mail de Cadastro
                    </label>
                    <div className="relative">
                      <div className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400 group-focus-within:text-emerald-500 transition-colors">
                        <Mail size={18} />
                      </div>
                      <input 
                        type="email" 
                        placeholder="seu.email@empresa.com"
                        className="w-full pl-12 pr-4 py-4 bg-slate-50 border-none rounded-2xl ring-1 ring-slate-200 focus:ring-2 focus:ring-emerald-500 outline-none transition-all text-slate-900 font-medium"
                        required
                      />
                    </div>
                  </div>

                  <button 
                    type="submit"
                    className="w-full py-5 bg-emerald-600 hover:bg-emerald-700 text-white font-black rounded-2xl shadow-xl shadow-emerald-500/20 transform active:scale-[0.98] transition-all text-sm uppercase tracking-[0.2em]"
                  >
                    Enviar Link de Redefinição
                  </button>

                  <div className="text-center">
                    <button 
                      type="button" 
                      onClick={() => setView('login')}
                      className="text-xs font-black text-slate-500 hover:text-slate-900 transition-colors uppercase tracking-[0.2em]"
                    >
                      ← Voltar para o Login
                    </button>
                  </div>
                </form>
              </motion.div>
            )}
          </AnimatePresence>

          {/* Legal Footer / Trust Badges */}
          <div className="pt-12 space-y-6 border-t border-slate-100">
            <div className="flex items-center justify-center gap-6 text-slate-300">
               <div className="flex items-center gap-2">
                 <ShieldCheck size={16} className="text-emerald-500" />
                 <span className="text-[0.6rem] font-black uppercase tracking-widest text-slate-400">Segurança TLS 1.3</span>
               </div>
               <div className="w-1 h-1 bg-slate-200 rounded-full" />
               <span className="text-[0.6rem] font-black uppercase tracking-widest text-slate-400">Criptografia AES-256</span>
            </div>
            
            <div className="text-center">
              <p className="text-[10px] text-slate-300 uppercase tracking-[0.4em] font-black opacity-60 transition-opacity hover:opacity-100 cursor-default">
                © {new Date().getFullYear()} PRALOG FROTA • LOGÍSTICA INTELIGENTE
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};
