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

import { styles } from './styles';
import { ImagePickerAsset } from 'expo-image-picker';

//TODO: simple refactor

type Props = {
  selectedAvatar: (avatarPath: ImagePickerAsset) => void;
  defaultAvatar?: string;
};

export const AvatarPicker: FC<Props> = ({ selectedAvatar, defaultAvatar }) => {
  const [image, setImage] = useState(defaultAvatar);

  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
    });

    if (!result.canceled) {
      setImage(result.assets[0].uri);
      selectedAvatar(result.assets[0]);
    }
  };
  return (
    <TouchableOpacity style={styles.avatarWrapper} onPress={pickImage}>
      {!image && (
        <>
          <AddIcon />
          <Text style={styles.textAvatar}>Upload Photo</Text>
        </>
      )}
      {image && (
        <Image
          source={{ uri: image ?? defaultAvatar }}
          style={{ width: 100, height: 100, borderRadius: 100 / 2 }}
        />
      )}
    </TouchableOpacity>
  );
};
