import React, {memo} from 'react';
import {Keyboard} from 'react-native';
import {IconVideo} from '@tabler/icons-react-native';
import {useNewPost} from '@components/_custom/NewPost/hooks/useNewPost';
import {AttachmentType, ImageOrVideoAttachment} from '@interfaces/attachments';
import {openCamera, uploadVideo} from '@shared/utils/files';
import {ERROR} from '@shared/strings';

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

interface Props {
  hasMaxSize: boolean;
}

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

  const addVideo = async (video: ImageOrVideoAttachment) => {
    setVideos(prevVideos =>
      prevVideos.concat([
        {
          position: images.length + prevVideos.length,
          path: video.path,
          isLoading: true,
          type: AttachmentType.VIDEO,
          size: video.size.toString(),
          name: video.filename,
          url: video.path,
        },
      ]),
    );
    const newVideo = await uploadVideo(video);
    if (newVideo !== ERROR) {
      setVideos(prevVideos =>
        prevVideos.map(item =>
          item.path === video.path
            ? {...item, ...newVideo, isLoading: false}
            : item,
        ),
      );
      setCurrentSize(prev => prev + video.size);
    } else {
      setVideos(prevVideos =>
        prevVideos.filter(item => item.path !== video.path),
      );
    }
  };

  const onAddVideo = () => {
    Keyboard.dismiss();
    editor.blur();
    openCamera({
      save: addVideo,
      options: {mediaType: 'video'},
    });
  };

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

export default memo(AddVideo);
