import React, { useState, useEffect } from 'react';
import { StyleSheet, TouchableOpacity, TouchableWithoutFeedback, View, Text, Modal, FlatList } from 'react-native';
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';

const INIT_SUBCATEGORY = {
    id: 1,
    value: '',
    foreign_id: 0,
}

const SelectForm = ({
    inputTitle,
    placeholder,
    data,
    selectedData,
    onValueChange,
    subData,
    selectedSubData,
    onSubValueChange,
    onUpdateDataPress,
}) => {
    const [option, setOption] = useState([])
    const [subOption, setSubOption] = useState([])

    const [selectedOption, setSelectedOption] = useState({})

    const [subOptionShow, setSubOptionShow] = useState(false)
    const [modalOpen, setModalOpen] = useState(false)

    const onPressSelectBox = () => { setModalOpen(true) }

    const modalClose = () => { setModalOpen(false); }

    const onPressOption = (item) => {
        if (item.id === 0) {
            return null
        }
        if (subOption !== undefined) {
            if (subOptionShow) {
                onValueChange(selectedOption)
                onSubValueChange(item)
                modalClose()
            } else {
                setSelectedOption(item)
                setSubOptionByOptionId(item)
            }
        } else {
            onValueChange(item)
            modalClose()
        }
    }

    const setSubOptionByOptionId = (item) => {
        const newOption = subData.filter((subItem) => {
            if (subItem.foreign_id === item.id)
                return true;
        })
        if (newOption.length === 0) {
            onValueChange(item)
            onSubValueChange(INIT_SUBCATEGORY)
            modalClose()
        } else {
            newOption.unshift({id: 1, value: '기타'})
            if (newOption.length % 3 == 0) {
                setSubOption(newOption)
                setSubOptionShow(true)
            } else {
                for (let i = 0; i < (newOption.length % 3); i++) {
                    newOption.push(INIT_SUBCATEGORY)
                }
                setSubOption(newOption)
                setSubOptionShow(true)
            }
        }
    }
    
    const renderOptionItem = ({ item }) => (
        <TouchableOpacity onPress={() => onPressOption(item)} style={style.option}>
            <Text style={style.optionText} >
                {item.value}
            </Text>
        </TouchableOpacity>
    );

    useEffect(() => {
        setOption(data)
        setSubOption(subData)
        setSubOptionShow(false)
    }, [modalOpen])

    return (
        <View>
            <View style={style.container}>
                <View style={style.inputTitleArea}>
                    <Text style={style.inputTitle}>{inputTitle}</Text>
                </View>
                <View style={style.selectBox}>
                    <TouchableWithoutFeedback onPress={onPressSelectBox}>
                        <Text style={style.textStyle}>
                            {selectedData.value ?
                                selectedSubData?.value ?
                                    selectedData.value + ' < ' + selectedSubData.value
                                    : selectedData.value
                                : placeholder}
                        </Text>
                    </TouchableWithoutFeedback>
                </View>
            </View>

            <Modal
                transparent
                swipeDirection="down"
                animationType="slide"
                visible={modalOpen}
                onRequestClose={modalClose}
            >
                <View style={style.selectModalContainer}>
                    <TouchableWithoutFeedback onPress={modalClose}>
                        <View style={{ flex: 1 }} />
                    </TouchableWithoutFeedback>
                    <View style={style.selectModal}>
                        <View style={style.modalHeader}>
                            {subOptionShow ?
                                <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'center' }} >
                                    <MaterialCommunityIcons name='arrow-left' size={35} color='white' onPress={() => { setSubOptionShow(false); }} />
                                    <Text style={style.modalHeaderText}>{selectedOption.value}</Text>
                                </View>
                                :
                                <Text style={style.modalHeaderText}>{inputTitle}</Text>}
                            <View style={{ flexDirection: "row" }}>
                                <MaterialCommunityIcons name='playlist-edit' size={35} color='white' onPress={() => { modalClose(); setTimeout(() => { onUpdateDataPress() }, 500) }} />
                                <MaterialCommunityIcons name='close' size={35} color='white' onPress={modalClose} />
                            </View>
                        </View>
                        <View style={[style.modalBody]}>
                            <FlatList
                                data={subOptionShow ? subOption : option}
                                renderItem={renderOptionItem}
                                numColumns={3}
                                keyExtractor={item => item.id.toString()}
                            />
                        </View>
                    </View>
                </View>
            </Modal>
        </View>
    );
};

const style = StyleSheet.create({
    container: {
        height: 50,
        flexDirection: 'row',
        alignItems: "center",
        marginHorizontal: 10,
        marginVertical: 3,
        borderWidth: 1.5,
        borderStyle: "solid",
        borderColor: "#1467ff",
        borderRadius: 5,
        backgroundColor: "#f5f5f5",
    },
    inputTitleArea: {
        flex: 1,
    },
    inputTitle: {
        alignSelf: "center",
        color: "#1467ff",
        fontSize: 20,
    },
    selectStyle: {
        flex: 3,
        fontSize: 20,
    },
    selectBox: {
        flex: 3,
    },
    textStyle: {
        fontSize: 20,
    },
    selectModalContainer: {
        flex: 1,
        justifyContent: 'flex-end',
    },
    selectModal: {
        flex: 1,
    },
    modalHeader: {
        flex: 1,
        backgroundColor: '#4f4f4f',
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
    },
    modalHeaderText: {
        color: 'white',
        marginLeft: 25,
        fontSize: 20,
    },
    modalBody: {
        flex: 5,
        flexDirection: 'row',
        backgroundColor: '#f0f0f0',
    },
    option: {
        flex: 1,
        height: 50,
        borderWidth: 0.8,
        borderStyle: 'solid',
        borderColor: '#575757',
        backgroundColor: '#adadad',
        justifyContent: 'center',
        alignItems: 'center',
    },
    optionText: {
        fontSize: 20,
    }
})

export default SelectForm