import { useState } from 'react';
import { useCreation, useReactive } from 'ahooks';
import { Menu as MenuIcon, Close as CloseIcon } from '@mui/icons-material';
import { Button, Container, useMediaQuery, Drawer } from '@mui/material';
import Header from './header';
import { styled, useTheme } from '../Theme';
import { type HeaderProps } from './header';

export interface ResponsiveHeaderProps extends Omit<HeaderProps, 'children'> {
  menu?: React.ReactNode;
  children?: React.ReactNode | ((props: { isMobile: boolean; closeMenu: () => void }) => React.ReactNode);
}

/**
 * ResponsiveHeader
 * - 窄屏下显示 burge menu
 * - 窄屏下将 children 区域显示到 menu 中
 *
 * 注意: 暂时不要通过 display: none 隐藏 logo, https://blog.patw.me/archives/1820/inline-svg-same-id-and-display-none-issue/
 */
function ResponsiveHeader({ prepend, children = null, ...rest }: ResponsiveHeaderProps) {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('md'));
  const [drawerOpen, setDrawerOpen] = useState(false);
  const _children =
    typeof children === 'function' ? children({ isMobile, closeMenu: () => setDrawerOpen(false) }) : children;

  // HACK: MUI 的 modal 只会对 body 元素设置防滚动样式，还需要对 html 元素进行设置防滚动样式
  const htmlOverflowState = useReactive({
    changed: false,
    value: '',
    priority: '',
  });
  useCreation(() => {
    if (document.documentElement?.style) {
      const clean = () => {
        if (htmlOverflowState.changed) {
          if (htmlOverflowState.value) {
            document.documentElement.style.setProperty('overflow', htmlOverflowState.value, htmlOverflowState.priority);
          } else {
            document.documentElement.style.removeProperty('overflow');
          }
          htmlOverflowState.value = '';
          htmlOverflowState.priority = '';
          htmlOverflowState.changed = false;
        }
      };
      if (drawerOpen) {
        htmlOverflowState.changed = true;
        htmlOverflowState.value = document.documentElement.style.getPropertyValue('overflow');
        htmlOverflowState.priority = document.documentElement.style.getPropertyPriority('overflow');
        document.documentElement.style.setProperty('overflow', 'revert', 'important');
      } else {
        clean();
      }

      return clean;
    }
    return () => {};
  }, [drawerOpen]);

  // 如果 children 没有值, 则使用普通的 Header 组件渲染 (此时并没有什么内容需要在 menu 中显示)
  if (!children) {
    return <Header prepend={prepend} {...rest} />;
  }
  return (
    <Root
      prepend={
        prepend || (
          <Button
            sx={{ color: theme.palette.grey[500] }}
            className="header-menu"
            aria-label="header menu button"
            onClick={() => setDrawerOpen(!drawerOpen)}>
            {drawerOpen ? <CloseIcon /> : <MenuIcon />}
          </Button>
        )
      }
      {...rest}>
      {!isMobile && _children}
      {isMobile && (
        <Drawer
          open={drawerOpen}
          onClose={() => setDrawerOpen(false)}
          ModalProps={{
            disablePortal: false,
            keepMounted: true,
            BackdropComponent: undefined,
          }}
          anchor="top"
          sx={{
            top: 64,
            zIndex: theme.zIndex.appBar - 1,
          }}
          slotProps={{
            paper: {
              style: {
                top: 64,
                bottom: 0,
                boxShadow: 'none',
                backgroundImage: 'none',
                backgroundColor: theme.palette.background.paper,
              },
            },
          }}>
          <MenuPanel>{_children}</MenuPanel>
        </Drawer>
      )}
    </Root>
  );
}

const Root = styled(Header)`
  .header-menu {
    display: none;
  }
  ${(props) => props.theme.breakpoints.down('md')} {
    .header-menu {
      display: flex;
      margin-right: 12px;
    }
  }
`;

const MenuPanel = styled(Container)`
  padding-top: 8px;
  padding-bottom: 16px;
  .navmenu {
    margin: 0 -16px;
    .navmenu-root > .navmenu-item,
    .navmenu-root > .navmenu-sub {
      border: 0;
    }
  }
`;

export default ResponsiveHeader;
