import { FC, useState } from 'react';

import { useTranslation } from 'react-i18next';

import { MediaEditor } from 'signals-hu';

import AddIcon from '@material-hu/icons/material/AddRounded';
import CancelIcon from '@material-hu/icons/material/Cancel';
import CloseIcon from '@material-hu/icons/material/Close';
import ModeOutlinedIcon from '@material-hu/icons/material/ModeOutlined';
import SendIcon from '@material-hu/icons/material/SendOutlined';
import Box from '@material-hu/mui/Box';
import CardMedia from '@material-hu/mui/CardMedia';
import Dialog from '@material-hu/mui/Dialog';
import DialogActions from '@material-hu/mui/DialogActions';
import DialogContent from '@material-hu/mui/DialogContent';
import DialogTitle from '@material-hu/mui/DialogTitle';
import IconButton from '@material-hu/mui/IconButton';
import ImageListItem from '@material-hu/mui/ImageListItem';
import ImageListItemBar from '@material-hu/mui/ImageListItemBar';
import Tooltip from '@material-hu/mui/Tooltip';
import Typography from '@material-hu/mui/Typography';

import Button from '@material-hu/components/design-system/Buttons/Button';

import videoIconBig from 'src/assets/images/videoIconBig.webp';
import { Attachment } from 'src/types/attachments';
import { FileTypes } from 'src/types/attachments';
import { getFileIcon, getNewFileForReplacement } from 'src/utils/files';

import File from 'src/components/FormInputs/FormFile';

const { VIDEO, IMAGE, FILE } = FileTypes;

export type AttachmentConfirmDialogProps = {
  open: boolean;
  images?: Attachment[];
  videos?: Attachment[];
  files?: Attachment[];
  disabled?: boolean;
  isLoading?: boolean;
  onAccept?: () => void;
  onCancel?: () => void;
  onAddMore?: (files) => void;
  handleReplaceImage?: any;
  addMoreDisabled?: boolean;
  onDelete?: (file: Attachment, index: number) => void;
};

export const AttachmentConfirmDialog: FC<
  AttachmentConfirmDialogProps
