/* eslint-disable react/jsx-no-leaked-render */
import { AppBarStyled } from './AppBarStyled';
import { DrawerToggle } from './DrawerToggle';
import { useLayoutDrawerState, useLayoutLogoState, useLayoutMediaState } from '@/components/Layout/Provider';
import { useSx } from '@/hooks';
import { AppBar, SxProps, Toolbar, useTheme } from '@mui/material';
import { Logo } from '@/components/Logo';
import React, { PropsWithChildren, useRef } from 'react';

type IHeaderProps = PropsWithChildren<{ sx?: SxProps }>;

// Style helpers
function getHeaderSxObj(horizontal: boolean, open: boolean, width: number, theme: any) {
  return {
    borderBottom: `1px solid ${theme.palette.divider}`,
    zIndex: 1200,
    width: horizontal ? '100%' : open ? `calc(100% - ${width}px)` : { xs: '100%', lg: 'calc(100% - 60px)' }
  };
}

function toolbarSx(theme: any) {
  return { '& > *': { marginX: theme.spacing(0.325) } };
}

function Header(props: IHeaderProps) {
  const headerRef = useRef<HTMLElement>(null);
  const theme = useTheme();
  const { downLg, horizontal } = useLayoutMediaState();
  const { open, width } = useLayoutDrawerState();
  const { icon, main } = useLayoutLogoState();

  const HeaderBarComponent = !downLg ? AppBarStyled : AppBar;
  const headerSx = useSx(props, getHeaderSxObj(horizontal, open, width, theme));
  const componentProps: any = {
    position: 'fixed',
    color: 'inherit',
    elevation: 0,
    sx: headerSx
  };
  if (!downLg) {
    componentProps.open = open;
  }

  // Prevent rendering if required values are missing (fixes leaked render)
  if (
    typeof horizontal !== 'boolean' ||
    (horizontal && !React.isValidElement(main)) ||
    (!horizontal && typeof open !== 'boolean')
  ) {
    return null;
  }

  return (
    // @ts-ignore
    <HeaderBarComponent ref={headerRef} {...componentProps}>
      <Toolbar sx={toolbarSx(theme)}>
        {horizontal &&
          (React.isValidElement(main) ? (
            <Logo to="/" isIcon={false} sx={{ width: 120, height: 40, ml: 2 }} logoMain={main} logoIcon={icon} />
          ) : null)}
        {!horizontal && <DrawerToggle />}
        {props.children}
      </Toolbar>
    </HeaderBarComponent>
  );
}

export { Header };
