import { useState } from 'react';

import { type FileCardType } from '@material-hu/components/design-system/FileCard/types';

import { uploadOneFile } from 'src/services/attachments';
import { FileTypes } from 'src/types/attachments';

type UseDocumentSlotUploadParams = {
  slotIndex: number;
  onFileChange: (slotIndex: number, fileAssetId: number | null) => void;
};

export const useDocumentSlotUpload = ({
  slotIndex,
  onFileChange,
}: UseDocumentSlotUploadParams) => {
  const [cards, setCards] = useState<FileCardType[]>([]);

  const handleUpload = async (file: File): Promise<FileCardType> => {
    try {
      const result = await uploadOneFile({
        name: file.name,
        type: FileTypes.FILE,
        contentType: file.type,
        fileObject: file,
        size: file.size,
      });

      onFileChange(slotIndex, result.id);

      return {
        status: 'success',
        file,
        attachment: {
          url: result.url ?? '',
          name: result.name ?? '',
          type: result.type || FileTypes.FILE,
          size: result.size || '0 B',
          bytes: file.size,
        },
      };
    } catch {
      return { status: 'error', file };
    }
  };

  const handleChange = (updatedCards: FileCardType[]) => {
    setCards(updatedCards);
    const hasFile = updatedCards.some(c => c.status === 'success');
    if (!hasFile) {
      onFileChange(slotIndex, null);
    }
  };

  return { cards, handleUpload, handleChange };
};
