import React, { useState, useEffect } from 'react';
import Styled from 'styled-components/native';
import { SelectButton } from './SelectButton';
import { usePopup } from './Popup';
import { usePrevious } from '../Hooks';

export default PopupSelect = ({ navigation, path, popupProps = {}, style={}, emptyLabel='선택', defaultLabel='', labelProperty='Name', onSelect=null, editable=false }) => {
    const [data, setData] = useState({
        value: '',
        label: defaultLabel
    });
    const { openPopup } = usePopup();

    const isValidOnSelect = () => {
        if(onSelect && typeof onSelect === 'function') return true;
        return false;
    }
    const fireOnSelect = (result) => {
        if(isValidOnSelect()) {
            onSelect(result);
        }
    }

    const prevEditable = usePrevious(editable);
    const prevDefaultLabel = usePrevious(defaultLabel);
    useEffect(() => {
        //console.log(`>>>> PopupSelect - useEffect[editable,defaultLabel]`);
        if(typeof prevEditable !== 'undefined' && prevEditable != editable) {
            //console.log(`>>>> PopupSelect - useEffect - setData(${defaultLabel})`);
            setData({...data, label: defaultLabel});
        }
        if((typeof prevDefaultLabel === 'undefined' || !prevDefaultLabel) && !!defaultLabel) {
            //console.log(`>>>> PopupSelect - useEffect - setData(${defaultLabel})`);
            setData({...data, label: defaultLabel});
        }
    }, [editable, defaultLabel]);

    //console.log(`>>>> PopupSelect - data : `);
    //console.log(data);

    return (
        <SelectButton style={style}
            defaultLabel={emptyLabel} selectedLabel={data.label} editable={editable}
            onPress={() => {
                let props = {...popupProps};
                if(navigation) {
                    props = {...popupProps, navigation};
                }
                openPopup(path, props, (result) => {
                    setData({...data, 
                        label: result[labelProperty]
                    });
                    fireOnSelect(result);
                });
            }}
        />
    )
} 