> = props => {
  const {
    images = [],
    videos = [],
    files = [],
    disabled = false,
    onDelete,
    onCancel,
    onAccept,
    onAddMore,
    handleReplaceImage,
    isLoading = false,
    addMoreDisabled,
    ...dialogProps
  } = props;

  const [selectedIndex, setSelectedIndex] = useState(0);
  const [openImageEditor, setOpenImageEditor] = useState(false);
  const [isHovering, setIsHovering] = useState(false);

  const { t } = useTranslation('attachments');

  const attachments = [...images, ...videos, ...files];

  const focusedAttachment = attachments[selectedIndex];

  const handleDelete = (event, item, index) => {
    let indexToDelete = index;
    event.stopPropagation();
    if (selectedIndex >= indexToDelete) {
      const newIndex = indexToDelete > 0 ? selectedIndex - 1 : 0;
      setSelectedIndex(newIndex);
    }
    if (item.type === VIDEO) {
      indexToDelete = indexToDelete - images.length;
    } else if (item.type === FILE) {
      indexToDelete = indexToDelete - images.length - videos.length;
    }
    onDelete(item, indexToDelete);
  };

  const handleAccept = () => {
    setSelectedIndex(0);
    onAccept();
  };

  const handleCancel = () => {
    setSelectedIndex(0);
    onCancel();
  };

  const handleOnDone = data => {
    const newFile = getNewFileForReplacement(focusedAttachment, data);
    handleReplaceImage(focusedAttachment, newFile, selectedIndex);
  };

  const miniIconToShow = item =>
    ({
      [FILE]: getFileIcon(item),
      [VIDEO]: videoIconBig,
      [IMAGE]: item.url,
    })[item.type];

  return (
    <Dialog
      maxWidth="lg"
      PaperProps={{ style: { width: '900px' } }}
      {...dialogProps}
    >
      <DialogTitle>
        <IconButton onClick={handleCancel}>
          <CloseIcon />
        </IconButton>
      </DialogTitle>
      <DialogContent>
        {focusedAttachment?.type === 'FILE' ? (
          <Box
            sx={{
              height: '250px',
              width: '100%',
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              justifyContent: 'center',
            }}
          >
            <img
              alt="fileIcon"
              src={getFileIcon(focusedAttachment)}
              style={{ marginBottom: '10px' }}
            />
            <Typography
              variant="h6"
              style={{ marginBottom: '2px' }}
            >
              {t('no_preview')}
            </Typography>
            <Typography variant="body2">{`${focusedAttachment?.size} - ${focusedAttachment?.name?.split('.').pop()}`}</Typography>
          </Box>
        ) : (
          <Box
            sx={{
              position: 'relative',
              height: '400px',
              width: '100%',
              display: 'flex',
              justifyContent: 'center',
            }}
          >
            <CardMedia
              onMouseEnter={() => setIsHovering(true)}
              onMouseLeave={() => setIsHovering(false)}
              src={focusedAttachment?.url}
              component={focusedAttachment?.type === VIDEO ? 'video' : 'img'}
              alt={focusedAttachment?.name}
              sx={{
                mb: 2,
                borderRadius: '16px',
                objectFit: 'contain',
                width: 'fit-content',
                height: '100%',
              }}
              controls
            />
            <IconButton
              className="icon-button"
              onMouseEnter={() => setIsHovering(true)}
              onClick={() => setOpenImageEditor(true)}
              sx={{
                position: 'absolute',
                top: 'calc(50% - 18px)',
                left: 'calc(50% - 18px)',
                opacity: isHovering ? 1 : 0,
                transition: 'opacity 0.3s ease',
                backgroundColor: '#00000099',
                borderRadius: '100%',
                width: '44px',
                height: '44px',
                ':hover': {
                  backgroundColor: '#00000099',
                },
              }}
            >
              <ModeOutlinedIcon sx={{ color: '#FFFFFF' }} />
            </IconButton>
          </Box>
        )}
        <Box
          sx={{
            display: 'flex',
            flexDirection: 'row',
            justifyContent: 'center',
            gap: '20px',
            alignItems: 'end',
          }}
        >
          {attachments.map((item, index) => (
            <ImageListItem
              onClick={() => setSelectedIndex(index)}
              key={item.url}
              sx={{
                cursor: 'pointer',
                width: '56px !important',
                height: '56px !important',
                mr: 1,
                mt: 1,
              }}
            >
              <img
                src={miniIconToShow(item)}
                alt={item.name}
                style={{
                  objectFit: 'contain',
                  width: '100%',
                  height: '100%',
                  padding: item.type !== IMAGE ? '6px' : '0',
                  borderRadius: '6px',
                  border: index === selectedIndex ? '2px solid #1565C0' : '',
                  filter: item.type === VIDEO ? 'opacity(80%)' : 'none',
                }}
              />
              <ImageListItemBar
                sx={{ backgroundColor: 'transparent' }}
                position="top"
                actionIcon={
                  <Tooltip title={t('eliminate')}>
                    <IconButton
                      aria-label={t('eliminate')}
                      sx={{
                        pt: 0,
                        pr: 0,
                        mt: -1,
                        mr: -1,
                        '& svg': {
                          backgroundColor: 'white',
                          borderRadius: '50%',
                        },
                      }}
                      disabled={disabled}
                      onClick={event => handleDelete(event, item, index)}
                    >
                      <CancelIcon />
                    </IconButton>
                  </Tooltip>
                }
              />
            </ImageListItem>
          ))}
          {!addMoreDisabled && attachments.length < 10 && (
            <File
              name="multimedia"
              inputProps={{
                multiple: true,
                accept: 'video/*, .jpg, .png',
              }}
              title={t('attach_image_file')}
              disabled={isLoading}
              type={VIDEO || IMAGE}
              iconSx={{
                padding: '0',
                width: '56px',
                height: '56px',
                borderRadius: '8px',
                border: '1px solid #E0E0E0',
              }}
              icon={<AddIcon />}
              onChange={onAddMore}
              multimediaSize={images.length + videos.length + files.length}
              multiple
            />
          )}
        </Box>
      </DialogContent>
      <DialogActions>
        <Tooltip title={t(isLoading ? 'sending_info' : 'send')}>
          <span>
            <Button
              sx={{ mb: 1, mr: 1 }}
              disabled={isLoading}
              onClick={handleAccept}
              variant="contained"
              startIcon={<SendIcon />}
            >
              {t(isLoading ? 'sending' : 'send')}
            </Button>
          </span>
        </Tooltip>
      </DialogActions>
      {openImageEditor && (
        <MediaEditor
          imageSrc={focusedAttachment?.url}
          isSending={false}
          onClose={() => setOpenImageEditor(false)}
          onDone={({ data }) => handleOnDone(data)}
        />
      )}
    </Dialog>
  );
};

export default AttachmentConfirmDialog;
