'use client';
import { FunctionComponent, ReactNode, useCallback } from 'react';
import { useTranslations } from 'next-intl';
import { Divider, Drawer, Stack } from '@mui/material';
import { AppButton } from '@/components';
import LocaleSwitcher from '@/components/common/LocaleSwitcher';
import { useIsAuthenticated } from '@/hooks';
import { useLogout } from '@/services/auth';
import { LinkToPage } from '@/utils';
import { SIDE_BAR_WIDTH } from '../config';
import SideBarNavList from './SideBarNavList';
import BrandLockup from './BrandLockup';
import { DarkModeFormSwitch } from './DarkModeButton';

export interface SideBarProps {
  items: Array<LinkToPage>;
  /** Physical edge, derived from text direction by the caller ('start' under both locales). */
  anchor: 'left' | 'right';
  mobileOpen: boolean;
  onMobileClose: () => void;
  /** Rendered below the brand header, above the nav list (the nurse shell's ProfileSummary card). */
  identity?: ReactNode;
}

/**
 * Renders the sidebar as two Drawers sharing one content tree — a `temporary` (overlay) drawer for
 * mobile and a `permanent` (in-flow) drawer for desktop, switched purely by CSS breakpoint (`sx`
 * `display`). Because the desktop variant is `permanent`, it reserves its own width as a normal flex
 * item — the caller never computes a matching content offset, and there is no JS `useIsMobile`
 * branching to cause a post-hydration layout jump.
 *
 * The close handler is wired to the nav list only (`SideBarNavList`'s `onClick`), not the whole
 * drawer body — toggling dark mode, switching locale, or a mis-tap on a divider never closes it.
 * @component SideBar
 */
const SideBar: FunctionComponent<SideBarProps> = ({ items, anchor, mobileOpen, onMobileClose, identity }) => {
  const isAuthenticated = useIsAuthenticated();
  const t = useTranslations('nav');
  const { mutate: logout } = useLogout();

  const handleNavClick = useCallback(() => onMobileClose(), [onMobileClose]);

  const content = (
    <Stack sx={{ height: '100%', padding: 2, gap: 2, overflowY: 'auto' }}>
      <BrandLockup />
      <Divider />

      {identity && (
        <>
          {identity}
          <Divider />
        </>
      )}

      <SideBarNavList items={items} showIcons onClick={handleNavClick} />

      <Divider sx={{ marginTop: 'auto' }} />

      <Stack direction="row" sx={{ alignItems: 'center', justifyContent: 'space-between' }}>
        {/* Only DarkModeFormSwitch subscribes to useColorScheme — it's the sole re-render target */}
        <DarkModeFormSwitch />
        <LocaleSwitcher />
      </Stack>

      {isAuthenticated && (
        <AppButton variant="text" color="error" startIcon="logout" fullWidth onClick={() => logout()}>
          {t('logout')}
        </AppButton>
      )}
    </Stack>
  );

  return (
    <>
      <Drawer
        anchor={anchor}
        open={mobileOpen}
        onClose={onMobileClose}
        variant="temporary"
        ModalProps={{ keepMounted: true }}
        sx={{ display: { xs: 'block', md: 'none' } }}
        slotProps={{ paper: { sx: { width: SIDE_BAR_WIDTH } } }}
      >
        {content}
      </Drawer>
      <Drawer
        anchor={anchor}
        variant="permanent"
        sx={{ display: { xs: 'none', md: 'block' }, width: SIDE_BAR_WIDTH, flexShrink: 0 }}
        slotProps={{ paper: { sx: { width: SIDE_BAR_WIDTH, position: 'relative' } } }}
      >
        {content}
      </Drawer>
    </>
  );
};

export default SideBar;
