import ChevronLeft from '@mui/icons-material/ChevronLeft'
import {
  Breadcrumbs as MuiBreadcrumbs,
  IconButton,
  Stack,
  styled,
  Typography,
} from '@mui/material'
import { ReactNode } from 'react'
import { Link, useNavigate } from 'react-router-dom'

interface BreadcrumbsProps {
  links: { to: string; name: string | ReactNode }[]
  icon?: ReactNode
}

const StyledStack = styled(Stack)(({ theme }) => ({
  flexDirection: 'row',
  alignItems: 'center',
  '& .MuiSvgIcon-root': {
    fontSize: '28px',
  },
  '& .MuiTypography-root': {
    fontSize: '18px',
    fontWeight: 600,
  },
}))

const StyledLink = styled(Link)(({ theme }) => ({
  textDecoration: 'none',
  color: theme.palette.text.primary,
  transition: 'color 0.2s ease-in-out',
  fontFamily: 'Poppins',
  '&:hover': {
    color: theme.palette.common.yellow,
  },
}))

const StyledIconButton = styled(IconButton)(({ theme }) => ({
  color: theme.palette.text.primary,
  padding: 0,
  marginRight: '5px',
}))

export default function Breadcrumbs({ links, icon }: BreadcrumbsProps) {
  const navigate = useNavigate()
  let linksArray = links.slice(0, -1)
  let currentPage = links.slice(-1)[0]
  const backLink = links.slice(-2)[0]

  return (
    <StyledStack direction={'row'} alignItems="center">
      {linksArray?.length ? (
        <StyledIconButton
          onClick={() => {
            navigate(backLink.to)
          }}
        >
          {icon ? icon : <ChevronLeft />}
        </StyledIconButton>
      ) : null}
      <MuiBreadcrumbs separator={<Typography variant="h3">/</Typography>}>
        {linksArray.map((link, index) => (
          <StyledLink to={link.to} key={index}>
            {link?.name}
          </StyledLink>
        ))}
        <Typography variant="h3">{currentPage?.name}</Typography>
      </MuiBreadcrumbs>
    </StyledStack>
  )
}
