import React from 'react';
import {IconFileUpload} from '@tabler/icons-react-native';
import {useNewPost} from '@components/index';
import {Attachment} from '@interfaces/attachments';
import {OnPressSendMessage} from '@modules/chat/interfaces';
import {sizeToBytes, uploadFile} from '@shared/utils/files';
import {MAX_SIZE_ERROR, ERROR} from '@shared/strings';

import {BaseButton} from '../BaseButton';

interface Props {
  hasMaxSize: boolean;
}

function SelectFile({hasMaxSize}: Props) {
  const {setFiles, setCurrentSize, editor, gif, post} = useNewPost();
  const requestEdit = !!post?._links?.requestEdit;

  const sendAttachment = (attachment: Attachment) => {
    setFiles(prevState => [...prevState, {...attachment, isLoading: true}]);
  };

  const handleUploadFile = async () => {
    editor.blur();
    const newFile = await uploadFile({
      sendAttachment: sendAttachment as OnPressSendMessage,
      classifyAudio: true,
    });
    if (newFile !== ERROR) {
      const newAttachment = newFile as Attachment;
      setFiles(prevState =>
        prevState.map(file =>
          file.isLoading && file.uri === newAttachment.uri
            ? newAttachment
            : file,
        ),
      );
      newFile !== MAX_SIZE_ERROR &&
        setCurrentSize(
          (prevState: number) => prevState + sizeToBytes(newFile.size),
        );
      return newFile;
    }
    setFiles(prevState => prevState.filter(file => !file.isLoading));
  };

  return (
    <BaseButton
      Icon={IconFileUpload}
      disabled={!!gif || hasMaxSize || requestEdit}
      onPress={handleUploadFile}
    />
  );
}

export default SelectFile;
