import React, { useMemo, useEffect } from 'react';
import { ThemeProvider, CssBaseline, Box } from '@mui/material';
import { CacheProvider } from '@emotion/react';
import createCache from '@emotion/cache';
import { getTheme } from './theme/theme';
import { useAppStore } from './store/useAppStore';
import Sidebar from './components/Sidebar.tsx';
import MainContent from './components/MainContent.tsx';
import Header from './components/Header.tsx';
import Login from './components/Login.tsx';
import NavigationRail from './components/NavigationRail.tsx';
import TransferContent from './components/TransferContent.tsx';

// Create emotion cache to handle the :first-child warning and ensure proper style injection
const cache = createCache({
  key: 'mui',
  prepend: true,
});

const App: React.FC = () => {
  const { darkMode, connected, activeTab, setActiveTab } = useAppStore();
  const theme = useMemo(() => getTheme(darkMode ? 'dark' : 'light'), [darkMode]);

  useEffect(() => {
    if (darkMode) {
      document.body.classList.add('dark');
    } else {
      document.body.classList.remove('dark');
    }
  }, [darkMode]);

  if (!connected) {
    return (
      <CacheProvider value={cache}>
        <ThemeProvider theme={theme}>
          <CssBaseline />
          <Login />
        </ThemeProvider>
      </CacheProvider>
    );
  }

  return (
    <CacheProvider value={cache}>
      <ThemeProvider theme={theme}>
        <CssBaseline />
        <Box sx={{ display: 'flex', height: '100vh', overflow: 'hidden' }}>
          <NavigationRail activeTab={activeTab} onTabChange={setActiveTab} />
          {activeTab === 'explorer' && <Sidebar />}
          <Box sx={{ flexGrow: 1, display: 'flex', flexDirection: 'column', minWidth: 0, overflow: 'hidden' }}>
            <Header />
            {activeTab === 'transfer' ? <TransferContent /> : <MainContent />}
          </Box>
        </Box>
      </ThemeProvider>
    </CacheProvider>
  );
};

export default App;
