import React, { useEffect, useState, forwardRef, useImperativeHandle, Fragment, useRef } from 'react';
import { fetchGet, isCancel } from '~/Utils/fetch';
import { Selectbox } from '../UIControls/Selectbox';
import { useToast } from '../UIControls/Message';

const EntitySelect = forwardRef(({ 
    entity, useCheck=false, siteId='', id='', name='', fields='', where='', sort='id', defaultLabel='', auth={Business:false},
    style={}, onChange=()=>{}, defaultValue='', selectedValue='', selectedText='', emptyLabel=null, editable=true, hidden=false, excludes=[]
}, ref) => {

    const [items, setItems] = useState([]);
    const [loading, setLoading] = useState(true);
    const [value, setValue] = useState(selectedValue ? selectedValue : defaultValue);
    const [cancel, setCancel] = useState({cancel:() => {}});
    const selectRef = useRef();
    const { showMessage } = useToast();

    const handleChange = (item) => {
        //console.log('============ handleChange - item : ', item);
        onChange(item);
    }

    useEffect(() => {
        fetch();
    }, [where]);
    useEffect(() => {
        setValue(selectedValue);
    }, [selectedValue, editable]);

    useEffect(() => () => {
        cancel.cancel();
    }, []);

    useImperativeHandle(ref, () => ({
        openSelect: () => {
            selectRef.current.openSelect();
        },
    }), []);

    const fetch = () => {
        fetchGet(
            `api/entity/select?entity=${entity}&useCheck=${useCheck}&siteId=${siteId}&id=${id}&name=${name}&fields=${fields}&where=${encodeURIComponent(where)}&sort=${sort}&businessAuth=${auth.Business}`, 
            null, true, 15000, 
            (cancel) => { setCancel({cancel:cancel}) }
        ).then(res => {

            let items = [];
            for(let item of res) {
                if(excludes.find(v => v == item.Id)) continue;
                items.push({...item, label:item.Name, value:item.Id});
            }

            setLoading(false);
            setItems(items);
            if(items.length > 0) {
                if(selectedValue) {
                    setValue(selectedValue);
                } else if(defaultValue) {
                    setValue(defaultValue);
                } else if(emptyLabel) {
                    setValue('');
                } else if(!defaultLabel) {
                    setValue(items[0].value);
                }
            } else {
                setValue('');
            }
        })
        .catch(e => {
            console.log(e.message);
            showMessage(e.message);
            setLoading(false);
        });
    };

    //console.log('@@@@@@ value : ', value);
    
    return (
        <Selectbox defaultLabel={defaultLabel} selectedValue={value} selectedText={selectedText} emptyLabel={emptyLabel} onChange={handleChange} items={items} style={style} loading={loading} editable={editable} ref={selectRef} hidden={hidden} />
    );
});

export default EntitySelect;
