import React, { useState, useEffect } from 'react';
import { ThemeProvider } from '@mui/material/styles';
import theme from './theme/theme.js';
import Layout from './components/Layout.js';
import Dashboard from './tabs/Dashboard.js';
import GlobalSettings from './tabs/GlobalSettings.js';
import RoleSettings from './tabs/RoleSettings.js';
import CountrySettings from './tabs/CountrySettings.js';
import ProTab from './tabs/ProTab.js';

const App = () => {
  const [activeTab, setActiveTab] = useState('dashboard');
  const [appData, setAppData] = useState({
    products: [],
    categories: [],
    roles: [],
    countries: [],
    nonce: '',
    roleSummary: {},
    countrySummary: {},
    globalSettings: {}
  });

  useEffect(() => {
    if (window.SRFWAPP) {
      setAppData({
        products: window.SRFWAPP.products || [],
        categories: window.SRFWAPP.categories || [],
        roles: window.SRFWAPP.roles || [],
        countries: window.SRFWAPP.countries || [],
        nonce: window.SRFWAPP.nonce || '',
        roleSummary: window.SRFWAPP.roleSettingsSummary || {},
        countrySummary: window.SRFWAPP.countrySettingsSummary || {},
        globalSettings: window.SRFWAPP.globalSettings || {}
      });
    }
  }, []);

  const renderContent = () => {
    switch (activeTab) {
      case 'dashboard':
        return <Dashboard
          roleSummary={appData.roleSummary}
          countrySummary={appData.countrySummary}
          globalSettings={appData.globalSettings}
        />;
      case 'global':
        return <GlobalSettings
          products={appData.products}
          categories={appData.categories}
          nonce={appData.nonce}
        />;
      case 'role':
        return <RoleSettings
          roles={appData.roles}
          products={appData.products}
          categories={appData.categories}
          nonce={appData.nonce}
          initialSummary={appData.roleSummary}
        />;
      case 'country':
        return <CountrySettings
          countries={appData.countries}
          products={appData.products}
          categories={appData.categories}
          nonce={appData.nonce}
          initialSummary={appData.countrySummary}
        />;
      case 'bulk-role':
        return <ProTab type="bulk-role" />;
      case 'bulk-country':
        return <ProTab type="bulk-country" />;
      case 'order':
        return <ProTab type="order" />;
      default:
        return <Dashboard />;
    }
  };

  return (
    <ThemeProvider theme={theme}>
      <Layout activeTab={activeTab} onTabChange={setActiveTab}>
        {renderContent()}
      </Layout>
    </ThemeProvider>
  );
};

export default App;
