import React, { useState, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { businessSettingService, productSheetService, serviceSheetService, campaignService } from '../services/api';
import useFormatters from '../hooks/useFormatters';
import BusinessSettingsTab from '../components/business/BusinessSettingsTab';
import ProductSheetsTab from '../components/business/ProductSheetsTab';
import ServiceSheetsTab from '../components/business/ServiceSheetsTab';
import PriceCalculatorTab from '../components/business/PriceCalculatorTab';
import CampaignsTab from '../components/business/CampaignsTab';

const Business = () => {
  const { t } = useTranslation();
  const { currency } = useFormatters();
  
  const [activeTab, setActiveTab] = useState('settings');
  const [settings, setSettings] = useState([]);
  const [sheets, setSheets] = useState([]);
  const [serviceSheets, setServiceSheets] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  // Carregar dados
  const loadData = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const [settingsData, sheetsData, serviceSheetsData] = await Promise.all([
        businessSettingService.getAll(),
        productSheetService.getAll(),
        serviceSheetService.getAll(),
      ]);
      setSettings(settingsData);
      setSheets(sheetsData);
      setServiceSheets(serviceSheetsData);
    } catch (err) {
      console.error('Error loading business data:', err);
      setError(err.response?.data?.message || t('common.error'));
    } finally {
      setLoading(false);
    }
  }, [t]);

  useEffect(() => {
    loadData();
  }, [loadData]);

  // Handlers para Settings
  const handleSettingCreated = (newSetting) => {
    setSettings(prev => [...prev, newSetting]);
  };

  const handleSettingUpdated = (updatedSetting) => {
    setSettings(prev => prev.map(s => s.id === updatedSetting.id ? updatedSetting : s));
  };

  const handleSettingDeleted = (id) => {
    setSettings(prev => prev.filter(s => s.id !== id));
  };

  // Handlers para Sheets (Products)
  const handleSheetCreated = (newSheet) => {
    setSheets(prev => [...prev, newSheet]);
  };

  const handleSheetUpdated = (updatedSheet) => {
    setSheets(prev => prev.map(s => s.id === updatedSheet.id ? updatedSheet : s));
  };

  const handleSheetDeleted = (id) => {
    setSheets(prev => prev.filter(s => s.id !== id));
  };

  // Handlers para Service Sheets
  const handleServiceSheetCreated = (newSheet) => {
    setServiceSheets(prev => [...prev, newSheet]);
  };

  const handleServiceSheetUpdated = (updatedSheet) => {
    setServiceSheets(prev => prev.map(s => s.id === updatedSheet.id ? updatedSheet : s));
  };

  const handleServiceSheetDeleted = (id) => {
    setServiceSheets(prev => prev.filter(s => s.id !== id));
  };

  // Filter settings by business type for products and services
  const productSettings = settings.filter(s => s.business_type === 'products' || s.business_type === 'both' || !s.business_type);
  const serviceSettings = settings.filter(s => s.business_type === 'services' || s.business_type === 'both');

  const tabs = [
    { id: 'settings', label: t('business.tabs.settings'), icon: 'bi-gear' },
    { id: 'products', label: t('business.tabs.products'), icon: 'bi-box-seam' },
    { id: 'services', label: t('business.tabs.services'), icon: 'bi-person-workspace' },
    { id: 'campaigns', label: t('business.tabs.campaigns'), icon: 'bi-megaphone' },
    { id: 'calculator', label: t('business.tabs.calculator'), icon: 'bi-calculator' },
  ];

  return (
    <div className="container-fluid py-4">
      {/* Header */}
      <div className="d-flex justify-content-between align-items-center mb-4">
        <div>
          <h1 className="h3 mb-1 text-white">
            <i className="bi bi-briefcase me-2"></i>
            {t('business.title')}
          </h1>
          <p className="text-slate-400 mb-0 small">
            {t('business.subtitle')}
          </p>
        </div>
        <button 
          className="btn btn-sm btn-outline-secondary"
          onClick={loadData}
          disabled={loading}
        >
          <i className={`bi bi-arrow-clockwise ${loading ? 'spin' : ''}`}></i>
        </button>
      </div>

      {/* Error Alert */}
      {error && (
        <div className="alert alert-danger d-flex align-items-center mb-4" role="alert">
          <i className="bi bi-exclamation-triangle me-2"></i>
          {error}
          <button type="button" className="btn-close ms-auto" onClick={() => setError(null)}></button>
        </div>
      )}

      {/* Tabs */}
      <ul className="nav nav-tabs mb-4" style={{ borderColor: 'rgba(255,255,255,0.1)' }}>
        {tabs.map(tab => (
          <li key={tab.id} className="nav-item">
            <button
              className={`nav-link ${activeTab === tab.id ? 'active' : ''}`}
              onClick={() => setActiveTab(tab.id)}
              style={{
                background: activeTab === tab.id ? 'rgba(59, 130, 246, 0.2)' : 'transparent',
                color: activeTab === tab.id ? '#3b82f6' : '#94a3b8',
                border: 'none',
                borderBottom: activeTab === tab.id ? '2px solid #3b82f6' : '2px solid transparent',
              }}
            >
              <i className={`bi ${tab.icon} me-2`}></i>
              {tab.label}
            </button>
          </li>
        ))}
      </ul>

      {/* Tab Content */}
      {loading ? (
        <div className="text-center py-5">
          <div className="spinner-border text-primary" role="status">
            <span className="visually-hidden">Loading...</span>
          </div>
        </div>
      ) : (
        <>
          {activeTab === 'settings' && (
            <BusinessSettingsTab
              settings={settings}
              onCreated={handleSettingCreated}
              onUpdated={handleSettingUpdated}
              onDeleted={handleSettingDeleted}
            />
          )}
          
          {activeTab === 'products' && (
            <ProductSheetsTab
              sheets={sheets}
              settings={productSettings}
              onCreated={handleSheetCreated}
              onUpdated={handleSheetUpdated}
              onDeleted={handleSheetDeleted}
            />
          )}

          {activeTab === 'services' && (
            <ServiceSheetsTab
              sheets={serviceSheets}
              settings={serviceSettings}
              onCreated={handleServiceSheetCreated}
              onUpdated={handleServiceSheetUpdated}
              onDeleted={handleServiceSheetDeleted}
            />
          )}
          
          {activeTab === 'campaigns' && (
            <CampaignsTab
              sheets={sheets}
            />
          )}
          
          {activeTab === 'calculator' && (
            <PriceCalculatorTab
              settings={settings}
              sheets={sheets}
            />
          )}
        </>
      )}
    </div>
  );
};

export default Business;
