import React, { useState, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import { 
  Lock, 
  AlertCircle, 
  Eye, 
  EyeOff,
  User,
  Zap,
  ArrowRight,
  Loader2
} from 'lucide-react';
import logo from '@/assets/Img/Util/iT_Guys/logo_2.png';
import { useDocumentMetadata } from '@/hooks/useDocumentMetadata';
import { useWorkspaceAuth } from '../hooks/useWorkspaceAuth';

const WORKSPACE_ENV_NAME = 'Workspace';
const WORKSPACE_BRAND_NAME = 'iTGUYS';

export const LoginView = () => {
  useDocumentMetadata(`Login | ${WORKSPACE_ENV_NAME} | ${WORKSPACE_BRAND_NAME}`, 'workspace');
  const navigate = useNavigate();
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  
  const {
    step,
    isLoading,
    error,
    otp,
    setOtp,
    handleFirstLogin,
    handleSecondLogin,
    reset
  } = useWorkspaceAuth();

  const otpRefs = useRef([]);

  const handleLogin = async (e) => {
    e.preventDefault();
    await handleFirstLogin(username, password);
  };

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

    // Move para o próximo campo se houver valor
    if (value && index < 5) {
      otpRefs.current[index + 1]?.focus();
    }

    // Auto-submit quando todos os campos estiverem preenchidos (baseado na lógica antiga)
    if (newOtp.every(digit => digit !== '')) {
      const code = newOtp.join('');
      // Pequeno delay para melhorar UX
      setTimeout(() => handleSecondLogin(code), 300);
    }
  };

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

  const handlePaste = (e) => {
    e.preventDefault();
    const pastedData = e.clipboardData.getData('text').slice(0, 6).split('');
    if (pastedData.length > 0) {
      const newOtp = [...otp];
      pastedData.forEach((value, i) => {
        if (i < 6 && /^\d$/.test(value)) {
          newOtp[i] = value;
        }
      });
      setOtp(newOtp);
      
      const nextIndex = Math.min(pastedData.length - 1, 5);
      otpRefs.current[nextIndex]?.focus();
      
      // Auto-submit se todos os campos estiverem preenchidos
      if (newOtp.filter(d => d !== '').length === 6) {
        const code = newOtp.join('');
        setTimeout(() => handleSecondLogin(code), 300);
      }
    }
  };

  const handleFinalize = async () => {
    const code = otp.join('');
    if (code.length === 6) {
      await handleSecondLogin(code);
    }
  };

  return (
    <div className="workspace-theme relative w-full h-screen bg-[#050505] font-lato text-white overflow-y-auto overflow-x-hidden selection:bg-[#26b1c7]/30">
      
      {/* Background Animated Gradients - Fixed */}
      <div className="fixed inset-0 z-0 pointer-events-none">
           <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-[#26b1c7]/10 blur-[120px] rounded-full" />
           <div className="absolute bottom-[-10%] left-[-10%] w-[50%] h-[50%] bg-[#003153]/20 blur-[120px] rounded-full" />
      </div>

      {/* Main Content Scroll Wrapper */}
      <div className="relative z-10 min-h-screen flex flex-col p-4 md:p-8">
        <div className="w-full max-w-6xl m-auto flex flex-col md:flex-row shadow-[0_0_80px_rgba(0,0,0,0.5)] rounded-[40px] overflow-hidden border border-white/5 bg-[#0a0a0a]/80 backdrop-blur-3xl min-h-[600px]">
        
        {/* Left Panel - Branding */}
        <div className="hidden md:flex flex-1 relative flex-col items-center justify-center p-16 border-r border-white/5">
          <div className="absolute inset-0 bg-gradient-to-br from-[#22bb6c]/5 to-transparent pointer-events-none" />
          
          <motion.div 
            initial={{ opacity: 0, y: 30 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.8 }}
            className="text-center"
          >
             <img 
               src={logo} 
               alt="iTGUYS" 
               className="w-full max-w-[280px] mb-12 drop-shadow-[0_0_50px_rgba(38,177,199,0.4)] mx-auto"
             />
             
             <div className="space-y-4">
               <h2 className="text-4xl font-bold tracking-tighter text-white">
                 WORKSPACE <span className="text-[#26b1c7]">EXPERIENCE</span>
               </h2>
             </div>
          </motion.div>
        </div>

        {/* Right Panel - Form Area */}
        <div className="flex-1 flex items-center justify-center p-8 md:p-16 bg-[#0c0c0c]/50 relative">
          <AnimatePresence mode="wait">
            {step === 1 ? (
              <motion.div 
                key="login-step"
                initial={{ opacity: 0, scale: 0.95 }}
                animate={{ opacity: 1, scale: 1 }}
                exit={{ opacity: 0, scale: 1.05 }}
                className="w-full max-w-md space-y-12"
              >
                <div className="space-y-4">
                   <div className="md:hidden flex justify-center mb-8">
                      <img src={logo} alt="iTGUYS" className="h-12 w-auto" />
                   </div>
                   <h1 className="text-5xl font-bold tracking-tighter text-white leading-none">Bem-vindo.</h1>
                   <p className="text-zinc-500 text-sm font-medium">Autentique-se para gerenciar sua plataforma de ativos.</p>
                </div>

                <form onSubmit={handleLogin} className="space-y-6">
                  <div className="space-y-4">
                    <div className="group relative">
                       <label className="text-[10px] font-bold uppercase tracking-widest text-zinc-600 mb-2 block ml-1 group-focus-within:text-[#26b1c7] transition-colors">Usuário</label>
                       <div className="relative">
                          <User size={18} className="absolute left-4 top-1/2 -translate-y-1/2 text-zinc-700 group-focus-within:text-[white] transition-colors" />
                          <input 
                            type="text" 
                            value={username}
                            onChange={(e) => setUsername(e.target.value)}
                            maxLength={250}
                            className="w-full bg-white/[0.04] border border-white/10 rounded-2xl py-4 flex pl-12 pr-4 text-white hover:text-white focus:text-white text-base font-bold outline-none focus:bg-white/[0.08] focus:border-white/20 transition-all placeholder:text-zinc-700"
                            placeholder="user@dominio.com.br"
                          />
                       </div>
                    </div>

                    <div className="group relative">
                       <label className="text-[10px] font-bold uppercase tracking-widest text-zinc-600 mb-2 block ml-1 group-focus-within:text-[#22bb6c] transition-colors">Chave de Segurança</label>
                       <div className="relative">
                          <Lock size={18} className="absolute left-4 top-1/2 -translate-y-1/2 text-zinc-700 group-focus-within:text-[#26b1c7] transition-colors" />
                          <input 
                            type={showPassword ? 'text' : 'password'} 
                            value={password}
                            onChange={(e) => setPassword(e.target.value)}
                            maxLength={250}
                            placeholder="digite sua senha"
                            autoFocus
                            className="w-full bg-white/[0.04] border border-white/10 rounded-2xl py-4 pl-12 pr-14 text-white font-bold focus:ring-2 focus:ring-[#26b1c7]/30 focus:border-[#26b1c7]/50 focus:bg-white/[0.08] transition-all outline-none placeholder:text-zinc-800"
                          />
                          <button 
                            type="button"
                            onClick={() => setShowPassword(!showPassword)}
                            className="absolute right-4 top-1/2 -translate-y-1/2 text-zinc-600 hover:text-white transition-colors"
                          >
                            {showPassword ? <EyeOff size={20} /> : <Eye size={20} />}
                          </button>
                       </div>
                    </div>
                  </div>

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

                  <button
                    type="submit"
                    disabled={isLoading || !password || !username}
                    className="w-full py-4.5 bg-[#26b1c7] hover:bg-[#26b1c7]/80 disabled:bg-zinc-900 disabled:text-zinc-700 text-[#050505] rounded-2xl font-bold uppercase tracking-widest text-sm transition-all shadow-2xl shadow-[#26b1c7]/20 flex items-center justify-center gap-3 hover:scale-[1.02] active:scale-[0.98]"
                  >
                    {isLoading ? (
                      <div className="w-5 h-5 border-2 border-black/20 border-t-black rounded-full animate-spin" />
                    ) : (
                      <>Entrar no Workspace <ArrowRight size={18} /></>
                    )}
                  </button>
                  
                  <div className="text-center pt-2">
                     <p className="text-xs text-zinc-500 font-medium">
                        Não tem conta? <button type="button" onClick={() => navigate('/plataforma/cadastro-motorista')} className="text-[#26b1c7] font-bold hover:underline transition-all">Junte-se a nós</button>
                     </p>
                  </div>
                </form>


              </motion.div>
            ) : (
              <motion.div 
                key="otp-step"
                initial={{ opacity: 0, scale: 0.95 }}
                animate={{ opacity: 1, scale: 1 }}
                className="w-full max-w-md space-y-12 text-center"
              >
                <div className="space-y-4">
                  <div className="flex justify-center mb-8">
                      <img src={logo} alt="iTGUYS" className="h-16 w-auto drop-shadow-[0_0_20px_rgba(38,177,199,0.3)]" />
                  </div>
                  <h2 className="text-4xl font-bold tracking-tighter text-white">Digite o Código</h2>
                  <p className="text-zinc-500 text-sm">Código enviado ao seu e-mail. Digite os 6 dígitos para continuar.</p>
                </div>

                <div className="flex justify-between gap-3">
                  {otp.map((digit, i) => (
                    <input
                      key={i}
                      ref={el => otpRefs.current[i] = el}
                      type="text"
                      inputMode="numeric"
                      maxLength={1}
                      value={digit}
                      onChange={(e) => handleOtpChange(i, e.target.value)}
                      onKeyDown={(e) => handleKeyDown(i, e)}
                      autoFocus={i === 0}
                      onPaste={handlePaste}
                      className="w-full h-20 bg-white/[0.04] border border-white/10 rounded-2xl text-white text-3xl font-bold text-center focus:ring-4 focus:ring-[#26b1c7]/30 focus:border-[#26b1c7] outline-none transition-all"
                    />
                  ))}
                </div>

                <button
                  onClick={handleFinalize}
                  disabled={isLoading || otp.join('').length !== 6}
                  className="w-full py-4 bg-[#26b1c7] hover:bg-[#26b1c7]/80 disabled:bg-zinc-900 disabled:text-zinc-700 text-[#050505] rounded-2xl font-bold uppercase tracking-widest text-sm transition-all shadow-2xl shadow-[#26b1c7]/20 disabled:cursor-not-allowed flex items-center justify-center gap-3 hover:scale-[1.02] active:scale-[0.98]"
                >
                  {isLoading ? (
                    <Loader2 className="w-5 h-5 animate-spin" />
                  ) : (
                    'Enviar'
                  )}
                </button>
                
                {error && (
                  <motion.div 
                    initial={{ opacity: 0, x: -10 }}
                    animate={{ opacity: 1, x: 0 }}
                    className="p-4 bg-rose-400/10 border border-rose-400/20 rounded-2xl flex items-center gap-3 text-rose-500 text-xs font-bold"
                  >
                    <AlertCircle size={16} /> {error}
                  </motion.div>
                )}
                
                <p className="text-[10px] text-zinc-600 font-bold uppercase tracking-widest">
                  Não recebeu? <button onClick={reset} className="text-[#26b1c7] hover:underline">Voltar ao Login</button>
                </p>
              </motion.div>
            )}
          </AnimatePresence>
        </div>
      </div>
      </div>
    </div>
  );
};
