import * as ImagePicker from "expo-image-picker"
import { ImageInfo } from "expo-image-picker/build/ImagePicker.types"
import React, { useEffect, useState } from "react"
import {Alert, Platform, Text} from 'react-native'
import { Menu, MenuOption, MenuOptions, MenuTrigger, renderers } from "react-native-popup-menu"
import { colors, getMediaPermissions } from "../utils/GlobalUtils"
const {SlideInMenu} = renderers

export const PhotoPicker: React.FC<{photoSourceMenuOpened: boolean, cancel: () => void, onBeforeLaunchPicker?: () => void, onReceivedPhotoResult?: (result: ImageInfo) => void, menuType: 'slideup' | 'alert', multiple: boolean}> = ({photoSourceMenuOpened, cancel, onBeforeLaunchPicker, onReceivedPhotoResult, menuType, multiple}) => {

    useEffect(() => {
        if (photoSourceMenuOpened && menuType ==  'alert') {
            showAlert()
        }
    }, [photoSourceMenuOpened])

    const showAlert = () => {
        if (Platform.OS == 'android') {
            Alert.alert(
                "Pick photo source", 
                "Where would like to get the photo from?",
                [
                    {text: 'Cancel', onPress: cancel, style: 'cancel'},
                    {text: 'Camera', onPress: () => selectNewPhoto('camera')},
                    {text: 'Library', onPress: () => selectNewPhoto('library')},
                ],
                {onDismiss: cancel, cancelable: true})
        }
        else if (Platform.OS == 'ios') {
            Alert.alert(
                "Pick photo source", 
                "Where would like to get the photo from?",
                [
                    {text: 'Camera', onPress: () => selectNewPhoto('camera')},
                    {text: 'Library', onPress: () => selectNewPhoto('library')},
                    {text: 'Cancel', onPress: cancel, style: 'cancel'},
                ],
                {onDismiss: cancel, cancelable: true})
        }

    }

    const selectNewPhoto = async (imageSource: 'camera' | 'library') => {
        if (onBeforeLaunchPicker) {
            onBeforeLaunchPicker()
        }
    
        const granted = await getMediaPermissions();
        console.log(granted)
        if (granted) {
            console.log(multiple)
            const imageOptions: ImagePicker.ImagePickerOptions = {
                mediaTypes: ImagePicker.MediaTypeOptions.Images,
                base64: true,
                allowsEditing: true,
                aspect: [4, 3],
                quality: 1,
                allowsMultipleSelection: multiple
            }

            let result: ImagePicker.ImagePickerResult = {cancelled: true}
    
            if (imageSource === 'camera') {
                result = await ImagePicker.launchCameraAsync(imageOptions)
            }
    
            if (imageSource === 'library') {
                result = await ImagePicker.launchImageLibraryAsync(imageOptions)
            }
        
            if (!result.cancelled) {
                onReceivedPhotoResult(result as ImageInfo)
            }
            else {
                cancel()
            }
        }
        else {
            Alert.alert("You need to grant camera/storage permissions to upload an image.")
        }
    }

    return (
        <>
        {menuType == 'slideup' ?
        <Menu renderer={SlideInMenu} style={{zIndex: 10}} opened={photoSourceMenuOpened} onBackdropPress={cancel} >
            <MenuTrigger />
            <MenuOptions optionsContainerStyle={{backgroundColor: colors.red}}>
                <MenuOption onSelect={async () => await selectNewPhoto('camera')} style={{padding: 20, alignItems: 'center', borderBottomWidth: 1, borderColor: 'white', marginHorizontal: 10}} >
                    <Text style={{fontSize: 20, color: 'white'}}>Select from camera</Text>
                </MenuOption>
                <MenuOption onSelect={async () => await selectNewPhoto('library')} style={{padding: 20, alignItems: 'center'}} >
                    <Text style={{fontSize: 20, color: 'white'}}>Select from library</Text>
                </MenuOption>
            </MenuOptions>
        </Menu> : null}
        </>
    )
}