/* Copyright (C) Click & Push Accessibility, Inc - All Rights Reserved
 * Unauthorized copying of this file, via any medium is strictly prohibited
 * Proprietary and confidential
 * Written and maintained by the Click & Push Development team 
 * <dev@clicknpush.ca>, January 2022
 */

import FontAwesome from "@expo/vector-icons/build/FontAwesome";
import { observer } from "mobx-react-lite";
import React, { memo } from "react";
import { ActivityIndicator, Image, ImageSourcePropType, Keyboard, KeyboardAvoidingView, Platform, SafeAreaView, StyleSheet, Text, TextInput, TouchableOpacity, View } from 'react-native';
import { ScrollView } from "react-native-gesture-handler";
import Modal from 'react-native-modal';
import { Image as ImageSVG, Svg } from 'react-native-svg';
import ViewShot from "react-native-view-shot";
import { colors, lmTypes } from "../../../../utils/GlobalUtils";
import { IconButton, SecondaryButton } from "../../../Buttons";
import LandmarkTypePicker from "../../../LandmarkTypePicker";
import { PhotoPicker } from "../../../PhotoPicker";
import { Separator } from "../../../Separator";
import IndoorFloor from "../../indoor/indoor-floor";
import TouchOpaq from "../LandmarkDetailsPanel/TouchOpaq";
import { useAddLandmarkPanel } from "./add-landmark-panel.logic";
import { addLandmarkStore } from "./add-landmark-panel.store";

const imgWidth = 346;
const imgHeight = 448;
const imageDim = 25;

/**
 * Props for the {@link AddLandmarkPanel} component.
 */
export interface AddLandmarkProps {
    /**
     * Whether the landmark is being added at the current users location
     */
    landmarkAtCurrentLocation?: boolean;
    /**
     * A call back that toggles the visibility state of the {@link AddLandmarkPanel} modal. Passed down from {@link AddLandmarkPanel}.
     */
    setVisible: (state: boolean) => void;
    visible: boolean;
}

/**
 * Component that renders a form for adding a new {@link Landmark}. Contained within a [react-native-modal]{@link https://github.com/react-native-modal/react-native-modal}.
 * @component
 * @category Map
 */
