import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { db } from '../firebase/config';
import { ref, onValue } from 'firebase/database';
import { Utensils, Star, Clock, MapPin, ChefHat, Instagram, Facebook, ArrowRight } from 'lucide-react';

export default function CustomerMenu() {
  const [menuItems, setMenuItems] = useState([]);
  const [categories, setCategories] = useState([]);
  const [activeCategory, setActiveCategory] = useState('Todos');
  const [menuTheme, setMenuTheme] = useState('dark'); // 'dark' or 'light'
  const navigate = useNavigate();

  useEffect(() => {
    // Escuchar el menú
    const menuRef = ref(db, 'menu');
    onValue(menuRef, (snapshot) => {
      const data = snapshot.val();
      if (data) {
        const list = Object.keys(data).map(id => ({ id, ...data[id] })).filter(item => item.active !== false);
        setMenuItems(list);
        
        const cats = [...new Set(list.map(item => item.category))];
        setCategories(['Todos', ...cats]);
      }
    });

    // Escuchar el tema configurado por el admin
    const themeRef = ref(db, 'config/menuTheme');
    onValue(themeRef, (snapshot) => {
      if (snapshot.exists()) {
        setMenuTheme(snapshot.val());
      }
    });
  }, []);

  const filteredItems = activeCategory === 'Todos' 
    ? menuItems 
    : menuItems.filter(item => item.category === activeCategory);

  const isDark = menuTheme === 'dark';
  
  const themeColors = {
    bg: isDark ? '#0a0a0a' : '#ffffff',
    text: isDark ? '#ffffff' : '#1a1a1a',
    muted: isDark ? 'rgba(255,255,255,0.6)' : 'rgba(0,0,0,0.6)',
    card: isDark ? 'rgba(255,255,255,0.03)' : 'rgba(0,0,0,0.02)',
    border: isDark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.08)',
    accent: '#FF6B6B'
  };

  return (
    <div style={{ 
      minHeight: '100vh', 
      background: themeColors.bg, 
      color: themeColors.text, 
      fontFamily: "'Outfit', sans-serif",
      transition: 'all 0.5s ease'
    }}>
      
      {/* Hero Section */}
      <section style={{ 
        height: '60vh', position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'center',
        background: `linear-gradient(rgba(0,0,0,${isDark ? 0.7 : 0.4}), rgba(0,0,0,${isDark ? 0.7 : 0.4})), url('https://images.unsplash.com/photo-1514362545857-3bc16c4c7d1b?auto=format&fit=crop&q=80&w=2070')`,
        backgroundSize: 'cover', backgroundPosition: 'center'
      }}>
        <div style={{ textAlign: 'center', padding: '0 20px' }} className="animate-slide-up">
          <h1 style={{ fontSize: '4rem', fontWeight: '900', marginBottom: '1rem', letterSpacing: '-2px' }}>Gourmet Experience</h1>
          <p style={{ fontSize: '1.25rem', opacity: 0.9, maxWidth: '600px', margin: '0 auto' }}>Descubre una fusión de sabores únicos, preparados con pasión y los ingredientes más frescos.</p>
          <div style={{ marginTop: '2rem', display: 'flex', gap: '1rem', justifyContent: 'center' }}>
            <button onClick={() => navigate('/login')} className="btn-primary" style={{ padding: '12px 30px', borderRadius: '30px' }}>
              Reservar Mesa <ArrowRight size={18} style={{ marginLeft: '10px' }} />
            </button>
          </div>
        </div>
        
        {/* Badges */}
        <div style={{ 
          position: 'absolute', bottom: '-40px', left: '50%', transform: 'translateX(-50%)',
          display: 'flex', gap: '30px', width: '100%', justifyContent: 'center', maxWidth: '800px'
        }}>
          {[
            { icon: <Star size={20} />, text: "4.9 Estrellas" },
            { icon: <Clock size={20} />, text: "30-45 min" },
            { icon: <MapPin size={20} />, text: "Centro Histórico" }
          ].map((badge, i) => (
            <div key={i} className="glass-card" style={{ 
              padding: '15px 25px', borderRadius: '15px', display: 'flex', alignItems: 'center', gap: '10px',
              background: isDark ? 'rgba(30,30,30,0.8)' : 'rgba(255,255,255,0.9)',
              color: isDark ? '#fff' : '#1a1a1a', border: `1px solid ${themeColors.border}`,
              boxShadow: '0 10px 30px rgba(0,0,0,0.1)'
            }}>
              <span style={{ color: themeColors.accent }}>{badge.icon}</span>
              <span style={{ fontWeight: '600', fontSize: '0.9rem' }}>{badge.text}</span>
            </div>
          ))}
        </div>
      </section>

      {/* Menu Section */}
      <section style={{ maxWidth: '1200px', margin: '100px auto', padding: '0 20px' }}>
        <div style={{ textAlign: 'center', marginBottom: '60px' }}>
          <h2 style={{ fontSize: '2.5rem', fontWeight: '800', marginBottom: '1rem' }}>Nuestra Carta</h2>
          <div style={{ width: '60px', height: '4px', background: themeColors.accent, margin: '0 auto', borderRadius: '2px' }}></div>
        </div>

        {/* Category Tabs */}
        <div style={{ 
          display: 'flex', justifyContent: 'center', gap: '10px', marginBottom: '50px', 
          overflowX: 'auto', padding: '10px 0', scrollbarWidth: 'none' 
        }}>
          {categories.map(cat => (
            <button
              key={cat}
              onClick={() => setActiveCategory(cat)}
              style={{
                padding: '12px 25px', borderRadius: '30px', border: 'none', cursor: 'pointer',
                background: activeCategory === cat ? themeColors.accent : themeColors.card,
                color: activeCategory === cat ? '#fff' : themeColors.text,
                fontWeight: '600', transition: 'all 0.3s ease', whiteSpace: 'nowrap',
                border: `1px solid ${activeCategory === cat ? themeColors.accent : themeColors.border}`
              }}
            >
              {cat}
            </button>
          ))}
        </div>

        {/* Menu Grid */}
        <div style={{ 
          display: 'grid', 
          gridTemplateColumns: 'repeat(auto-fill, minmax(350px, 1fr))', 
          gap: '30px' 
        }}>
          {filteredItems.map(item => (
            <div key={item.id} className="glass-card" style={{ 
              padding: '0', overflow: 'hidden', border: `1px solid ${themeColors.border}`,
              background: themeColors.card, position: 'relative', transition: 'transform 0.3s ease'
            }} onMouseEnter={e => e.currentTarget.style.transform = 'translateY(-10px)'} onMouseLeave={e => e.currentTarget.style.transform = 'translateY(0)'}>
              
              {/* Dish Image */}
              <div style={{ height: '240px', overflow: 'hidden', position: 'relative' }}>
                <img 
                  src={item.image || 'https://images.unsplash.com/photo-1546069901-ba9599a7e63c?auto=format&fit=crop&q=80&w=1760'} 
                  alt={item.name} 
                  style={{ width: '100%', height: '100%', objectFit: 'cover' }}
                />
                <div style={{ 
                  position: 'absolute', top: '15px', right: '15px', 
                  background: 'rgba(0,0,0,0.6)', color: '#fff', padding: '5px 15px', 
                  borderRadius: '20px', fontWeight: '800', fontSize: '1.1rem', backdropFilter: 'blur(5px)'
                }}>
                  ${item.price}
                </div>
              </div>

              {/* Dish Details */}
              <div style={{ padding: '25px' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '10px' }}>
                  <span style={{ fontSize: '0.75rem', textTransform: 'uppercase', color: themeColors.accent, fontWeight: '800', letterSpacing: '1px' }}>{item.category}</span>
                </div>
                <h3 style={{ fontSize: '1.4rem', fontWeight: '700', marginBottom: '10px' }}>{item.name}</h3>
                <p style={{ color: themeColors.muted, fontSize: '0.95rem', lineHeight: '1.6' }}>Preparado con ingredientes frescos de la estación y el toque secreto de nuestro chef.</p>
                <div style={{ marginTop: '20px', display: 'flex', gap: '15px' }}>
                  <span style={{ fontSize: '0.85rem', display: 'flex', alignItems: 'center', gap: '5px', color: themeColors.muted }}>
                    <ChefHat size={16} /> Especialidad
                  </span>
                  <span style={{ fontSize: '0.85rem', display: 'flex', alignItems: 'center', gap: '5px', color: themeColors.muted }}>
                    <Clock size={16} /> 20 min
                  </span>
                </div>
              </div>
            </div>
          ))}
        </div>
      </section>

      {/* Footer */}
      <footer style={{ 
        padding: '80px 20px', borderTop: `1px solid ${themeColors.border}`, 
        background: isDark ? 'rgba(0,0,0,0.5)' : 'rgba(0,0,0,0.02)', textAlign: 'center' 
      }}>
        <div style={{ maxWidth: '600px', margin: '0 auto' }}>
          <h2 style={{ fontSize: '1.8rem', fontWeight: '900', marginBottom: '1.5rem' }}>Restaurant OS</h2>
          <p style={{ color: themeColors.muted, marginBottom: '30px' }}>Siguenos en nuestras redes sociales para estar al tanto de nuestras promociones y eventos especiales.</p>
          <div style={{ display: 'flex', justifyContent: 'center', gap: '20px' }}>
            <button onClick={() => {}} style={{ background: 'none', border: 'none', color: themeColors.text, cursor: 'pointer' }}><Instagram size={24} /></button>
            <button onClick={() => {}} style={{ background: 'none', border: 'none', color: themeColors.text, cursor: 'pointer' }}><Facebook size={24} /></button>
          </div>
          <div style={{ marginTop: '50px', fontSize: '0.85rem', color: themeColors.muted }}>
            © {new Date().getFullYear()} Gourmet Experience. Todos los derechos reservados.
          </div>
        </div>
      </footer>

      {/* Admin Quick Back (Floating) */}
      <button 
        onClick={() => navigate('/login')}
        style={{
          position: 'fixed', bottom: '30px', right: '30px', width: '50px', height: '50px', borderRadius: '50%',
          background: themeColors.accent, color: '#fff', border: 'none', cursor: 'pointer',
          boxShadow: '0 10px 20px rgba(0,0,0,0.2)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 100
        }}
        title="Admin Login"
      >
        <Utensils size={24} />
      </button>
    </div>
  );
}
