import React, {memo} from 'react';
import {Keyboard} from 'react-native';
import {IconCamera} from '@tabler/icons-react-native';
import {Image as ImageType} from 'react-native-image-crop-picker';
import {useNewPost} from '@components/_custom/NewPost/hooks/useNewPost';
import {AttachmentType} from '@interfaces/attachments';
import {openCamera, uploadImage} from '@shared/utils/files';
import {ERROR} from '@shared/strings';
import {logImageCropped} from '@shared/utils/logs';

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

interface Props {
  hasMaxSize: boolean;
}

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

  const addImage = async (image: ImageType) => {
    setImages(prevImages =>
      prevImages.concat([
        {
          position: prevImages.length + videos.length,
          path: image.path,
          isLoading: true,
          type: AttachmentType.IMAGE,
          size: image.size.toString(),
          name: image.filename,
          url: image.path,
        },
      ]),
    );

    const {height, width, x, y} = image.cropRect!;
    const newImage = await uploadImage({...image, height, width});
    if (newImage !== ERROR) {
      setImages(prevImages =>
        prevImages.map(item =>
          item.path === image.path
            ? {...item, ...newImage, isLoading: false}
            : item,
        ),
      );
      setCurrentSize(prev => prev + image.size);
      logImageCropped('PublishPost', x, y);
    } else {
      setImages(prevImages =>
        prevImages.filter(item => item.path !== image.path),
      );
    }
  };

  const onAddImage = () => {
    Keyboard.dismiss();
    editor.blur();
    openCamera({save: addImage, options: {cropping: true}});
  };
  return (
    <BaseButton
      Icon={IconCamera}
      onPress={onAddImage}
      disabled={!!gif || hasMaxSize || requestEdit}
    />
  );
}

export default memo(AddImage);
