import React, {useEffect, useState} from 'react';
import CustomSelect, {CustomSelectProps} from "./CustomSelect";
import {instance} from "../../../../API/axios";
import SelectItem from "./SelectItem";
import {CustomSelectOptions} from "../../../../models/ReactComponents";


interface MakeCustomSelectFromEndpointProps extends Omit<CustomSelectProps, 'children'> {
    optionsApi: {
        model: string,
        param: {
            name: string | null,
            value: number | string | null
        }
    }
}


const MakeCustomSelectFromEndpoint = ({optionsApi, ...props}: MakeCustomSelectFromEndpointProps) => {



    const [options, setOptions] = useState<CustomSelectOptions>([])



    useEffect(() => {

        (async ()=>{



            let endpoint = 'api/dynamic/lookups/'+optionsApi.model
            if(optionsApi.param.name)
            {
                endpoint+=`/${optionsApi.param.name}/${optionsApi.param.value}`
            }
            const res = await instance.get(endpoint);


            // const newO:CustomSelectOptions = res.data.map((op:any) =>{
            //     return{
            //         value: op.value ?? op.id,
            //         name: op.name
            //     }
            //
            // })

            // props.handleChange(0)
            setOptions(res.data)
        })()


    }, [optionsApi.param.value])


    return (
        // @ts-ignore
        <CustomSelect

            {...props}
        >
            {
                options?.map(opt => {
                    return <SelectItem key={opt.value} value={opt.value}>{opt.name}</SelectItem>
                })
            }
        </CustomSelect>
    );
}

export default MakeCustomSelectFromEndpoint;
