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

import CloseIcon from '@material-hu/icons/material/Close';
import DownloadIcon from '@material-hu/icons/material/Download';
import Box from '@material-hu/mui/Box';
import DialogUI, { type DialogProps } from '@material-hu/mui/Dialog';
import IconButton from '@material-hu/mui/IconButton';
import { styled } from '@material-hu/mui/styles';
import Tooltip from '@material-hu/mui/Tooltip';
import Typography from '@material-hu/mui/Typography';

import { type Attachment } from 'src/types/attachments';
import { getMaxHeight } from 'src/utils/attachments';
import { downloadUrl, getDownloadName } from 'src/utils/files';
import { useLokaliseTranslation as useTranslation } from 'src/utils/i18n';

import MediaBase from 'src/components/attachment/MediaBase';

const Dialog = styled(DialogUI)({
  '& .content': {
    position: 'fixed',
    width: '100%',
    height: '100%',
    left: '0',
    top: '0',
    display: 'flex',
    flexDirection: 'column',
    '& .large-btn > .MuiSvgIcon-root': {
      width: 'calc(2.5 * 1rem)',
      height: 'calc(2.5 * 1rem)',
    },
  },
  '& .header': {
    color: 'white',
    backgroundColor: 'rgba(0,0,0,0.7)',
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center',
    '& .title': {
      marginLeft: '10px',
    },
    '& .actions': {
      marginLeft: 'auto',
      '& button, a': {
        margin: '6px',
        marginRight: '10px',
        marginLeft: '0px',
        color: 'white',
      },
    },
  },
  '& .carousel': {
    marginTop: 'auto',
    marginBottom: 'auto',
    height: '100%',
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'center',
    '& > div > div > div > div > div': {
      display: 'flex',
      justifyContent: 'center',
      alignItems: 'center',
    },
    '& .MuiCardMedia-root': {
      maxWidth: '80%',
      width: 'auto',
    },
  },
  '& .MuiBackdrop-root': {
    backgroundColor: 'rgba(0, 0, 0, 0.8)',
  },
  '& .MuiPaper-root': {
    backgroundColor: 'transparent',
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'center',
  },
});

export type FullMediaCarouselProps = Omit<DialogProps, 'onClose'> & {
  mediaList: Attachment[];
  initialIndex?: number;
  showName?: boolean;
  showDownload?: boolean;
  onClose?: () => void;
};

export const FullMediaCarousel: FC<FullMediaCarouselProps> = props => {
  const {
    open,
    mediaList,
    initialIndex = 0,
    showName = false,
    showDownload = false,
    onClose = () => null,
    ...dialogProps
  } = props;

  const [index, setIndex] = useState<number>(initialIndex);

  const { t } = useTranslation();

  useEffect(() => {
    setIndex(initialIndex);
  }, [open, initialIndex]);

  const fetchBlobUrl = () => {
    downloadUrl(mediaList[index]?.url, getDownloadName('humand_image_'));
  };

  const isNext = e => e.key === 'ArrowRight';
  const isPrev = e => e.key === 'ArrowLeft';

  const handleNext = () => index < mediaList.length - 1 && setIndex(index + 1);
  const handlePrev = () => index > 0 && setIndex(index - 1);
  const handleChange = now => setIndex(now);

  const handleKeyDown = e => {
    if (isNext(e) || isPrev(e)) {
      e.preventDefault();
    }
  };

  const handleKeyUp = e => {
    if (isNext(e)) {
      handleNext();
    } else if (isPrev(e)) {
      handlePrev();
    }
  };

  const height = getMaxHeight(mediaList);

  return (
    <Dialog
      onKeyUp={handleKeyUp}
      onKeyDown={handleKeyDown}
      onClose={onClose}
      open={open}
      {...dialogProps}
    >
      <Box className="content">
        <Box className="header">
          {showName && (
            <Typography className="title">{mediaList[index]?.name}</Typography>
          )}
          <Box className="actions">
            {showDownload && (
              <Tooltip
                className="downloadBtn"
                title={t('DOWNLOAD')}
              >
                <span>
                  <IconButton
                    aria-label={t('DOWNLOAD')}
                    className="large-btn"
                    onClick={fetchBlobUrl}
                  >
                    <DownloadIcon fontSize="inherit" />
                  </IconButton>
                </span>
              </Tooltip>
            )}
            <Tooltip
              className="closeBtn"
              title={t('CLOSE')}
            >
              <span>
                <IconButton
                  aria-label={t('CLOSE')}
                  onClick={onClose}
                  className="large-btn"
                >
                  <CloseIcon fontSize="inherit" />
                </IconButton>
              </span>
            </Tooltip>
          </Box>
        </Box>
        <Box
          onClick={onClose}
          sx={{ height: '100%' }}
        >
          <Carousel
            autoPlay={false}
            swipe={false}
            indicators={mediaList.length > 1}
            navButtonsAlwaysVisible
            navButtonsAlwaysInvisible={mediaList.length === 1}
            onChange={handleChange}
            index={index}
            fullHeightHover={false}
            cycleNavigation={false}
            animation="fade"
            duration={600}
            className="carousel"
            height={height}
            navButtonsProps={{
              className: 'large-btn',
            }}
            indicatorIconButtonProps={{
              style: {
                pointerEvents: 'none',
              },
            }}
          >
            {mediaList.map(media => (
              <MediaBase
                hasZoom
                key={media.url}
                media={media}
                onClick={e => e.stopPropagation()}
              />
            ))}
          </Carousel>
        </Box>
      </Box>
    </Dialog>
  );
};

export default FullMediaCarousel;
