/**
 * @deprecated Use `Attachments` from `@material-hu/components/composed-components/files/Attachments` instead.
 * Note: also uses `IconsMenu` from `@material-hu/components/deprecated` — that dependency goes away with migration.
 */
import { useModal } from '@material-hu/hooks/useModal';
import AddCircleOutlineIcon from '@material-hu/icons/material/AddCircleOutline';
import InsertDriveFileIcon from '@material-hu/icons/material/InsertDriveFile';
import Box from '@material-hu/mui/Box';
import { CardProps } from '@material-hu/mui/Card';
import CardContent from '@material-hu/mui/CardContent';
import CircularProgress from '@material-hu/mui/CircularProgress';
import List from '@material-hu/mui/List';
import ListItem from '@material-hu/mui/ListItem';
import ListItemIcon from '@material-hu/mui/ListItemIcon';
import ListItemText from '@material-hu/mui/ListItemText';
import Typography from '@material-hu/mui/Typography';

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

import excelIcon from 'src/assets/excel.svg';
import gifIcon from 'src/assets/gif.svg';
import pdfIcon from 'src/assets/pdf.svg';
import pptIcon from 'src/assets/powerpoint.svg';
import videoIcon from 'src/assets/video.svg';
import wordIcon from 'src/assets/word.svg';
import DownloadIcon from 'src/icons/Download';
import PencilAltIcon from 'src/icons/PencilAlt';
import XIcon from 'src/icons/X';
import { Attachment } from 'src/types/attachments';
import { insertIf } from 'src/utils/arrayUtils';
import { downloadFile, FileTypes, getFileType } from 'src/utils/filesUtils';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getFileNameExtension } from 'src/utils/stringUtils';

import EditFileName from './EditFileName';

type Props = {
  files: Attachment[];
  handleRemove?: Function;
  handleEditName?: Function;
  uploadOnDrop?: boolean;
  handleAddAttachment?: Function;
  sx?: CardProps['sx'];
  disabledAddAttachments?: boolean;
  inputProps?: any;
  showDownload?: boolean;
};

function FilesList({
  sx,
  disabledAddAttachments,
  files,
  handleRemove,
  handleEditName,
  inputProps = null,
  uploadOnDrop = false,
  handleAddAttachment,
  showDownload = true,
}: Props) {
  const { t } = useLokaliseTranslation('backoffice_only');

  const filesList = files.map(att => ({
    ...att,
    previewUrl:
      att.previewUrl || att.url || URL.createObjectURL(att.file || new Blob()),
    previewType: getFileType(getFileNameExtension(att.name) || ''),
  }));

  const { modal, showModal } = useModal<{
    index: number;
    filename: string;
    handleEditName: Function;
  }>(EditFileName, { fullWidth: true, maxWidth: 'sm' });

  return (
    <>
      <CardContent sx={{ ...sx }}>
        {files.length ? (
          <List>
            {modal}
            {filesList.map((file, index) => {
              let imgSrc = '';
              switch (file.previewType) {
                case FileTypes.VIDEO:
                  imgSrc = videoIcon;
                  break;
                case FileTypes.IMAGE:
                  imgSrc = file.previewUrl || file.url;
                  break;
                case FileTypes.DOC:
                  imgSrc = wordIcon;
                  break;
                case FileTypes.EXCEL:
                  imgSrc = excelIcon;
                  break;
                case FileTypes.PDF:
                  imgSrc = pdfIcon;
                  break;
                case FileTypes.PPT:
                  imgSrc = pptIcon;
                  break;
                case FileTypes.GIF:
                  imgSrc = gifIcon;
                  break;
                case FileTypes.FILE:
                  imgSrc = null;
                  break;
                default:
                  imgSrc = null;
              }
              return (
                <ListItem
                  key={file.url || file.previewUrl}
                  sx={{
                    border: 1,
                    borderColor: 'divider',
                    borderRadius: 1,
                    '& + &': {
                      mt: 1,
                    },
                  }}
                >
                  <ListItemIcon>
                    {imgSrc ? (
                      <img
                        src={imgSrc}
                        alt=""
                        width="30"
                        crossOrigin="anonymous"
                      />
                    ) : (
                      <InsertDriveFileIcon
                        fontSize="medium"
                        color="primary"
                        sx={{ mr: 1 }}
                      />
                    )}
                  </ListItemIcon>
                  <Box sx={{ flex: 1 }}>
                    <ListItemText
                      primary={file.name}
                      primaryTypographyProps={{
                        color: 'textPrimary',
                        variant: 'subtitle2',
                      }}
                      secondary={file.size}
                    />
                  </Box>
                  {!file.url && uploadOnDrop && <CircularProgress />}
                  <IconsMenu
                    options={[
                      ...insertIf(showDownload, {
                        onClick: () =>
                          downloadFile(file.previewUrl || file.url, file.name),
                        icon: <DownloadIcon fontSize="small" />,
                        label: t('backoffice_only:files_list.download'),
                        divider: !!handleEditName || !!handleRemove,
                      }),
                      ...insertIf(!!handleEditName, {
                        onClick: () =>
                          showModal({
                            index,
                            filename: file.name,
                            handleEditName,
                          }),
                        icon: <PencilAltIcon fontSize="small" />,
                        label: t('backoffice_only:files_list.edit'),
                      }),
                      ...insertIf(!!handleRemove, {
                        onClick: () => handleRemove(index),
                        icon: <XIcon fontSize="small" />,
                        label: t('backoffice_only:files_list.remove'),
                      }),
                    ]}
                  />
                </ListItem>
              );
            })}
          </List>
        ) : (
          handleAddAttachment && (
            <Typography
              variant="subtitle2"
              color="textSecondary"
              sx={{ mt: 2 }}
            >
              {t('backoffice_only:files_list.no_attachments')}
            </Typography>
          )
        )}
      </CardContent>
      {handleAddAttachment && (
        <Box sx={{ mt: 2, mb: 1, ml: 2 }}>
          <Button
            size="small"
            variant="outlined"
            disabled={disabledAddAttachments}
            startIcon={<AddCircleOutlineIcon />}
            onClick={() => handleAddAttachment()}
          >
            {t('backoffice_only:files_list.add_attachments')}
            {/* input for Mozilla Firefox working ok */}
            <input {...inputProps()} />
          </Button>
        </Box>
      )}
    </>
  );
}

export default FilesList;
