/* eslint-disable no-underscore-dangle */
import * as React from 'react';
import { Platform, View } from 'react-native';
import { Button, Icon, Image, Div } from 'react-native-magnus';
import * as ImagePicker from 'expo-image-picker';
import useModel from 'flooks';

import request from '../utils/RequestUtils';
import { toastShow, toastHide } from '../utils/SystemUtils';

const _pickImage = (aspect) => {
  return ImagePicker.requestCameraRollPermissionsAsync()
    .then((res) => {
      if (!res.granted) {
        return Promise.reject('notAllod');
      } else {
        return ImagePicker.launchImageLibraryAsync({
          mediaTypes: ImagePicker.MediaTypeOptions.Images,
          allowsEditing: true,
          aspect: aspect || [1, 1],
          quality: 0.6,
          base64: true,
        });
      }
    })
    .then((res) => {
      if (!res.cancelled) {
        if (Platform.OS === 'web') {
          toastShow();
          return Promise.resolve(res.uri);
        }
        return Promise.resolve(res.base64);
      } else {
        return Promise.reject('cancel');
      }
    })
    .then((img) => {
      return request.post(`/upload/base64`, {
        data: { base64: img },
        requestType: 'form',
      });
    });
};

export default function ImagePickerCom({
  aspect = [1, 1],
  img,
  setImg,
  cancelEvent,
  h = 67,
  w = 67,
}) {
  return (
    <Div mr="sm" mb="sm">
      <Button
        bg="yellow200"
        h={h}
        w={w}
        rounded="xs"
        onPress={() => {
          _pickImage(aspect || [1, 1])
            .then((newImg) => {
              if (setImg) {
                setImg(newImg);
              }
            })
            .catch((e) => {
              console.log(e);
            })
            .finally(() => {
              toastHide();
            });
        }}
      >
        {!img && <Icon name="plus" color="white" fontSize="4xl" />}
        {!!img && (
          <Image
            h={h}
            w={w}
            rounded="xs"
            source={{
              uri: img,
            }}
          />
        )}
      </Button>
      {!!cancelEvent && (
        <Button
          bg="red500"
          h={16}
          w={16}
          rounded="circle"
          position="absolute"
          right={-5}
          top={-5}
          onPress={cancelEvent}
        >
          <Icon name="minus" fontFamily="AntDesign" color="#fff" />
        </Button>
      )}
    </Div>
  );
}
