import React, { FC, useState } from 'react';
import { Image, Text, TouchableOpacity } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import * as FileSystem from 'expo-file-system';
import AddIcon from '../../../assets/icons/add.svg';

import { styles } from './styles';

//TODO: simple refactor + download photo

export const AvatarPicker: FC = () => {
  const [image, setImage] = useState('');

  const pickImage = async () => {
    // No permissions request is necessary for launching the image library
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1
    });

    console.log(result);

    if (!result.canceled) {
      setImage(result.assets[0].uri);

      // const uploadResult = await FileSystem.uploadAsync(
      //   'https://nomadmania.eu/webapi/user/join2',
      //   result.assets[0].uri,
      //   {
      //     httpMethod: 'POST',
      //     uploadType: FileSystem.FileSystemUploadType.MULTIPART,
      //     fieldName: 'demo_image',
      //     headers: {
      //       nmusername: 'test',
      //       nmemail: 'test@gmail.com',
      //       nmpassword: 'testpass123',
      //       nmfirstname: 'Name',
      //       nmlastname: 'Lastname',
      //       nmdateofbirth: `${new Date()}`,
      //       nmhomebase: 'testid10'
      //     }
      //   }
      // );
      //
      // console.log(JSON.stringify(uploadResult));
    }
  };
  return (
    <TouchableOpacity style={styles.avatarWrapper} onPress={pickImage}>
      {!image && (
        <>
          <AddIcon />
          <Text style={styles.textAvatar}>Upload Photo</Text>
        </>
      )}
      {image && (
        <Image source={{ uri: image }} style={{ width: 100, height: 100, borderRadius: 100 / 2 }} />
      )}
    </TouchableOpacity>
  );
};
