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

/**
 * LoginPage V2 - Financial Environment
 * Premium design based on Rect project.
 */
export const LoginPage = () => {
  useDocumentMetadata('Login | Integra Finance', 'finance');
  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 permitir que o ProtectedRoute 
  // e o fluxo de login explícito controlem a navegação.
  /*
  useEffect(() => {
    if (user) {
      navigate('/financeiro-v2');
    }
  }, [user, navigate]);
  */

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

  const handleLogin = async (e) => {
    e.preventDefault();
    const success = await login({ email: formData.email, password: formData.password }, 'financeiro');
    if (success) {
      navigate('/plataforma/financeiro-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">
      {/* Visual Panel */}
      <div className="hidden md:flex flex-1 bg-emerald-600 relative overflow-hidden items-center justify-center font-inter">
        <div className="absolute inset-0 bg-gradient-to-br from-emerald-600 via-emerald-500 to-emerald-800 opacity-40" />
        <div className="relative z-10 text-center p-12">
          <motion.div 
            initial={{ opacity: 0, scale: 0.8 }}
            animate={{ opacity: 1, scale: 1 }}
            className="mb-8 flex justify-center"
          >
            <div className="w-24 h-24 bg-white rounded-[2.5rem] flex items-center justify-center shadow-2xl border border-white/20 shadow-emerald-500/20">
              <Building className="w-12 h-12 text-emerald-600" strokeWidth={2.5} />
            </div>
          </motion.div>
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.2 }}
          >
            <h1 className="text-6xl font-black text-white mb-4 tracking-tighter">
              Integra<span className="text-emerald-300">Finance</span>
            </h1>
            <h2 className="text-xl text-emerald-50/80 font-medium tracking-[0.3em] uppercase">Enterprise Finance</h2>
          </motion.div>
        </div>
        {/* Subtle decorative elements */}
        <div className="absolute -bottom-24 -left-24 w-64 h-64 bg-white/10 rounded-full blur-3xl text-emerald-100" />
        <div className="absolute -top-24 -right-24 w-96 h-96 bg-white/5 rounded-full blur-3xl text-emerald-100" />
      </div>

      {/* Form Panel */}
      <div className="flex-1 flex items-center justify-center p-8 bg-white shadow-2xl z-10 lg:rounded-l-[2.5rem]">
        <div className="w-full max-w-md space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-700">
          
          {view === 'login' ? (
            <>
              <div className="text-center md:text-left">
                <h2 className="text-3xl font-bold text-slate-900 tracking-tight">Bem-vindo</h2>
                <p className="mt-2 text-slate-500">Insira suas credenciais para acessar o painel financeiro.</p>
              </div>

              <form onSubmit={handleLogin} className="mt-8 space-y-6">
                <div className="space-y-4">
                  <div className="space-y-1.5">
                    <label className="text-[0.7rem] font-bold uppercase tracking-wider text-slate-500 ml-1">
                      E-mail Corporativo
                    </label>
                    <input 
                      type="email" 
                      name="email"
                      value={formData.email}
                      onChange={handleChange}
                      placeholder="admin@pralog.com"
                      className="w-full px-4 py-3 bg-slate-50 border-0 rounded-xl ring-1 ring-slate-200 focus:ring-2 focus:ring-emerald-500 outline-none transition-all text-slate-900"
                      required
                    />
                  </div>

                  <div className="relative space-y-1.5">
                    <label className="text-[0.7rem] font-bold uppercase tracking-wider text-slate-500 ml-1">
                      Senha de Acesso
                    </label>
                    <div className="relative">
                      <input 
                        type={showPassword ? "text" : "password"} 
                        name="password"
                        value={formData.password}
                        onChange={handleChange}
                        placeholder="••••••••"
                        className="w-full px-4 py-3 bg-slate-50 border-0 rounded-xl ring-1 ring-slate-200 focus:ring-2 focus:ring-emerald-500 outline-none transition-all text-slate-900"
                        required
                      />
                      <button 
                        type="button"
                        onClick={togglePasswordVisibility}
                        className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600"
                      >
                        {showPassword ? <EyeOff size={20} /> : <Eye size={20} />}
                      </button>
                    </div>
                  </div>
                </div>

                {error && (
                  <motion.div 
                    initial={{ opacity: 0, scale: 0.95 }}
                    animate={{ opacity: 1, scale: 1 }}
                    className="p-3 bg-destructive/10 border border-destructive/20 rounded-xl text-destructive text-xs font-semibold"
                  >
                    {error}
                  </motion.div>
                )}

                <div className="flex items-center justify-between">
                  <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" />
                    <span className="text-xs text-slate-600 group-hover:text-slate-900 transition-colors">Manter conectado</span>
                  </label>
                  <button 
                    type="button" 
                    onClick={() => setView('recovery')}
                    className="text-xs font-bold text-emerald-600 hover:text-emerald-700 transition-colors"
                  >
                    Esqueceu a senha?
                  </button>
                </div>

                <button 
                  type="submit"
                  disabled={loading}
                  className="group w-full py-4 bg-emerald-600 hover:bg-emerald-700 text-white font-bold rounded-xl shadow-lg shadow-emerald-500/20 transform active:scale-[0.98] transition-all flex items-center justify-center gap-2"
                >
                  {loading ? 'Validando...' : (
                    <>
                      Acessar Sistema <ArrowRight size={18} className="group-hover:translate-x-1 transition-transform" />
                    </>
                  )}
                </button>
              </form>
            </>
          ) : (
            <>
              <div className="text-center md:text-left">
                <h2 className="text-3xl font-bold text-slate-900 tracking-tight">Recuperar Acesso</h2>
                <p className="mt-2 text-slate-500">Informe seu e-mail para receber as instruções de redefinição.</p>
              </div>

              <form className="mt-8 space-y-6">
                <div className="space-y-1.5">
                  <label className="text-[0.7rem] font-bold uppercase tracking-wider text-slate-500 ml-1">
                    E-mail de Cadastro
                  </label>
                  <input 
                    type="email" 
                    placeholder="seu.email@empresa.com"
                    className="w-full px-4 py-3 bg-slate-50 border-0 rounded-xl ring-1 ring-slate-200 focus:ring-2 focus:ring-emerald-500 outline-none transition-all text-slate-900"
                    required
                  />
                </div>

                <button 
                  type="submit"
                  className="w-full py-4 bg-emerald-600 hover:bg-emerald-700 text-white font-bold rounded-xl shadow-lg shadow-emerald-500/20 transform active:scale-[0.98] transition-all"
                >
                  Enviar Instruções
                </button>

                <div className="text-center">
                  <button 
                    type="button" 
                    onClick={() => setView('login')}
                    className="text-xs font-bold text-slate-500 hover:text-slate-800 transition-colors"
                  >
                    ← Voltar para o Login
                  </button>
                </div>
              </form>
            </>
          )}

          {/* Legal Footer */}
          <div className="pt-8 text-center text-[0.6rem] text-slate-400 space-y-2 uppercase tracking-widest font-medium opacity-60">
            <p>&copy; {new Date().getFullYear()} Integra Finance. Tecnologia para Gestão.</p>
          </div>
        </div>
      </div>
    </div>
  );
};
