import { useEffect, useState } from 'react';
import Helmet from 'react-helmet';
import {
  AppBar,
  Container,
  Drawer,
  Divider,
  IconButton,
  Link,
  List,
  ListItemText,
  Toolbar,
  Typography,
  type SxProps,
  ListItemButton,
} from '@mui/material';
import { Menu as MenuIcon } from '@mui/icons-material';

import Footer from '../Footer';
import OpenInWallet from '../Wallet/Open';
import Icon from '../Icon';
import Logo from '../Logo';
import { styled } from '../Theme';
import { type LinkItem } from './dashboard/sidebar';

export interface LayoutProps extends React.HTMLAttributes<HTMLDivElement> {
  title: string;
  brand: React.ReactNode;
  description?: React.ReactNode;
  links?: LinkItem[];
  logo?: React.ReactNode;
  showLogo?: false | true;
  addons?: React.ReactNode;
  footer?: React.ReactNode;
  baseUrl?: string;
  homeUrl?: string;
  variant?: 'shadow' | 'border';
  contentOnly?: false | true;
  sx?: SxProps;
}

export default function Layout({
  title,
  brand,
  description = undefined,
  links = [],
  logo = <Logo showText={false} style={{ width: '40px', height: '40px' }} />,
  showLogo = false,
  addons = undefined,
  footer = (
    <Container>
      <Footer />
    </Container>
  ),
  baseUrl = '',
  homeUrl = '/',
  variant = 'shadow',
  contentOnly = false,
  children,
  ...rest
}: LayoutProps) {
  const [drawerOpen, setDrawerOpen] = useState(false);
  const onToggleDrawer = () => {
    setDrawerOpen(!drawerOpen);
  };

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

  if (contentOnly) {
    return <Container>{children}</Container>;
  }

  let activeLink = '';
  // @ts-expect-error
  const { pathname: currentPath } = new URL(window.location);
  links.forEach((link) => {
    if (currentPath.startsWith(link.url) && link.url.length > activeLink.length) {
      activeLink = link.url;
    }
  });

  const drawer = (
    <div>
      <Toolbar className="toolbar toolbar--drawer">
        {!!showLogo && <div className="menu-logo">{logo}</div>}
        <div style={{ flexGrow: 1, overflow: 'hidden', textOverflow: 'ellipsis' }}>{brand}</div>
      </Toolbar>
      <Divider />
      <List>
        {links.map((x) => (
          <Link className="nav-link" key={x.url} href={x.url} underline="hover">
            <ListItemButton className={activeLink === x.url ? 'drawer-highlight-nav' : ''}>
              <ListItemText>
                {typeof x.icon === 'string' ? (
                  <Icon name={x.icon} size={18 * (x.iconZoom || 1)} color="inherit" style={{ marginRight: '5px' }} />
                ) : (
                  x.icon
                )}
                {x.title}
              </ListItemText>
            </ListItemButton>
          </Link>
        ))}
      </List>
    </div>
  );

  return (
    <>
      <Div {...rest}>
        <Helmet title={title} />
        <AppBar position="fixed" className={`appbar appbar--${variant}`} color="default" style={{ height: 56 }}>
          <Container disableGutters>
            <Toolbar className="toolbar">
              <IconButton
                color="inherit"
                aria-label="open drawer"
                edge="start"
                onClick={onToggleDrawer}
                className="menu-button"
                size="large">
                <MenuIcon />
              </IconButton>
              {!!showLogo && <div className="menu-logo">{logo}</div>}
              <Typography
                href={homeUrl}
                component="a"
                variant="h5"
                color="inherit"
                noWrap
                className="brand"
                sx={{
                  display: 'block',
                }}>
                {brand}
              </Typography>
              {description && (
                <Typography component="small" variant="subtitle2" color="inherit" noWrap className="description">
                  {description}
                </Typography>
              )}
              <div style={{ flexGrow: 1 }} />
              <div className="nav-links">
                {links.map((x) => (
                  <Link
                    key={x.url}
                    href={x.url}
                    className={`nav-link ${activeLink === x.url ? 'highlight-nav' : ''}`}
                    color={x.color}
                    underline="hover">
                    {typeof x.icon === 'string' ? (
                      <Icon
                        name={x.icon}
                        size={20 * (x.iconZoom || 1)}
                        color="inherit"
                        style={{ marginRight: '5px' }}
                      />
                    ) : (
                      x.icon
                    )}
                    {x.title}
                  </Link>
                ))}
              </div>
              {addons}
            </Toolbar>
          </Container>
        </AppBar>
        <div className="toolbar" />
        <Container style={{ marginTop: 16, flex: 1 }}>{children}</Container>
        {footer}
        {!!baseUrl && <OpenInWallet locale="zh" link={baseUrl} />}
      </Div>
      <DrawerDiv>
        <Drawer
          variant="temporary"
          open={drawerOpen}
          onClose={onToggleDrawer}
          classes={{
            paper: 'drawer-paper',
          }}
          ModalProps={{
            keepMounted: true, // Better open performance on mobile.
            disablePortal: true,
          }}>
          {drawer}
        </Drawer>
      </DrawerDiv>
    </>
  );
}

const Div = styled('div')`
  width: 100%;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  .appbar {
    &.appbar--border {
      box-shadow: none;
      &::before {
        content: '';
        position: absolute;
        left: 0;
        right: 0;
        height: 1px;
        bottom: -1px;
        display: block;
        background-color: rgba(0, 0, 0, 0.12);
      }
    }
  }

  .toolbar {
    min-height: 56px;
    background: inherit;
    white-space: nowrap;
    .menu-logo {
      font-size: 0;
      margin-right: 8px;
    }

    .nav-links {
      display: flex;
      align-items: center;
      .nav-link {
        margin: 8px 12px;
        font-size: 16px;
        display: flex;
        align-items: center;
      }

      .highlight-nav {
        font-weight: bolder;
      }
    }
    .brand {
      cursor: pointer;
      text-decoration: none;
      overflow: hidden;
      text-overflow: ellipsis;
      flex-shrink: 1;
    }
    .description {
      color: #999;
      font-size: 15px;
      margin-left: 10px;
      font-weight: normal;
      flex-shrink: 999999;
    }
  }

  ${(props) => props.theme.breakpoints.up('md')} {
    .toolbar {
      .menu-button {
        display: none;
      }
      .menu-logo {
        & + .brand {
          padding-left: 45px;
          margin-left: -45px;
        }
      }
    }
  }

  ${(props) => props.theme.breakpoints.down('md')} {
    .toolbar {
      .nav-links,
      .menu-logo,
      .description {
        display: none;
      }
    }
  }
`;

const DrawerDiv = styled('nav')`
  width: 240px;
  .drawer-paper {
    width: 240px;
  }
  .toolbar {
    min-height: 56px;
  }

  a:hover,
  a:active,
  a:visited,
  a:focus {
    text-decoration: none;
  }

  .drawer-highlight-nav {
    background-color: #eee;
  }

  .toolbar--drawer {
    font-size: 18px;
    .menu-logo {
      display: inline-flex;
    }
  }
`;
