import React, { useState, useEffect } from 'react';
import { db } from '../../firebase/config';
import { ref, onValue, set, update } from 'firebase/database';
import { Settings, Percent, DollarSign, Store, Globe, Bell, Save } from 'lucide-react';

export default function SettingsPlus() {
  const [settings, setSettings] = useState({
    restaurantName: 'Resto OS Premium',
    currency: 'USD',
    taxRate: 16,
    serviceCharge: 10,
    language: 'es',
    timezone: 'America/Mexico_City'
  });
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    onValue(ref(db, 'config/settings'), (snapshot) => {
      if (snapshot.exists()) setSettings(snapshot.val());
    });
  }, []);

  const handleSave = async () => {
    setSaving(true);
    await set(ref(db, 'config/settings'), settings);
    setTimeout(() => setSaving(false), 800);
  };

  return (
    <div className="animate-fade-in" style={{ padding: '0 1rem' }}>
      <header style={{ marginBottom: '2.5rem' }}>
        <h2 className="text-gradient" style={{ fontSize: '2rem', fontWeight: '800', display: 'flex', alignItems: 'center', gap: '0.75rem' }}>
          <Settings size={28} /> Configuración Global
        </h2>
        <p style={{ color: 'var(--text-muted)' }}>Ajustes generales del sistema ERP</p>
      </header>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(400px, 1fr))', gap: '2rem' }}>
        
        <div className="glass-card">
          <h3 style={sectionTitleStyle}><Store size={18} /> Información Local</h3>
          <div style={formGrid}>
            <div style={inputGroup}>
                <label style={labelStyle}>Nombre del Establecimiento</label>
                <input type="text" value={settings.restaurantName} onChange={e => setSettings({...settings, restaurantName: e.target.value})} style={inputStyle} />
            </div>
            <div style={inputGroup}>
                <label style={labelStyle}>Moneda Principal</label>
                <select value={settings.currency} onChange={e => setSettings({...settings, currency: e.target.value})} style={inputStyle}>
                    <option value="USD">Dólar ($ USD)</option>
                    <option value="MXN">Peso ($ MXN)</option>
                    <option value="EUR">Euro (€ EUR)</option>
                    <option value="COP">Peso ($ COP)</option>
                </select>
            </div>
          </div>
        </div>

        <div className="glass-card">
          <h3 style={sectionTitleStyle}><Percent size={18} /> Impuestos y Cargos</h3>
          <div style={formGrid}>
            <div style={inputGroup}>
                <label style={labelStyle}>Impuesto (IVA/VAT) %</label>
                <input type="number" value={settings.taxRate} onChange={e => setSettings({...settings, taxRate: parseFloat(e.target.value)})} style={inputStyle} />
            </div>
            <div style={inputGroup}>
                <label style={labelStyle}>Servicio Sugerido %</label>
                <input type="number" value={settings.serviceCharge} onChange={e => setSettings({...settings, serviceCharge: parseFloat(e.target.value)})} style={inputStyle} />
            </div>
          </div>
        </div>

        <div className="glass-card">
          <h3 style={sectionTitleStyle}><Globe size={18} /> Idioma y Región</h3>
          <div style={formGrid}>
            <div style={inputGroup}>
                <label style={labelStyle}>Idioma Interfaz</label>
                <select value={settings.language} onChange={e => setSettings({...settings, language: e.target.value})} style={inputStyle}>
                    <option value="es">Español</option>
                    <option value="en">English</option>
                </select>
            </div>
            <div style={inputGroup}>
                <label style={labelStyle}>Zona Horaria</label>
                <select value={settings.timezone} onChange={e => setSettings({...settings, timezone: e.target.value})} style={inputStyle}>
                    <option value="America/Mexico_City">Mexico City (CST)</option>
                    <option value="America/Bogota">Bogotá (EST)</option>
                    <option value="Europe/Madrid">Madrid (CET)</option>
                </select>
            </div>
          </div>
        </div>

        <div className="glass-card" style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', border: '1px dashed var(--primary)' }}>
            <button 
                onClick={handleSave} 
                className="btn-primary" 
                style={{ width: '200px', height: '55px', fontSize: '1.1rem' }}
                disabled={saving}
            >
                {saving ? 'Guardando...' : <span style={{ display: 'flex', alignItems: 'center', gap: '8px' }}><Save size={20}/> Guardar Cambios</span>}
            </button>
            <p style={{ marginTop: '1rem', fontSize: '0.8rem', color: 'var(--text-muted)' }}>Los cambios se aplicarán a todos los terminales.</p>
        </div>

      </div>
    </div>
  );
}

const inputStyle = { width: '100%', padding: '0.8rem', borderRadius: '8px', background: 'rgba(0,0,0,0.03)', border: '1px solid var(--border-subtle)', color: 'var(--text-main)', outline: 'none' };
const labelStyle = { display: 'block', fontSize: '0.8rem', color: 'var(--text-muted)', marginBottom: '0.5rem' };
const sectionTitleStyle = { marginBottom: '1.5rem', fontSize: '1.1rem', fontWeight: '700', display: 'flex', alignItems: 'center', gap: '0.75rem' };
const formGrid = { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1.5rem' };
const inputGroup = { display: 'flex', flexDirection: 'column' };
