import { useNavigationState } from "@react-navigation/native";
import { ImageInfo } from "expo-image-picker";
import { useState, useEffect, useRef } from "react";
import { Dimensions, Keyboard, KeyboardEventName, Platform } from "react-native";
import { captureRef } from "react-native-view-shot";
import { LMPhoto, useAddLandmark } from "../../../../state/external/landmarks";
import { lmTypesIndoor, lmTypes } from "../../../../utils/GlobalUtils";
import { addLandmarkStore } from "./add-landmark-panel.store";

export const useAddLandmarkPanel = () => {
    const [photos, setPhotos] = useState<LMPhoto[]>([])
    const [photoSourceMenuOpened, togglePhotoSourceMenu] = useState<boolean>(false)
    const [keyboardOpened, setKeyboardOpened] = useState<boolean>(false);

    const addLandmarkMutation = useAddLandmark()

    const navigationState = useNavigationState(state => state)
    const [currentRoute, setCurrentRoute] = useState<string>()

    useEffect(() => {
        const currentRouteIndex = navigationState?.routes[0]?.state?.index
        const currentRouteName = navigationState?.routes[0]?.state?.routeNames[currentRouteIndex]
        setCurrentRoute(currentRouteName)
    }, [navigationState])

    
    useEffect(() => {
        let eventString = Platform.OS == "android" ? 'keyboardDidShow' : Platform.OS == "ios" ? 'keyboardWillShow' : null;
        if (eventString) {
            const validEventString: KeyboardEventName = eventString as KeyboardEventName;

            const keyboardDidShowListener = Keyboard.addListener(
                validEventString,
                () => {
                    setKeyboardOpened(true); // or some other action
                }
            );
            const keyboardDidHideListener = Keyboard.addListener(
                validEventString,
                () => {
                    setKeyboardOpened(false); // or some other action
                }
            );

            return () => {
                keyboardDidHideListener.remove();
                keyboardDidShowListener.remove();
            };
        }
    }, []);

    /**
     * Returns a height for the modal depending on if an image is maximzed, if the keyboard is opened, and if the current landmark has photos associated with it
     */
    const determineModalHeight = () => {
        if (keyboardOpened) {
            return Dimensions.get("window").height * .45
        }
        else if (photos?.length > 0)
            return Dimensions.get("window").height * .9
        else
            return Dimensions.get("window").height * .6
    }
    const capture: any = useRef();
    
    let currentLmTypes = lmTypes;
    if (currentRoute=="Indoor") {
        currentLmTypes = lmTypesIndoor;
    }

    useEffect(() => {
        /**
         * Resets the {@link addLandmarkAsync} mutation on successful add.
         * Embedded in a useEffect that listens to the {@link addLandmarkStatus} value from the {@link useLandmarks} hook.
         * @memberOf AddLandmark
         */
        const resetAddMutationOnSuccess = () => {
            if (addLandmarkMutation.isSuccess) {
                addLandmarkMutation.reset()
            }
        }
        resetAddMutationOnSuccess();
    }, [addLandmarkMutation.status]);

    useEffect(() => {
        addLandmarkMutation.reset();
    }, [addLandmarkStore.panelVisible]);

    /**
     * Calls {@link addLandmarkAsync} from {@link useLandmarks} to initate the process of adding a landmark, then closes the modal.
     */
    const submit = async () => {
        if (typeof addLandmarkStore.pendingLandmark.floor === 'number') {
            try {
                const uri = await captureRef(capture, {
                    format: "jpg",
                    quality: 1,
                    result: 'base64'
                })

                await addLandmarkMutation.mutateAsync({ landmark: addLandmarkStore.pendingLandmark, photos: photos, indoorMapSnapshotBase64: uri }); // pass it in here


            } catch (error) {
                console.error("Oops, snapshot failed", error);
            }
        }
        else {
            await addLandmarkMutation.mutateAsync({ landmark: addLandmarkStore.pendingLandmark, photos: photos });
        }

        addLandmarkStore.close();
    }

    const addPhoto = (result: ImageInfo) => {
        togglePhotoSourceMenu(false)
        const photo: LMPhoto = { id: '', image_b64: 'data:image/png;base64,' + result.base64, height: result.height, width: result.width, landmark: '' }
        setPhotos([...photos, photo])
    }

    const deletePhoto = (index: number) => {
        setPhotos(photos.filter((photo, i) => i != index))
    }

    return {deletePhoto, addPhoto, submit, determineModalHeight, photos, togglePhotoSourceMenu, photoSourceMenuOpened, keyboardOpened, addLandmarkMutation, navigationState, currentRoute, setCurrentRoute, currentLmTypes, capture}
}