import { useTranslation } from 'react-i18next';

import FormUploader from '@design-system/Uploader/form';
import { isAbortError } from '@design-system/Uploader/utils';
import { type UploadFile } from '@src/types/attachments';

export type AddAttachmentFormContentProps = {
  upload?: UploadFile;
};

const AddAttachmentFormContent = ({
  upload,
}: AddAttachmentFormContentProps) => {
  const { t } = useTranslation();

  const handleUpload = async (
    file: File,
    options?: { signal?: AbortSignal },
  ) => {
    const { signal } = options ?? {};
    try {
      const attachment = upload ? await upload(file, { signal }) : undefined;
      if (!attachment) {
        return {
          status: 'error' as const,
          file,
        };
      }

      return {
        status: 'success' as const,
        attachment: {
          url: attachment.url || '',
          name: attachment.name || '',
          size: attachment.size || '',
          bytes: attachment.bytes || 0,
          type: attachment.type,
        },
        file,
      };
    } catch (err) {
      if (isAbortError(err)) throw err;
      return {
        status: 'error' as const,
        file,
      };
    }
  };

  return (
    <FormUploader
      name="fileCards"
      uploaderProps={{
        triggerOnChangeWhenUploading: true,
        acceptedTypes: ['image', 'pdf', 'msword', 'video'],
        uploadFunction: handleUpload,
        helperText: t('general:attachment.empty'),
        description: t('general:attachment.allowed_with_max_size', {
          maxSize: '100MB',
        }),
        fileSizeLimit: Infinity,
        slotProps: {
          fileCard: {
            showRemoveUploadingButton: false,
          },
        },
      }}
    />
  );
};

export default AddAttachmentFormContent;
