import React, { ReactNode } from 'react';
import styled from 'styled-components';
import { useForbiddenRouteToast } from '@/features/auth/hooks/useForbiddenRouteToast';
import { PageContainer } from '../PageContainer';
import { Header } from '../Header';
import { Sidebar } from '../Sidebar';
import { SidebarNavProvider, useSidebarNav, SIDEBAR_MOBILE_MAX_WIDTH } from '../SidebarNavContext';

interface AppLayoutProps {
  children: ReactNode;
}

const AppShell = styled.div`
  --sidebar-width: ${({ theme }) => theme.layout.sidebarWidth};
  display: grid;
  grid-template-columns: var(--sidebar-width) minmax(0, 1fr);
  height: 100dvh;
  overflow: hidden;
  background-color: ${({ theme }) => theme.colors.background};

  @media ${SIDEBAR_MOBILE_MAX_WIDTH} {
    grid-template-columns: minmax(0, 1fr);
  }
`;

const ShellBody = styled.div`
  display: flex;
  flex-direction: column;
  min-width: 0;
  height: 100dvh;
  overflow: hidden;
`;

const MainScrollArea = styled.main`
  flex: 1;
  min-height: 0;
  padding: ${({ theme }) => theme.layout.pagePadding};
  overflow-y: auto;
  overflow-x: hidden;
  max-width: 100%;

  @media ${SIDEBAR_MOBILE_MAX_WIDTH} {
    padding: ${({ theme }) => theme.spacing[6]} ${({ theme }) => theme.spacing[4]};
  }

  @media (max-width: 480px) {
    padding: ${({ theme }) => theme.spacing[5]} ${({ theme }) => theme.spacing[4]};
  }

  @media (max-width: 390px) {
    padding: ${({ theme }) => theme.spacing[4]} ${({ theme }) => theme.spacing[3]};
  }
`;

const ContentInner = styled(PageContainer)`
  padding-top: ${({ theme }) => theme.layout.pageTop};
`;

const MobileOverlay = styled.div<{ $isVisible: boolean }>`
  display: none;

  @media ${SIDEBAR_MOBILE_MAX_WIDTH} {
    display: ${({ $isVisible }) => ($isVisible ? 'block' : 'none')};
    position: fixed;
    inset: 0;
    background-color: ${({ theme }) => theme.colors.overlay};
    z-index: ${({ theme }) => theme.zIndex.fixed - 1};
    backdrop-filter: blur(2px);
  }
`;

const AppLayoutInner: React.FC<{ children: ReactNode }> = ({ children }) => {
  const nav = useSidebarNav();
  useForbiddenRouteToast();
  if (!nav) {
    throw new Error('AppLayoutInner must render inside SidebarNavProvider');
  }

  const { isMobile, isDrawerOpen, closeDrawer } = nav;
  const sidebarCollapsed = isMobile ? !isDrawerOpen : false;

  return (
    <AppShell data-testid="app-shell">
      <Sidebar isCollapsed={sidebarCollapsed} />
      <ShellBody>
        <Header />
        <MainScrollArea>
          <ContentInner>{children}</ContentInner>
        </MainScrollArea>
      </ShellBody>
      <MobileOverlay $isVisible={isDrawerOpen} onClick={closeDrawer} data-testid="sidebar-overlay" />
    </AppShell>
  );
};

export const AppLayout: React.FC<AppLayoutProps> = ({ children }) => (
  <SidebarNavProvider>
    <AppLayoutInner>{children}</AppLayoutInner>
  </SidebarNavProvider>
);
