import React, { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { useNavigate } from 'react-router-dom';
import { 
  Lock, 
  ChevronRight, 
  ShieldCheck, 
  AlertCircle, 
  Eye, 
  EyeOff,
  User,
  Zap
} from 'lucide-react';
import { useAuthContext } from '@/components/shared/AuthProvider';
import logo from '@/assets/Img/Util/iT_Guys/logo1.png';

/**
 * LoginView - Versão Premium para o Workspace iTGUYS
 * Inspirado no design "Reproduced" com split-screen e alta fidelidade visual.
 */
export const LoginView = () => {
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [error, setError] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [step, setStep] = useState(1); // 1: Login, 2: OTP
  const navigate = useNavigate();

  const [otp, setOtp] = useState(['', '', '', '', '', '']);
  const otpRefs = React.useRef([]);

  const handleLogin = async (e) => {
    e.preventDefault();
    setIsLoading(true);
    setError('');

    // Senhas de teste permitidas
    const allowedPasswords = ['itguys@2026', 'teste@finance', 'admin'];

    setTimeout(() => {
      if (allowedPasswords.includes(password)) {
        sessionStorage.setItem('workspace_access', 'granted');
        setStep(2); 
        setIsLoading(false);
      } else {
        setError('Chave de acesso inválida ou expirada.');
        setIsLoading(false);
      }
    }, 800);
  };

  const handleOtpChange = (index, value) => {
    if (!/^\d*$/.test(value)) return;
    
    const newOtp = [...otp];
    newOtp[index] = value.slice(-1);
    setOtp(newOtp);

    // Auto focus next
    if (value && index < 5) {
      otpRefs.current[index + 1]?.focus();
    }

    // Auto submit if full
    if (newOtp.every(digit => digit !== '')) {
      setTimeout(() => handleFinalize(), 600);
    }
  };

  const handleKeyDown = (index, e) => {
    if (e.key === 'Backspace' && !otp[index] && index > 0) {
      otpRefs.current[index - 1]?.focus();
    }
  };

  const handleFinalize = () => {
    navigate('/plataforma/workspace');
    window.location.reload();
  };

  return (
    <div className="workspace-theme flex h-screen w-full bg-[var(--workspace-sec-5-dark)] overflow-hidden font-lato select-none text-white">
      {/* Left Panel - Brand & Identity */}
      <div className="hidden lg:flex flex-1 relative items-center justify-center overflow-hidden border-r border-white/5 bg-[var(--workspace-sec-5-dark)]">
        {/* Background Effects */}
        <div className="absolute inset-0 z-0">
           <div className="absolute inset-0 bg-gradient-to-br from-[#003153]/40 to-transparent mix-blend-overlay" />
           <div className="absolute top-[-10%] right-[-10%] w-[50%] h-[50%] bg-[#22bb6c]/10 blur-[120px] rounded-full" />
           <div className="absolute bottom-[-10%] left-[-10%] w-[50%] h-[50%] bg-[#003153]/20 blur-[120px] rounded-full" />
        </div>
        
        {/* Logo Area */}
        <motion.div 
          initial={{ opacity: 0, scale: 0.9, y: 20 }}
          animate={{ opacity: 1, scale: 1, y: 0 }}
          transition={{ duration: 1 }}
          className="relative z-10 flex flex-col items-center text-center px-12"
        >
          <img 
            src={logo} 
            alt="iTGUYS Logo" 
            className="w-full max-w-[400px] mb-8 drop-shadow-[0_0_25px_rgba(34,187,108,0.2)]"
          />
          <div className="h-[2px] w-24 bg-gradient-to-r from-transparent via-[#22bb6c] to-transparent mb-6" />
          <h2 className="text-3xl font-black italic tracking-tighter text-white/90">
             WORKSPACE <span className="text-[#22bb6c]">EXPERIENCE</span>
          </h2>
          <p className="mt-4 text-white/40 max-w-sm text-sm font-medium uppercase tracking-[0.3em]">
             Gestão Estratégica & Inteligência Financeira
          </p>
        </motion.div>

        {/* Floating Badges */}
        <div className="absolute bottom-10 left-10 flex gap-4 z-10 opacity-30">
           <div className="flex items-center gap-2 px-3 py-1.5 rounded-full border border-white/10 bg-white/5 text-[10px] font-bold uppercase tracking-widest text-[#22bb6c]">
              <ShieldCheck size={12} /> Encrypted
           </div>
           <div className="flex items-center gap-2 px-3 py-1.5 rounded-full border border-white/10 bg-white/5 text-[10px] font-bold uppercase tracking-widest text-slate-400">
              Versão 2026.1
           </div>
        </div>
      </div>

      {/* Right Panel - Interactive Form */}
      <div className="flex-[0.8] flex items-center justify-center p-8 bg-[var(--workspace-sec-5-dark)] relative overflow-hidden">
        {/* Decorative Grid */}
        <div className="absolute inset-0 opacity-[0.02] pointer-events-none" 
             style={{ backgroundImage: 'radial-gradient(#fff 1px, transparent 0)', backgroundSize: '40px 40px' }} 
        />

        <AnimatePresence mode="wait">
          {step === 1 ? (
            <motion.div 
              key="step1"
              initial={{ opacity: 0, x: 50 }}
              animate={{ opacity: 1, x: 0 }}
              exit={{ opacity: 0, x: -50 }}
              className="w-full max-w-[420px] space-y-8 relative z-10"
            >
              <div className="space-y-2">
                <div className="inline-flex items-center gap-2 text-[#22bb6c] font-black text-xs uppercase tracking-[0.3em] mb-2 bg-[#22bb6c]/10 px-3 py-1 rounded-full">
                   <Lock size={12} /> Restricted Access
                </div>
                <h1 className="text-4xl font-extrabold tracking-tighter text-white">Identifique-se</h1>
                <p className="text-white/40 text-sm font-medium">Insira sua chave mestra para acessar o sistema.</p>
              </div>

              <form onSubmit={handleLogin} className="space-y-6">
                <div className="space-y-4">
                  {/* User field (Readonly for Context) */}
                  <div className="relative group">
                    <User className="absolute left-4 top-1/2 -translate-y-1/2 text-white/20 group-focus-within:text-[#22bb6c] transition-colors" size={20} />
                    <input 
                      type="text" 
                      value="PLATAFORMA SISTEMAS"
                      disabled
                      className="w-full bg-white/[0.03] border border-white/10 rounded-2xl py-4 pl-12 pr-4 text-white/40 text-sm font-bold opacity-60 cursor-not-allowed uppercase tracking-wider"
                    />
                  </div>

                  {/* Password Field */}
                  <div className="relative group">
                    <Lock className="absolute left-4 top-1/2 -translate-y-1/2 text-white/20 group-focus-within:text-[#22bb6c] transition-colors" size={20} />
                    <input 
                      type={showPassword ? 'text' : 'password'} 
                      value={password}
                      onChange={(e) => setPassword(e.target.value)}
                      placeholder="Chave de Acesso"
                      autoFocus
                      className="w-full bg-white/[0.05] border border-white/10 rounded-2xl py-4 pl-12 pr-12 text-white text-sm font-bold focus:ring-2 focus:ring-[#22bb6c]/50 focus:border-[#22bb6c] focus:bg-white/[0.08] outline-none transition-all placeholder:text-white/20 tracking-[0.2em]"
                    />
                    <button 
                      type="button"
                      onClick={() => setShowPassword(!showPassword)}
                      className="absolute right-4 top-1/2 -translate-y-1/2 text-white/20 hover:text-white transition-colors"
                    >
                      {showPassword ? <EyeOff size={18} /> : <Eye size={18} />}
                    </button>
                  </div>
                </div>

                {error && (
                  <motion.div 
                    initial={{ opacity: 0, y: -10 }}
                    animate={{ opacity: 1, y: 0 }}
                    className="flex items-center gap-2 p-4 bg-red-500/10 border border-red-500/20 rounded-xl text-red-500 text-xs font-bold"
                  >
                    <AlertCircle size={14} /> {error}
                  </motion.div>
                )}

                <button
                  type="submit"
                  disabled={isLoading || !password}
                  className="w-full relative overflow-hidden group bg-gradient-to-r from-[#22bb6c] to-[#22c0a3] disabled:from-zinc-800 disabled:to-zinc-900 text-[#050505] rounded-2xl py-4 font-black text-sm uppercase tracking-[0.2em] shadow-xl shadow-[#22bb6c]/20 hover:scale-[1.02] active:scale-[0.98] transition-all"
                >
                  {isLoading ? (
                    <div className="flex items-center justify-center gap-3">
                      <div className="w-4 h-4 border-2 border-[#050505]/30 border-t-[#050505] rounded-full animate-spin" />
                      <span>Validando...</span>
                    </div>
                  ) : (
                    <div className="flex items-center justify-center gap-2">
                       Acessar Ambiente <ChevronRight size={18} className="group-hover:translate-x-1 transition-transform" />
                    </div>
                  )}
                </button>
              </form>

              <div className="pt-8 flex items-center justify-center gap-8 border-t border-white/5 opacity-40">
                 <img src={logo} alt="Logo" className="h-4 grayscale hover:grayscale-0 transition-all cursor-crosshair" />
                 <span className="text-[10px] text-zinc-500 uppercase tracking-widest font-bold">iTGUYS Core Systems v4</span>
              </div>
            </motion.div>
          ) : (
            /* Step 2 - Digite o Código (Reference Image 1 style) */
            <motion.div 
              key="step2"
              initial={{ opacity: 0, scale: 0.9 }}
              animate={{ opacity: 1, scale: 1 }}
              className="bg-[#002137] p-16 rounded-[60px] shadow-2xl flex flex-col items-center text-center max-w-[600px] w-full border border-white/5"
            >
               <h2 className="text-5xl font-extrabold text-white tracking-tight mb-12">Digite o Código</h2>
               
               <div className="flex gap-4 mb-12">
                  {otp.map((digit, i) => (
                    <input
                      key={i}
                      ref={el => otpRefs.current[i] = el}
                      type="text"
                      maxLength={1}
                      value={digit}
                      onChange={(e) => handleOtpChange(i, e.target.value)}
                      onKeyDown={(e) => handleKeyDown(i, e)}
                      autoFocus={i === 0}
                      className="w-16 h-20 bg-white rounded-[20px] text-[#002137] text-4xl font-black text-center outline-none focus:ring-4 focus:ring-[#22bb6c]/50 transition-all shadow-lg"
                    />
                  ))}
               </div>

               <button
                 onClick={handleFinalize}
                 className="px-12 py-4 bg-white text-[#002137] rounded-2xl font-black text-xl hover:bg-[#22bb6c] hover:text-white transition-all shadow-xl hover:scale-105 active:scale-95"
               >
                 Enviar
               </button>
            </motion.div>
          )}
        </AnimatePresence>
      </div>

      {/* Decorative Blur and Logo Overlay for Mobile (if any) */}
      <div className="absolute top-0 left-0 w-full h-full pointer-events-none overflow-hidden z--1 opacity-20">
         <div className="absolute top-[-20%] left-[-10%] w-[60%] h-[60%] bg-[#003153] blur-[150px] rounded-full" />
      </div>
    </div>
  );
};
