import Slider from '@react-native-community/slider'
import React, { useEffect, useState } from "react"
import { Keyboard, Text, TextInput, TouchableOpacity, View } from "react-native"
import Modal from 'react-native-modal'
import Select from "react-native-multiple-select"
import { Checkbox } from "react-native-paper"
import { SafeAreaView } from 'react-native-safe-area-context'
import { useLandmarks } from '../../../../hooks/useLandmarks'
import { lmTypes } from "../../../../utils/GlobalUtils"
import { IconButton } from "../../../Buttons"
import { Separator } from "../../../Separator"
import { FilterLmTypes } from './FilterLmTypes'
import { FilterMinRating } from './FilterMinRating'

interface FilterPanelProps {
    setMinLmRating: (min: number) => void,
    setLmFilteredTypes: (type: number[]) => void,
    toggleFilter: (state: boolean) => void,
    minLmRating: number,
    lmFilteredTypes: number[],
    onlyOwned: boolean,
    visible: boolean,
    toggleOnlyOwned: (state: boolean) => void
}

/**
 * Modal panel that displays filter controls for the landmarks
 */
export const FilterPanel: React.FC<FilterPanelProps> = (props) => {
    /**
     * These three state variables are copies of their mapState counterparts, and are kept local to this component. They hold the values the sets user on this panel. 
     * They are kept local until "Apply filters is pressed", which will copy their values into their mapState counterparts and trigger the filtering
     * These are used locally instead of the mapState values in order to prevent the entire Map component from re-rendering every time one of these values is changed, 
     * greatly improving performance of this component
    */ 
    const [localMinRating, setLocalMinRating] = useState<number>(props.minLmRating)
    const [localFilterTypes, setLocalFilterTypes] = useState<number[]>(props.lmFilteredTypes)
    const [localOwned, toggleLocalOwned] = useState<boolean>(props.onlyOwned)

    /**
     * Resets all map filter values
     */
    const resetFilters = () => {
        props.setLmFilteredTypes([])
        props.setMinLmRating(0)
        props.toggleOnlyOwned(false)
    }

    /**
     * Resets only local filter values
     */
    const cancelChanges = () => {
        setLocalFilterTypes([])
        setLocalMinRating(0)
        toggleLocalOwned(false)
    }

    /**
     * Sets the map's filter state to the value of the local filter state, clears the local state, closes the panel and refetches the landmarks.
     */
    const applyChanges = () => {
        props.setMinLmRating(localMinRating)
        props.setLmFilteredTypes(localFilterTypes)
        props.toggleOnlyOwned(localOwned)
        props.toggleFilter(false)
        setLocalMinRating(0)
        setLocalFilterTypes([])
        toggleLocalOwned(false)
    }   

    /**
     * Sets the local state the map's current filter state. Runs when the panel is opened
     */
    const addExistingFilters = () => {
        toggleLocalOwned(props.onlyOwned)
        setLocalFilterTypes(props.lmFilteredTypes)
        setLocalMinRating(props.minLmRating)
    }

    // useEffects that update local settings based on parent changes (e.g. deleting a chip)
    useEffect(() => {
        setLocalMinRating(props.minLmRating)
    }, [props.minLmRating])

    useEffect(() => {
        setLocalFilterTypes(props.lmFilteredTypes)
    }, [props.lmFilteredTypes])

    useEffect(() => {
        toggleLocalOwned(props.onlyOwned)
    }, [props.onlyOwned])

    useEffect(() => {
        console.log('Filter panel visible: ' + props.visible)
    }, [props.visible])

    /**
     * State that holds keyboard open or close state
     */
     const [keyboardIsOpen, setKeyboardState] = useState<boolean>(false);

    /**
    * Map effects
    */
    useEffect(() => {
    const keyboardHideListener = Keyboard.addListener('keyboardDidHide', () => {
        setKeyboardState(false)
    })
    const keyboardShowListener = Keyboard.addListener('keyboardDidShow', () => {
        setKeyboardState(true)
    })
    return () => {
        keyboardHideListener.remove();
        keyboardShowListener.remove();
    }
    }, [])

    const OwnedFilter: React.FC = () => {
        return (
            <View style={{flexDirection: 'row', alignItems: 'center', marginBottom: 10}} >
                <Text>Only show my landmarks:</Text>
                <Checkbox status={localOwned ? 'checked' : 'unchecked'} onPress={() => toggleLocalOwned(!localOwned)} />
            </View>
        )
    }

    const FilterButtons: React.FC = () => {
        return (
            <View style={{marginTop: 20, flexDirection: 'row', alignSelf: 'flex-end'}}>
                <TouchableOpacity style={{marginRight: 40}} onPress={resetFilters}>
                    <Text>Reset</Text>
                </TouchableOpacity>
                <TouchableOpacity onPress={() => applyChanges()}>
                    <Text>Apply</Text>
                </TouchableOpacity>
            </View>
        )
    }

    return (
        <Modal 
            onModalWillShow={addExistingFilters}
            useNativeDriver={true}
            useNativeDriverForBackdrop={true}
            isVisible={props.visible} 
            animationIn={'slideInDown'} 
            animationOut={'slideOutUp'}
            style={{justifyContent: 'flex-start', height: '100%', width: '100%', margin: 0}}
            swipeDirection={'up'}
            onBackdropPress={() => {
                if (keyboardIsOpen) {
                    Keyboard.dismiss()
                }
                else {
                    cancelChanges();
                    props.toggleFilter(false);
                }
            }} >
                <SafeAreaView style={{padding: 20, backgroundColor: 'white'}}>
                    <FilterMinRating 
                        localMinRating={localMinRating} 
                        setLocalMinRating={setLocalMinRating} 
                        cancelChanges={cancelChanges} 
                        toggleFilter={props.toggleFilter} />
                    <FilterLmTypes localFilterTypes={localFilterTypes} setLocalFilterTypes={setLocalFilterTypes} />
                    <OwnedFilter />
                    <Separator color='grey' />   
                    <FilterButtons />
                </SafeAreaView> 
            </Modal>
        
    )
}