import FormUploader from '@material-hu/components/design-system/Uploader/form';

import { uploadImage, uploadVideo } from 'src/services/attachments';
import { FileTypes } from 'src/types/attachments';
import { getFileType, processAttachment } from 'src/utils/attachments';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { acknowledgementFormNames } from '../form';

export const SelectAcknowledgementMultimedia = () => {
  const { t } = useLokaliseTranslation('acknowledgements');

  const handleUpload = async (
    file: File,
    options?: { signal?: AbortSignal },
  ) => {
    try {
      const formFile = await processAttachment({ file });
      const fileType = getFileType(file);
      const uploadFn = fileType === FileTypes.IMAGE ? uploadImage : uploadVideo;
      const attachment = await uploadFn(formFile, { signal: options?.signal });

      return {
        status: 'success' as const,
        attachment: {
          url: attachment.url ?? '',
          name: attachment.name ?? '',
          size: attachment.size ?? '',
          bytes: file.size,
          type: attachment.type,
        },
        file,
      };
    } catch {
      return { status: 'error' as const, file };
    }
  };

  return (
    <FormUploader
      name={acknowledgementFormNames.attachments}
      uploaderProps={{
        label: t('multimedia_label'),
        acceptedTypes: ['image', 'video'],
        triggerOnChangeWhenUploading: true,
        uploadFunction: handleUpload,
      }}
    />
  );
};
