import { useMutation } from 'react-query';

import { useModal } from '@material-hu/hooks/useModal';
import Typography from '@material-hu/mui/Typography';

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

import PlusIcon from 'src/icons/Plus';
import * as libraryService from 'src/services/libraryService';
import { ArticleAttachment, Attachment } from 'src/types/attachments';
import { getFileType } from 'src/utils/filesUtils';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getFileNameExtension } from 'src/utils/stringUtils';

import BasicModal from 'src/components/BasicModal';
import FilesList from 'src/components/FilesList';

import AttachmentModal from './AttachmentModal';

type Props = {
  articleId: number;
  attachments?: Attachment[];
  refetch?: Function;
};

const Attachments = ({ articleId, attachments, refetch }: Props) => {
  const { t } = useLokaliseTranslation('general');
  const { enqueueSnackbar } = useHuSnackbar();

  const attachmentsList =
    attachments?.map(att => ({
      ...att,
      previewType: getFileType(getFileNameExtension(att.name)),
    })) || [];

  const mutation = useMutation(
    ({ attIndex, attNewName }: { attIndex: number; attNewName: string }) =>
      libraryService.editLibraryAttachmentName(
        articleId,
        attachmentsList[attIndex].id,
        attNewName,
      ),
    {
      onSuccess: () => {
        enqueueSnackbar({
          title: t('attachment.rename.success'),
          variant: 'success',
        });
        refetch();
      },
    },
  );

  const handleEditName = (attIndex: number, attNewName: string) => {
    mutation.mutate({ attIndex, attNewName });
  };

  const {
    showModal: showAttachmentModal,
    modal: attachmentModal,
    closeModal: closeAttachmentModal,
  } = useModal<{ attachment: ArticleAttachment }>(
    ({ attachment }) => (
      <AttachmentModal
        articleId={articleId}
        closeModal={closeAttachmentModal}
        refetch={refetch}
        originalAttachment={attachment}
      />
    ),
    { maxWidth: 'sm', fullWidth: true },
  );

  const deleteLibraryAttachmentMutation = useMutation(
    async ({ attachmentId }: { attachmentId: number }) => {
      const response = await libraryService.deleteLibraryAttachment(
        articleId,
        attachmentId,
      );
      refetch();
      return response;
    },
    {
      onSuccess: () => {
        enqueueSnackbar({
          title: t('attachment.delete.success'),
          variant: 'success',
        });
      },
    },
  );

  const {
    modal: deleteDocumentModal,
    showModal: showDeleteDocumentModal,
    closeModal: closeDeleteDocumentModal,
  } = useModal<{ attachmentId: number }>(attachmentId => (
    <BasicModal
      title={t('attachment.delete.confirm.title')}
      primaryButtonProps={{
        loading: deleteLibraryAttachmentMutation.isLoading,
        children: t('delete'),
        onClick: () =>
          deleteLibraryAttachmentMutation.mutateAsync(attachmentId, {
            onSettled: closeDeleteDocumentModal,
          }),
      }}
      secondaryButtonProps={{
        children: t('cancel'),
        onClick: closeDeleteDocumentModal,
      }}
    />
  ));

  return (
    <>
      {attachmentModal}
      {deleteDocumentModal}
      <Typography variant="h6">{t('attachments')}</Typography>
      {attachments ? (
        <FilesList
          files={attachmentsList}
          handleRemove={index =>
            showDeleteDocumentModal({ attachmentId: attachments[index].id })
          }
          handleEditName={handleEditName}
          sx={{ maxHeight: 200, overflow: 'auto' }}
        />
      ) : (
        <Typography
          variant="subtitle2"
          color="textSecondary"
          sx={{ my: 2 }}
        >
          {t('attachment.empty')}
        </Typography>
      )}
      <Button
        onClick={() => showAttachmentModal()}
        variant="outlined"
        sx={{ maxWidth: '1px' }}
      >
        <PlusIcon fontSize="small" />
      </Button>
    </>
  );
};
export default Attachments;