const AddLandmarkPanel: React.FC<AddLandmarkProps> = observer(() => {
    const state = useAddLandmarkPanel()

    return (
        <Modal
            useNativeDriver={true}
            useNativeDriverForBackdrop={true}
            testID="addLMModal"
            avoidKeyboard={addLandmarkStore.photos?.length > 0}
            onBackdropPress={close}
            style={{ flex: 1, justifyContent: "flex-end", height: '100%', margin: 0}}
            isVisible={addLandmarkStore.panelVisible} >

            <KeyboardAvoidingView
                behavior={Platform.OS === "ios" ? "padding" : "height"}
                enabled={addLandmarkStore.photos?.length > 0}
                style={{ flex: 1, justifyContent: "flex-end"}}
            >
                <SafeAreaView style={{ backgroundColor: colors.red, height: state.determineModalHeight(), justifyContent: 'flex-end'}}>
                    {state.addLandmarkMutation.isIdle ?
                        <>
                            <View style={{
                                justifyContent: 'space-between',
                                alignItems: 'center',
                                flexDirection: "row",
                                marginBottom: 15,
                                borderBottomWidth: 1,
                                borderBottomColor: 'white',
                                paddingHorizontal: 20,
                                paddingVertical: 10,
                            }}
                            onTouchStart={() => Keyboard.dismiss()}
                            >
                                <Text style={{ color: 'white', fontSize: 15 }}>Add landmark here?</Text>
                                <TouchOpaq
                                    func={close}
                                    name={"close"}
                                    size={25}
                                    col={"white"}
                                />

                            </View>
                            <ScrollView>
                                <View style={{ paddingHorizontal: 20, paddingBottom: 20 }}>
                                    <TextInput
                                        returnKeyType="done"
                                        blurOnSubmit={true}
                                        multiline={true}
                                        style={{ backgroundColor: 'white', textAlignVertical: 'top', paddingHorizontal: 10, paddingTop: 10, paddingBottom: 10, marginBottom: 20, height: 150 }}
                                        placeholder="Description"
                                        onChangeText={value => addLandmarkStore.updatePendingLandmark({ ...addLandmarkStore.pendingLandmark, description: value })}>
                                        {addLandmarkStore.pendingLandmark?.description}
                                    </TextInput>
                                    <View style={{ flexDirection: 'row' }}>
                                        <LandmarkTypePicker 
                                            placeholder={{ label: "Select a landmark type...", value: 0 }}
                                            value={addLandmarkStore.pendingLandmark?.landmark_type}
                                            onValueChange={(value) => {
                                                if (value) {
                                                    addLandmarkStore.updatePendingLandmark({ ...addLandmarkStore.pendingLandmark, landmark_type: value, title: lmTypes[value].label })
                                                }
                                                else {
                                                    addLandmarkStore.updatePendingLandmark({ ...addLandmarkStore.pendingLandmark, landmark_type: undefined, title: 'no title' })
                                                }
                                            }}
                                            items={Object.keys(lmTypes)?.map(icon => {
                                                return (
                                                    { label: lmTypes[parseInt(icon)]?.label.toUpperCase(), value: icon, key: icon }
                                                )
                                            })}/>
                                        {addLandmarkStore.pendingLandmark?.landmark_type ? <Image source={lmTypes[addLandmarkStore.pendingLandmark.landmark_type].image} />
                                            : null}
                                    </View>
                                </View>
                                <View style={{ justifyContent: 'flex-end', flexDirection: 'row', paddingHorizontal: 20, marginTop: 5 }}> 
                                    <View style={{ flexDirection: 'row' }}>
                                        <TouchableOpacity onPress={async () => await state.submit()}><Text style={{ color: 'white', marginRight: 25, opacity: addLandmarkStore.landmarkReady ? 1 : .5 }}>Add</Text></TouchableOpacity>
                                        <TouchableOpacity onPress={close}><Text style={{ color: 'white', marginRight: 25 }}>Cancel</Text></TouchableOpacity>
                                    </View>
                                </View>
                                {addLandmarkStore.photos?.length > 0 && !state.keyboardOpened ?
                                    <>
                                        <ScrollView style={{ borderTopWidth: 1, borderColor: 'lightgray', paddingTop: 20, marginHorizontal: 20, flexDirection: 'row', marginBottom: 5, marginTop: 30 }} horizontal={true}>
                                            {addLandmarkStore.photos.map((photo, i) => {
                                                return (
                                                    <View key={i} style={{ marginHorizontal: 1, padding: 15 }}>
                                                        <IconButton style={{ position: 'absolute', top: 0, right: 0, zIndex: 10, }} icon="times-circle" color="lightgray" size={20} onPress={() => addLandmarkStore.deletePhoto(i)} />
                                                        <Image style={{ borderWidth: 1, alignSelf: 'center', height: 200, width: 200 * photo.width / photo.height }} source={{ uri: photo.image_b64 }} />
                                                    </View>
                                                )
                                            })}
                                            {addLandmarkStore.photos.length < 5 ? <IconButton style={{ alignSelf: 'center', padding: 10, opacity: .5, marginLeft: 10 }} color='white' size={30} icon="plus" onPress={() => state.togglePhotoSourceMenu(true)} /> : null}
                                        </ScrollView>
                                    </> : null}
                            </ScrollView>
                            {addLandmarkStore.photos?.length == 0 && !state.keyboardOpened ?
                            <>
                                <Separator color="white" style={{marginHorizontal: 20}} />
                                <TouchableOpacity style={{height: '30%', alignItems: 'center', justifyContent: 'center', marginBottom: 20}} onPress={() => {state.togglePhotoSourceMenu(true)}}>
                                    <Text style={{fontSize: 20, marginBottom: 10, color: 'white'}}>Add photo of landmark</Text>
                                    <FontAwesome name="plus" size={30} color='white' />
                                </TouchableOpacity> 
                            </>: null}
                        </> :
                        <View style={{ height: '100%', justifyContent: "space-evenly", alignItems: "center" }}>
                            <Text style={{ color: 'white', fontSize: 20 }}>{
                                state.addLandmarkMutation.isLoading ? 'Uploading landmark...' :
                                state.addLandmarkMutation.isError ? 'Something went wrong when trying to upload the landmark.' : null}
                            </Text>
                            {
                                state.addLandmarkMutation.isLoading ? <ActivityIndicator color='white' size="large" /> :
                                state.addLandmarkMutation.isError ? <SecondaryButton text="Okay" onPress={close} /> : null
                            }
                        </View>}
                </SafeAreaView>
                <PhotoPicker multiple={true} menuType='alert' photoSourceMenuOpened={state.photoSourceMenuOpened} onReceivedPhotoResult={result => addLandmarkStore.addPhoto(result)} cancel={() => state.togglePhotoSourceMenu(false)} />

                <ViewShot style={{ width: imgWidth + 20, height: imgHeight + 20, position: 'absolute', right: -2000 }} ref={state.capture} >
                    {/* {console.log("newLandmark is " + newLandmark)} */}
                    {addLandmarkStore.pendingLandmark == null || addLandmarkStore.pendingLandmark.floor == null || addLandmarkStore.pendingLandmark.landmark_type == null ? <></> :
                        <View style={styles.container}>
                            <Svg>
                                <IndoorFloor floorNum={addLandmarkStore.pendingLandmark.floor} />
                                <ImageSVG x={addLandmarkStore.pendingLandmark.longitude * imgWidth - 3} y={addLandmarkStore.pendingLandmark.latitude * imgHeight - 3} width={imageDim} height={imageDim} href={lmTypes[addLandmarkStore.pendingLandmark.landmark_type]['image'] as ImageSourcePropType} />
                            </Svg>
                        </View>
                    }
                </ViewShot>
            </KeyboardAvoidingView>
        </Modal>

    )
})

const styles = StyleSheet.create({
    container: {
        aspectRatio: 8 / 10,  // (caters to portrait mode) (width is 80% the value of height dimension)
        width: '100%',
        height: '100%',
        maxWidth: "100%",
        maxHeight: "100%",
        backgroundColor: "white",
        padding: 10
    }
})



export default memo(AddLandmarkPanel);
