import { MenuBreadcrumb, MenuItem } from '@/components/Layout';
import { MainCard } from '@/components/MainCard';
import { ApartmentOutlined, HomeFilled, HomeOutlined } from '@ant-design/icons';
import { Divider, Grid, Typography } from '@mui/material';
import { default as MuiBreadcrumbs } from '@mui/material/Breadcrumbs';
import { useTheme } from '@mui/material/styles';
import { useEffect, useState } from 'react';
import { Link, useLocation } from 'react-router-dom';

function renderBreadcrumb({ id, title, icon, url, last }: MenuBreadcrumb) {
  const Icon = icon ? icon : ApartmentOutlined;
  return (
    <Typography
      key={id}
      component={Link}
      to={url}
      variant={last ? 'subtitle1' : 'h6'}
      sx={{
        textDecoration: 'none',
        display: 'inline-flex',
        alignItems: 'center'
      }}
      color="textSecondary"
    >
      {/* @ts-ignore */}
      {icon ? <Icon style={{ marginRight: 8, fontSize: '0.875rem' }} /> : null}
      {title}
    </Typography>
  );
}
type BreadcrumbsProps = {
  home?: boolean | string;
  card?: boolean;
  divider?: boolean;
  icon?: boolean;
  icons?: boolean;
  maxItems?: number;
  navigation?: any;
  rightAlign?: boolean;
  separator?: any;
  title?: boolean;
  titleBottom?: boolean;
  sx?: any;
  breadcrumbs: MenuBreadcrumb[];
  mode?: 'navigation' | 'breadcrumbs';
};

