import { type FC } from 'react';
import Carousel from 'react-material-ui-carousel';

import { Grid } from '@mui/material';
import { chunk } from 'lodash';

import { type CompleteFile } from '../../../types/attachments';
import FileCard from '../../design-system/FileCard';

import FileCarrouselItemEditable from './FileCarrouselItemEditable';

export type FileCarrouselProps = {
  slidesPerView?: number;
};

type FilesCarrouselProps = {
  files?: CompleteFile[];
  isEditable?: boolean;
  filesCarrouselProps?: FileCarrouselProps;
};
export const FilesCarrousel: FC<FilesCarrouselProps> = ({
  files,
  isEditable,
  filesCarrouselProps,
}) => {
  const { slidesPerView = 3 } = filesCarrouselProps ?? {};
  if (!files?.length) return null;
  return (
    <Carousel
      key={files.every(f => f.attachment).toString()} // forces re-render to vertically align navigation buttons
      indicators={false}
      navButtonsAlwaysVisible
      navButtonsAlwaysInvisible={files.length === 1}
      fullHeightHover={false}
      cycleNavigation={false}
      autoPlay={false}
      sx={{
        overflow: 'unset',
        '> div:not(:first-of-type)': {
          top: '50%',
          transform: 'translateY(-50%)',
        },
        'div:has(> button[aria-label="Next"])': {
          right: '-30px',
        },
        'div:has(> button[aria-label="Previous"])': {
          left: '-30px',
        },
      }}
    >
      {chunk(files, slidesPerView).map(c => (
        <Grid
          container
          columns={slidesPerView}
          spacing={1}
          key={c[0].id}
        >
          {c.map(item => (
            <Grid
              item
              xs={1}
              key={item.id}
            >
              {isEditable ? (
                <FileCarrouselItemEditable item={item} />
              ) : (
                <FileCard
                  sx={{
                    width: '100%',
                  }}
                  file={item.file}
                  attachment={item.attachment}
                  status="success"
                />
              )}
            </Grid>
          ))}
        </Grid>
      ))}
    </Carousel>
  );
};

export default FilesCarrousel;
