import { useMemo } from 'react';

import {
  Breadcrumbs as MuiBreadcrumbs,
  Typography,
  useTheme,
} from '@mui/material';

import { BreadcrumbsItemText } from './components/BreadcrumbsItemText';
import { BreadcrumbsLinkBox } from './components/BreadcrumbsLinkBox';
import { BreadcrumbsSkeleton } from './components/BreadcrumbsSkeleton';
import { CollapsedIcon } from './components/CollapsedIcon';
import { type BreadcrumbsProps } from './types';

const BreadCrumbs = ({ links, darkBackground, loading }: BreadcrumbsProps) => {
  const theme = useTheme();
  const collapsedLinks = useMemo(() => links.slice(1, -2), [links]);

  if (loading) return <BreadcrumbsSkeleton />;

  return (
    <MuiBreadcrumbs
      aria-label="breadcrumb"
      sx={{
        '& .MuiBreadcrumbs-li': {
          minWidth: 0,
          maxWidth: theme.spacing(30),
        },
        '& .MuiLink-root': {
          textDecoration: 'underline',
          cursor: 'pointer',
          color: darkBackground
            ? theme.palette.new.text.neutral.inverted
            : theme.palette.new.action.button.background.primary.default,
          '&:visited': {
            color: theme.palette.new.action.button.background.primary.focus,
            textDecorationColor:
              theme.palette.new.action.button.background.primary.focus,
          },
          '&:disabled, &.Mui-disabled': {
            color: theme.palette.new.action.button.background.primary.disabled,
            textDecorationColor:
              theme.palette.new.action.button.background.primary.disabled,
            cursor: 'not-allowed',
          },
        },
        '& .MuiButtonBase-root': {
          '&, &:hover': { backgroundColor: 'transparent' },
        },
        '& .MuiBreadcrumbs-separator': {
          mx: 0.5,
          color: darkBackground
            ? theme.palette.new.text.neutral.inverted
            : 'inherit',
        },
      }}
      maxItems={4}
      itemsAfterCollapse={2}
      separator={
        <Typography
          variant="globalS"
          sx={{ mx: 0.5 }}
        >
          /
        </Typography>
      }
      slots={{ CollapsedIcon }}
      // @ts-expect-error - Mui does not recognize the CollapsedIcon props
      slotProps={{ collapsedIcon: { collapsedLinks, darkBackground } }}
    >
      {links.map((link, index) => {
        const isLink = !link.isPresentational && index < links.length - 1;

        return (
          <BreadcrumbsLinkBox
            key={`${link.title}-${link.href}`}
            breadcrumbIcon={link.icon}
          >
            <BreadcrumbsItemText
              link={link}
              isLink={isLink}
              darkBackground={darkBackground}
            />
          </BreadcrumbsLinkBox>
        );
      })}
    </MuiBreadcrumbs>
  );
};

export type { BreadcrumbsProps };
export default BreadCrumbs;