function Breadcrumbs({
  home = 'Home',
  card,
  divider = true,
  icon,
  icons,
  maxItems,
  navigation,
  rightAlign,
  separator,
  title,
  titleBottom,
  sx,
  breadcrumbs,
  mode = 'navigation',
  ...others
}: BreadcrumbsProps) {
  const theme = useTheme();
  const location = useLocation();
  const [main, setMain] = useState<MenuItem>();
  const [item, setItem] = useState<MenuItem>();

  const currentPath = location.pathname;

  const iconSX = {
    marginRight: theme.spacing(0.75),
    marginTop: `-${theme.spacing(0.25)}`,
    width: '1rem',
    height: '1rem',
    color: theme.palette.secondary.main
  };

  // set active item state
  function getCollapse(menu: MenuItem) {
    if (menu.children) {
      menu.children.filter((collapse) => {
        if (collapse.type && collapse.type === 'collapse') {
          getCollapse(collapse);
          if (collapse.url === currentPath) {
            setMain(collapse);
            setItem(collapse);
          }
        } else if (collapse.type && collapse.type === 'item') {
          if (currentPath.includes(collapse.url)) {
            setMain(menu);
            setItem(collapse);
          }
        }
        return false;
      });
    }
  }

  useEffect(() => {
    navigation?.items?.map((menu: MenuItem) => {
      if (menu.type && menu.type === 'group') {
        getCollapse(menu);
      }
      return false;
    });
  });

  // item separator
  const SeparatorIcon = separator;
  const separatorIcon = separator ? <SeparatorIcon style={{ fontSize: '0.75rem', marginTop: 2 }} /> : '/';
  const cardSx = {
    mb: 2,
    bgcolor: card === false ? 'transparent' : 'inherit',
    ...sx,
    [theme.breakpoints.down('sm')]: {
      mb: 1
    }
  };

  let mainContent;
  let itemContent;
  let breadcrumbContent = <Typography />;
  let itemTitle = '';
  let CollapseIcon;
  let ItemIcon;
  if (mode === 'breadcrumbs') {
    return (
      <MainCard border={card} sx={cardSx} {...others} content={card} shadow="none">
        <Grid
          container
          direction={rightAlign ? 'row' : 'column'}
          justifyContent={rightAlign ? 'space-between' : 'flex-start'}
          alignItems={rightAlign ? 'center' : 'flex-start'}
          spacing={1}
        >
          {title && !titleBottom ? (
            <Grid item>
              <Typography variant="h2">{item!.title}</Typography>
            </Grid>
          ) : null}
          <Grid item>
            <MuiBreadcrumbs
              aria-label="breadcrumb"
              maxItems={maxItems || 8}
              separator={separatorIcon}
              sx={{
                [theme.breakpoints.down('sm')]: {
                  mt: 1
                }
              }}
            >
              {home !== false && (
                <Typography component={Link} to="/" color="textSecondary" variant="h6" sx={{ textDecoration: 'none' }}>
                  {icons ? <HomeOutlined style={iconSX} /> : null}
                  {icon && !icons ? <HomeFilled style={{ ...iconSX, marginRight: 0 }} /> : null}
                  {!icon || icons ? home : null}
                </Typography>
              )}
              {breadcrumbs.map(renderBreadcrumb)}
            </MuiBreadcrumbs>
          </Grid>
          {title && titleBottom ? (
            <Grid item sx={{ mt: card === false ? 0.25 : 1 }}>
              <Typography variant="h2">{item!.title}</Typography>
            </Grid>
          ) : null}
        </Grid>
        {card === false && divider !== false && <Divider sx={{ mt: 2 }} />}
      </MainCard>
    );
  }
  // collapse item
  if (main && main.type === 'collapse' && main.breadcrumbs === true) {
    CollapseIcon = main.icon ? main.icon : ApartmentOutlined;
    mainContent = (
      <Typography
        component={Link}
        to={item?.url || document.location.pathname}
        variant="h6"
        sx={{ textDecoration: 'none' }}
        color="textSecondary"
      >
        {/* @ts-ignore */}
        {icons ? <CollapseIcon style={iconSX} /> : null}
        {main.title}
      </Typography>
    );
    breadcrumbContent = (
      <MainCard border={card} sx={cardSx} {...others} content={card} shadow="none">
        <Grid
          container
          direction={rightAlign ? 'row' : 'column'}
          justifyContent={rightAlign ? 'space-between' : 'flex-start'}
          alignItems={rightAlign ? 'center' : 'flex-start'}
          spacing={1}
        >
          <Grid item>
            <MuiBreadcrumbs aria-label="breadcrumb" maxItems={maxItems || 8} separator={separatorIcon}>
              {home !== false && (
                <Typography component={Link} to="/" color="textSecondary" variant="h6" sx={{ textDecoration: 'none' }}>
                  {icons ? <HomeOutlined style={iconSX} /> : null}
                  {icon && !icons ? <HomeFilled style={{ ...iconSX, marginRight: 0 }} /> : null}
                  {!icon || icons ? home : null}
                </Typography>
              )}
              {mainContent}
            </MuiBreadcrumbs>
          </Grid>
          {title && titleBottom ? (
            <Grid item sx={{ mt: card === false ? 0.25 : 1 }}>
              <Typography variant="h2">{main.title}</Typography>
            </Grid>
          ) : null}
        </Grid>
        {card === false && divider !== false && <Divider sx={{ mt: 2 }} />}
      </MainCard>
    );
  }

  // items
  if (item && item.type === 'item') {
    itemTitle = item.title;

    ItemIcon = item.icon ? item.icon : ApartmentOutlined;
    itemContent = (
      <Typography
        variant="subtitle1"
        color="textPrimary"
        component={Link}
        to={item.url}
        sx={{
          textDecoration: 'none'
        }}
      >
        {/* @ts-ignore */}
        {icons ? <ItemIcon style={iconSX} /> : null}
        {itemTitle}
      </Typography>
    );

    // main
    if (item.breadcrumbs !== false) {
      breadcrumbContent = (
        <MainCard
          border={card}
          sx={{
            mb: 3,
            bgcolor: card === false ? 'transparent' : 'inherit',
            ...sx,
            [theme.breakpoints.down('sm')]: {
              mb: 1
            }
          }}
          {...others}
          content={card}
          shadow="none"
        >
          <Grid
            container
            direction={rightAlign ? 'row' : 'column'}
            justifyContent={rightAlign ? 'space-between' : 'flex-start'}
            alignItems={rightAlign ? 'center' : 'flex-start'}
            spacing={1}
          >
            {title && !titleBottom ? (
              <Grid item>
                <Typography variant="h2">{item.title}</Typography>
              </Grid>
            ) : null}
            <Grid item>
              <MuiBreadcrumbs aria-label="breadcrumb" maxItems={maxItems || 8} separator={separatorIcon}>
                {home !== false && (
                  <Typography
                    component={Link}
                    to="/"
                    color="textSecondary"
                    variant="h6"
                    sx={{ textDecoration: 'none' }}
                  >
                    {icons ? <HomeOutlined style={iconSX} /> : null}
                    {icon && !icons ? <HomeFilled style={{ ...iconSX, marginRight: 0 }} /> : null}
                    {!icon || icons ? home : null}
                  </Typography>
                )}
                {mainContent}
                {itemContent}
              </MuiBreadcrumbs>
            </Grid>
            {title && titleBottom ? (
              <Grid item sx={{ mt: card === false ? 0.25 : 1 }}>
                <Typography variant="h2">{item.title}</Typography>
              </Grid>
            ) : null}
          </Grid>
          {card === false && divider !== false && <Divider sx={{ mt: 2 }} />}
        </MainCard>
      );
    }
  }

  return breadcrumbContent;
}
export { Breadcrumbs };
export type { BreadcrumbsProps };
