import { FC } from 'react';

import { IconDownload, IconLink } from '@material-hu/icons/tabler';

import HuMenuList from '@material-hu/components/composed-components/MenuList';
import useHuSnackbar from '@material-hu/components/design-system/Snackbar';

import useCopyUrl from 'src/hooks/useCopyUrl';
import { FileTypes } from 'src/types/attachments';
import { type File } from 'src/types/files';
import { insertIf } from 'src/utils/arrays';
import { downloadUrl } from 'src/utils/files';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { filesRoutes } from '../routes';

export type FileMenuProps = {
  file: File;
};

export const FileMenu = (props: FileMenuProps) => {
  const { enqueueSnackbar } = useHuSnackbar();
  const { copyUrlToClipboard } = useCopyUrl();

  const { file } = props;
  const { t } = useLokaliseTranslation('files');

  const handleCopyFolderUrl = () => {
    copyUrlToClipboard(filesRoutes.detail(file.id));
    enqueueSnackbar({
      title: t('link_copied'),
      variant: 'success',
    });
  };

  const handleDownloadFile = () => {
    downloadUrl(file.source!, file.name);
    enqueueSnackbar({
      title: t('file_downloaded'),
      variant: 'success',
    });
  };

  const options = [
    ...insertIf(file.type === FileTypes.FILE, {
      Icon: IconDownload,
      title: t('download'),
      onClick: handleDownloadFile,
    }),
    ...insertIf(file.type === FileTypes.FOLDER, {
      Icon: IconLink,
      title: t('copy_link'),
      onClick: handleCopyFolderUrl,
    }),
  ];

  return <HuMenuList options={options}></HuMenuList>;
};

export default FileMenu;
