import { FontAwesome } from "@expo/vector-icons"
import { ImageInfo } from "expo-image-picker/build/ImagePicker.types"
import React, { useState } from "react"
import { ActivityIndicator, Image, ScrollView, Text, TouchableOpacity, View } from "react-native"
import { QueryStatus } from "react-query"
import { useAuth } from "../../../../state/external/auth-provider"
import { Landmark, LMPhoto } from "../../../../state/external/landmarks"
import { IconButton, PrimaryButton } from "../../../Buttons"
import { PhotoPicker } from "../../../PhotoPicker"

interface LandmarkPhotosProps {
    deletePhotoStatus: QueryStatus 
    addPhoto: (photo: LMPhoto) => void
    addPhotoStatus: QueryStatus
    toggleLmDetails: (state: boolean) => void
    landmark?: Landmark
    editingEnabled: boolean
    setUpdatedLandmark: (state: Landmark) => void
    updatedLandmark?: Landmark
    setSelectedImage: (index: number) => void
    tryDeletePhoto: (photoId: string) => void
    processingPhoto: boolean
    setProcessingPhoto: (state: boolean) => void
    profileId: string
}

export const LandmarkPhotos: React.FC<LandmarkPhotosProps> = (props) => {
    const {landmarkOwnedByUser} = useAuth()

    /**
     * Flag that toggles the photo source menu being displayed
    */
    const photoSourceMenuOpenedState = false
    const [photoSourceMenuOpened, togglePhotoSourceMenu] = useState<boolean>(photoSourceMenuOpenedState) 

    /**
     * Handles selection of a selected photo. Adds the photo data to the database.
    */
     const _onPhotoSelected = async (result: ImageInfo) => {
        togglePhotoSourceMenu(false)
        const photo: LMPhoto = {id: '', image_b64: 'data:image/png;base64,' + result.base64, height: result.height, width: result.width, landmark: props.landmark?.id}
        props.setProcessingPhoto(false)
        await props.addPhoto(photo)
    }

    /**
     * Sets given image as selected photo to be maximized on the screen
     * @param 
     */
    const maximizePhoto = (i: number): void => {
        if (!props.editingEnabled) {
            props.setSelectedImage(i)
        }
        else {
            console.warn('[LandmarkDetails]: Editing is enabled, can\'t maximize image')
        }
    }

    return (
        <>
            {
            props.deletePhotoStatus == 'loading' || 
            props.deletePhotoStatus == 'error' || 
            props.addPhotoStatus == "loading" || 
            props.addPhotoStatus == "error" ||
            props.processingPhoto ?
            <View style={{justifyContent: "space-evenly", alignItems: "center"}}>
                <Text style={{color: 'white', fontSize: 20, marginBottom: 40}}>{
                    props.deletePhotoStatus == "loading" || props.addPhotoStatus == "loading" ? "Loading photos" :
                    props.deletePhotoStatus == "error" || props.addPhotoStatus == "error" ? "There was an error loading photos" : 
                    props.processingPhoto ? "Processing photo" : null
                }</Text>
                {
                    props.deletePhotoStatus == 'loading' || props.addPhotoStatus == "loading" || props.processingPhoto ? <ActivityIndicator color='white' size="large"/> :
                    props.deletePhotoStatus == 'error' || props.addPhotoStatus == "error" ? <PrimaryButton text="Okay" style={{borderColor: 'white', borderWidth: 1}} onPress={() => props.toggleLmDetails(false)} /> : null
                }
            </View> : 
            <>
                <PhotoPicker 
                    multiple={true} 
                    menuType="alert" 
                    onReceivedPhotoResult={async result => await _onPhotoSelected(result)} 
                    photoSourceMenuOpened={photoSourceMenuOpened} 
                    onBeforeLaunchPicker={() => props.setProcessingPhoto(true)} 
                    cancel={() => {props.setProcessingPhoto(false) ; togglePhotoSourceMenu(false)}}/> 
                {props.landmark?.photos?.length > 0 ? 
                <>
                    <ScrollView nestedScrollEnabled={true} contentContainerStyle={{alignItems: 'center'}} style={{flexDirection: 'row', marginBottom: 5, alignSelf: 'center'}} horizontal={true}>
                        {props.landmark?.photos?.length < 5 && landmarkOwnedByUser(props.landmark) ? <IconButton style={{alignSelf: 'center', padding: 10, opacity: .5, marginLeft: 10}} color='white' size={30} icon="plus" onPress={() => togglePhotoSourceMenu(true)} />: null}
                        {props.landmark?.photos?.map((photo, i) => {    
                            
                            return (
                                <TouchableOpacity activeOpacity={1} key={i} style={{marginHorizontal: 1, padding: 14, zIndex: 11}} onPress={() => maximizePhoto(i)}>
                                    <Image style={{alignSelf: 'center', height: 300, width: 200}} source={{uri: 'data:image/png;base64,' + photo.image_b64}}/> 
                                    {landmarkOwnedByUser(props.landmark) ? <IconButton icon="times-circle" color="lightgray" style={{position: 'absolute', top: -2, right: 0}} size={25} onPress={() => props.tryDeletePhoto(photo.id)} /> : null}
                                </TouchableOpacity>
                            )
                        })}
                    </ScrollView>
                    
                </> : 
                <>
                {landmarkOwnedByUser(props.landmark) ?
                <TouchableOpacity style={{marginTop: 30, justifyContent: 'center', alignItems: 'center', opacity: .7}} onPress={() => {togglePhotoSourceMenu(true)}}>
                    <Text style={{fontSize: 20, marginBottom: 10, color: 'white'}}>Add photo of landmark</Text>
                    <FontAwesome name="plus" size={30} color='white' />
                </TouchableOpacity> : null}
                </>}
            </> }
        </>
    )
}