import {useState, useEffect} from "react"
import FirebaseQuery from "../../firebase/firebaseQuery";
import {countryList} from "../../constants"; 


export interface DropdownProps {
    defaultValue?: string;
    required?: boolean;
    id?: string;
    disabled?: boolean,
    onValueChange?: (value: string) => void;
    value?: string;
    mode?: "default" | "modal"
    name?: string;
    search?: boolean | false
    data?: {key?: number, label: string, value: string}[]
    path?: string;
    label: string;
    size?: "small" | "medium" | "large";
    style?: any;
    errorText?: string;
  }
  
export function useDropdown(props: DropdownProps){
    const [value, setValue] = useState<string>(
        props.defaultValue || props?.name === "country" ? countryList[0] : ""
    );

    const firebaseQuery = new FirebaseQuery();

    const [data, setData] = useState<{key?: number, label: string, value: string}[]|undefined>(props.data);

    useEffect(() => {
        // Get items from database if none are given as children.
        if (!props.path) {
            return;
        }

        firebaseQuery.getDocsWhere(props.path).then((collectionResult: any) => {
            const items = Object.keys(collectionResult).map((key) => {
                const item = collectionResult[key];
                return {
                    label: item.name,
                    value: key,
                };
            });
            setData(items);
            setValue(props.defaultValue || "");
        });
    }, []);

    return ({...{value, setValue, data, setData}})
}