import { Box, type BoxProps, Container, type Breakpoint } from '@mui/material';
import { useRef, useState, useEffect, type JSX } from 'react';
import AutoHidden from './auto-hidden';
import { styled } from '../Theme';
import HeaderAddons from './header-addons';

export interface HeaderProps extends Omit<BoxProps, 'maxWidth'> {
  /** logo img/svg, 可以包裹一个 a 标签 */
  logo?: React.ReactNode;
  /** 相当于 Title, 可以包裹一个 a 标签 */
  brand?: React.ReactNode;
  /** brand 右侧的内容区域, 可显示一个 badge 或 tag */
  brandAddon?: React.ReactNode;
  /** brand 下方的描述 */
  description?: React.ReactNode;
  /** 右侧区域, 可以放置 icons/actions/login 等 */
  addons?: React.ReactNode;
  /** logo 左侧内容 */
  prepend?: React.ReactNode;
  align?: 'left' | 'right';
  maxWidth?: Breakpoint | false;
  homeLink?: string | ((brandContent: React.ReactNode) => JSX.Element | null);
}

/**
 * Header 组件
 * TODO: Layout/dashboard 可以复用此处的 header
 */
function Header({
  logo = null,
  brand = null,
  brandAddon = null,
  description = null,
  children = null,
  addons = null,
  prepend = null,
  align = 'left',
  maxWidth = false,
  homeLink = '/',
  ...rest
}: HeaderProps) {
  const logoRef = useRef<HTMLDivElement>(null);
  const [brandWrapperMinWidth, setBrandWrapperMinWidth] = useState('0px');
  const style = { minWidth: brandWrapperMinWidth };

  useEffect(() => {
    const { searchParams } = new URL(window.location.href);
    if (searchParams.get('inviter')) {
      window.localStorage.setItem('inviter', searchParams.get('inviter')!);
    }

    if (logoRef.current) {
      setBrandWrapperMinWidth(`${logoRef.current.offsetWidth}px`);
    }
  }, []);

  const renderBrand = () => {
    const brandContent = (
      <>
        {logo && (
          <div className="header-logo" ref={logoRef}>
            {logo}
          </div>
        )}
        {brand && (
          <AutoHidden height={44} sx={{ flexShrink: { xs: 1 } }}>
            <div className="header-brand">
              <div className="header-brand-title">
                <h2>{brand}</h2>
              </div>
              <div className="header-brand-desc">{description}</div>
            </div>
          </AutoHidden>
        )}
      </>
    );
    if (typeof homeLink === 'function') {
      return homeLink(brandContent);
    }
    return <a href={homeLink}>{brandContent}</a>;
  };

  return (
    <Root {...rest}>
      <Container maxWidth={maxWidth} className="header-container">
        {prepend}
        <div className="header-brand-wrapper" style={style}>
          {renderBrand()}
        </div>
        <div className="header-brand-addon">{brandAddon}</div>
        {align === 'right' && (
          <Box
            sx={{
              display: 'inline-block',
              flexGrow: 1,
            }}
          />
        )}
        {children}
        {align === 'left' && (
          <Box
            sx={{
              display: 'inline-block',
              flexGrow: 1,
            }}
          />
        )}
        <HeaderAddons className="header-addons">{addons}</HeaderAddons>
      </Container>
    </Root>
  );
}

const Root = styled(Box)`
  position: relative;
  font-size: 14px;
  z-index: ${({ theme }) => theme.zIndex.appBar};
  background: ${({ theme }) => theme.palette.background.default};
  .header-container {
    display: flex;
    align-items: center;
    height: 64px;
  }

  .header-brand-wrapper {
    flex-shrink: 2;
    > a {
      display: flex;
      align-items: center;
      height: 100%;
      line-height: 1;
      color: inherit;
      text-decoration: none;
    }
  }
  .header-brand-wrapper .header-logo {
    display: inline-flex;
    position: relative;
    height: 44px;
    margin-right: 16px;
    img,
    svg {
      width: auto;
      height: 100%;
      max-height: 100%;
    }
  }
  .header-brand {
    display: flex;
    flex-direction: column;
    justify-content: center;
    height: 44px;
    margin-right: 16px;
    line-height: 1;
    a {
      color: inherit;
      text-decoration: none;
    }
    .header-brand-title {
      display: flex;
      align-items: center;
      h2 {
        margin: 0;
        font-size: 16px;
      }
    }
    .header-brand-desc {
      margin-top: 4px;
      color: ${({ theme }) => {
        return theme.palette.text.hint;
      }};
    }
  }
  .header-brand-addon {
    margin-right: 16px;
  }
  .header-addons {
    display: flex;
    align-items: center;
  }
  ${(props) => props.theme.breakpoints.down('lg')} {
    .header-brand {
      margin-right: 12px;
      .header-brand-title {
        h2 {
          font-size: 14px;
        }
      }
    }
    .header-brand-addon {
      display: none;
    }
  }
  ${(props) => props.theme.breakpoints.down('md')} {
    .header-menu {
      display: inline-block;
    }
    .header-brand-wrapper .header-logo {
      height: 32px;
    }
    .header-brand {
      .header-brand-title {
        h2 {
          font-size: 13px;
        }
      }
      .header-brand-desc {
        font-size: 12px;
      }
    }
  }
`;

export default Header;
