import { useState, ReactNode } from 'react';
import { Box, Toolbar } from '@mui/material';
import { useLocation } from 'react-router-dom';
import Header from '../shared/Header';
import Sidebar from '../shared/Sidebar';
import { useAuth } from '../../contexts/AuthContext';
import Loading from '../shared/Loading';
import { LayoutProvider, useLayout, DRAWER_WIDTH, DRAWER_WIDTH_COLLAPSED } from '../../contexts/LayoutContext';
import { ChatProvider } from '../../contexts/ChatContext';
import ChatPanel from '../chat/ChatPanel';

interface DashboardLayoutProps {
  children: ReactNode;
}

function DashboardLayoutInner({ children }: DashboardLayoutProps) {
  const [mobileOpen, setMobileOpen] = useState(false);
  const { isLoading } = useAuth();
  const { sidebarCollapsed, chatPanelOpen, chatPanelWidth } = useLayout();
  const location = useLocation();
  const onChatPage = location.pathname === '/chat';

  const handleDrawerToggle = () => {
    setMobileOpen(!mobileOpen);
  };

  if (isLoading) {
    return <Loading message="Lade Dashboard..." />;
  }

  const sidebarWidth = sidebarCollapsed ? DRAWER_WIDTH_COLLAPSED : DRAWER_WIDTH;
  const chatWidth = onChatPage ? 0 : (chatPanelOpen ? chatPanelWidth : 64);

  return (
    <Box sx={{ display: 'flex', height: '100vh', overflow: 'hidden' }}>
      <Header onMenuClick={handleDrawerToggle} />
      <Sidebar mobileOpen={mobileOpen} onMobileClose={() => setMobileOpen(false)} />

      <Box
        component="main"
        sx={{
          flexGrow: 1,
          p: 3,
          width: { sm: `calc(100% - ${sidebarWidth}px - ${chatWidth}px)` },
          overflowY: 'auto',
          backgroundColor: 'background.default',
          transition: 'width 225ms cubic-bezier(0.4, 0, 0.6, 1)',
          minWidth: 0,
        }}
      >
        <Toolbar />
        {children}
      </Box>

      {!onChatPage && <ChatPanel />}
    </Box>
  );
}

function DashboardLayout({ children }: DashboardLayoutProps) {
  return (
    <LayoutProvider>
      <ChatProvider>
        <DashboardLayoutInner>{children}</DashboardLayoutInner>
      </ChatProvider>
    </LayoutProvider>
  );
}

export default DashboardLayout;
