import React, { useState } from 'react';
import { useAuth } from '../context/AuthContext';
import { useNavigate } from 'react-router-dom';
import { User, ShieldCheck, Utensils, ArrowRightCircle } from 'lucide-react';

export default function Login() {
  const [email, setEmail] = useState('admin@rest-os.com');
  const [password, setPassword] = useState('admin-password123');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [loginMode, setLoginMode] = useState('admin'); // 'admin' or 'mesero'

  const { login, currentUser } = useAuth();
  const navigate = useNavigate();

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError('');
    
    // Si ya hay una sesión activa, simplemente navegar
    if (currentUser && currentUser.email === email) {
      const targetRole = email.includes('admin') ? 'admin' : 'mesero';
      navigate(targetRole === 'admin' ? '/admin' : '/pos');
      setLoading(false);
      return;
    }

    try {
      await login(email, password);
      // navigation is handled by RootRedirect in App.jsx
    } catch (err) {
      setError('Credenciales inválidas. Por favor intente de nuevo.');
    } finally {
      setLoading(false);
    }
  };

  const setDemo = (role) => {
    if (role === 'admin') {
      setEmail('admin@rest-os.com');
      setPassword('admin-password123');
      setLoginMode('admin');
    } else {
      setEmail('mesero@rest-os.com');
      setPassword('mesero-password123');
      setLoginMode('mesero');
    }
  };

  return (
    <div className="app-container" style={{
      background: 'radial-gradient(circle at top right, #1a1a1a, #0a0a0a)',
      justifyContent: 'center', alignItems: 'center', minHeight: '100vh', padding: '20px'
    }}>
      {/* Icono de Ver Menú Público */}
      <button
        onClick={() => navigate('/menu')}
        className="glass-card animate-fade-in"
        style={{
          position: 'absolute', top: '30px', right: '30px', padding: '12px 24px',
          display: 'flex', alignItems: 'center', gap: '10px', color: 'var(--primary)',
          cursor: 'pointer', border: '1px solid rgba(255,107,107,0.3)',
          zIndex: 10
        }}
      >
        <Utensils size={20} />
        <span style={{ fontWeight: '600' }}>Ver Carta Digital</span>
        <ArrowRightCircle size={18} />
      </button>

      <div className="glass-panel animate-slide-up" style={{
        maxWidth: '900px', width: '100%', padding: '0', display: 'flex',
        overflow: 'hidden', boxShadow: '0 25px 50px -12px rgba(0, 0, 0, 0.5)'
      }}>

        {/* Lado Izquierdo: Selección de Rol */}
        <div style={{
          width: '35%', background: 'rgba(255,255,255,0.03)',
          borderRight: '1px solid var(--border-subtle)', padding: '40px 30px',
          display: 'flex', flexDirection: 'column', gap: '20px'
        }}>
          <h2 style={{ fontSize: '1.4rem', fontWeight: '800', marginBottom: '10px' }}>Bienvenido</h2>
          <p style={{ color: 'var(--text-muted)', fontSize: '0.9rem', marginBottom: '20px' }}>Seleccione su rol para ingresar al sistema</p>

          <button
            onClick={() => { setDemo('admin'); setError(''); }}
            style={{
              padding: '20px', borderRadius: 'var(--radius-sm)', border: '1px solid',
              borderColor: loginMode === 'admin' ? 'var(--primary)' : 'transparent',
              background: loginMode === 'admin' ? 'rgba(255,107,107,0.1)' : 'rgba(255,255,255,0.02)',
              display: 'flex', alignItems: 'center', gap: '15px', textAlign: 'left',
              transition: 'all 0.3s ease', cursor: 'pointer'
            }}
          >
            <div style={{
              padding: '10px', borderRadius: '10px',
              background: loginMode === 'admin' ? 'var(--primary)' : 'rgba(255,255,255,0.05)',
              color: loginMode === 'admin' ? '#fff' : 'var(--text-muted)'
            }}>
              <ShieldCheck size={24} />
            </div>
            <div>
              <div style={{ fontWeight: '700', color: loginMode === 'admin' ? 'var(--text-main)' : 'var(--text-muted)' }}>Administrador</div>
              <div style={{ fontSize: '0.75rem', color: 'var(--text-muted)' }}>Gestión y Reportes</div>
            </div>
          </button>

          <button
            onClick={() => { setDemo('mesero'); setError(''); }}
            style={{
              padding: '20px', borderRadius: 'var(--radius-sm)', border: '1px solid',
              borderColor: loginMode === 'mesero' ? 'var(--primary)' : 'transparent',
              background: loginMode === 'mesero' ? 'rgba(255,107,107,0.1)' : 'rgba(255,255,255,0.02)',
              display: 'flex', alignItems: 'center', gap: '15px', textAlign: 'left',
              transition: 'all 0.3s ease', cursor: 'pointer'
            }}
          >
            <div style={{
              padding: '10px', borderRadius: '10px',
              background: loginMode === 'mesero' ? 'var(--primary)' : 'rgba(255,255,255,0.05)',
              color: loginMode === 'mesero' ? '#fff' : 'var(--text-muted)'
            }}>
              <User size={24} />
            </div>
            <div>
              <div style={{ fontWeight: '700', color: loginMode === 'mesero' ? 'var(--text-main)' : 'var(--text-muted)' }}>Mesero / POS</div>
              <div style={{ fontSize: '0.75rem', color: 'var(--text-muted)' }}>Pedidos y Control</div>
            </div>
          </button>
        </div>

        {/* Lado Derecho: Formulario de Login */}
        <div style={{ flex: 1, padding: '60px' }}>
          <div style={{ marginBottom: '40px' }}>
            <h1 className="text-gradient" style={{ fontSize: '2.5rem', fontWeight: '900', marginBottom: '10px' }}>
              {loginMode === 'admin' ? 'Dashboard Admin' : 'Terminal Meseros'}
            </h1>
            <p style={{ color: 'var(--text-muted)' }}>Ingrese sus credenciales para continuar</p>
          </div>

          {error && (
            <div className="glass-card" style={{ padding: '10px 20px', background: 'rgba(255,90,95,0.1)', border: '1px solid var(--primary)', borderRadius: 'var(--radius-sm)', marginBottom: '20px', color: 'var(--primary)', fontSize: '0.9rem' }}>
              {error}
            </div>
          )}

          <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: '1.5rem' }}>
            <div>
              <label style={{ display: 'block', marginBottom: '8px', fontSize: '0.9rem', color: 'var(--text-muted)' }}>Correo Electrónico</label>
              <input
                type="email" required value={email} onChange={(e) => setEmail(e.target.value)}
                style={{ width: '100%', padding: '14px', borderRadius: '10px', background: 'rgba(255,255,255,0.05)', border: '1px solid var(--border-subtle)', color: '#fff' }}
              />
            </div>
            <div>
              <label style={{ display: 'block', marginBottom: '8px', fontSize: '0.9rem', color: 'var(--text-muted)' }}>Contraseña</label>
              <input
                type="password" required value={password} onChange={(e) => setPassword(e.target.value)}
                style={{ width: '100%', padding: '14px', borderRadius: '10px', background: 'rgba(255,255,255,0.05)', border: '1px solid var(--border-subtle)', color: '#fff' }}
              />
            </div>
            <button type="submit" className="btn-primary" style={{ height: '55px', fontSize: '1.1rem', marginTop: '10px' }} disabled={loading}>
              {loading ? 'Validando...' : 'Iniciar Sesión'}
            </button>
          </form>

          {/* Botón Demo rápido */}
          <div style={{ marginTop: '30px', textAlign: 'center' }}>
            <button
              onClick={() => setDemo(loginMode)}
              style={{ background: 'none', border: 'none', color: 'var(--text-muted)', cursor: 'pointer', textDecoration: 'underline', fontSize: '0.85rem' }}
            >
              Usar cuenta de prueba para {loginMode === 'admin' ? 'Admin' : 'Mesero'}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
