import { FC } from 'react';
import { useQuery } from 'react-query';

import 'src/components/dashboard/chat/i18n';

import MenuItem from '@material-hu/mui/MenuItem';

import { fetchBlob } from 'src/services/attachments';
import { Attachment } from 'src/types/attachments';
import { getDownloadAudioName } from 'src/utils/attachments';

import { attachmentKeys } from 'src/components/attachment/queries';
import { useTranslation } from 'src/components/dashboard/chat/i18n';

export type DownloadAudioOptionProps = {
  closeMenu: any;
  attachment: Attachment;
};

export const DownloadAudioOption: FC<DownloadAudioOptionProps> = props => {
  const { closeMenu, attachment } = props;

  const { t } = useTranslation();

  const { data } = useQuery(
    attachmentKeys.blob(attachment.url),
    () => fetchBlob(attachment),
    {
      refetchOnMount: false,
      placeholderData: { blob: null, blobUrl: null },
    },
  );

  const { blob, blobUrl } = data;

  return (
    <MenuItem
      onClick={closeMenu}
      component="a"
      href={blobUrl}
      download={getDownloadAudioName()}
      type={blob?.type}
      disabled={!blobUrl}
    >
      {t('DOWNLOAD_AUDIO')}
    </MenuItem>
  );
};

export default DownloadAudioOption;
