import VendorController from "@/actions/App/Http/Controllers/VendorController";
import useReactSelectTheme from "@/hooks/use-react-select";
import { Vendor } from "@/types/vendor";
import axios from "axios";
import { useEffect, useState } from "react";
import AsyncSelect from "react-select/async";

type OptionType = {
    value: number;
    label: string;
    [key: string]: any;
};

interface Props {
    value?: number;
    onChange: (option: OptionType | null) => void;
    id?: string;
    placeholder?: string;
    isClearable?: boolean;
    isDisabled?: boolean;
}

export default function SelectVendor({ value, onChange, id = "id_vendor", placeholder = 'Pilih Vendor', isClearable = false, isDisabled = false, }: Props) {
    const reactSelectTheme = useReactSelectTheme();
    const [defaultValue, setDefaultValue] = useState<OptionType | null>(null);

    const loadOptions = async (inputValue: string): Promise<OptionType[]> => {
        const { data: res } = await axios.get(VendorController.index.url(), {
            params: {
                search: inputValue,
                json: true,
            }
        });

        return res?.data?.map((item: Vendor) => ({
            value: item.id_vendor,
            label: `${item.nama_vendor} | ${item.nama_pic} ${item.telp_pic ?? `-`}`,
            ...item,
        }));
    }

    useEffect(() => {
        const findData = async () => {
            const { data: item } = await axios.get(VendorController.show.url(value!), {
                params: {
                    json: true,
                },
            });

            setDefaultValue({
                value: item.id_vendor,
                label: `${item.nama_vendor} | ${item.nama_pic} ${item.telp_pic ?? `-`}`,
                ...item,
            });
        }

        if (!!value) {
            findData();
        } else {
            setDefaultValue(null);
        }
    }, [value]);

    return (
        <AsyncSelect
            inputId={id}
            cacheOptions
            defaultOptions
            loadOptions={loadOptions}
            value={defaultValue}
            onChange={(val) => onChange(!val ? null : val as OptionType)}
            styles={reactSelectTheme}
            placeholder={placeholder}
            isClearable={isClearable}
            isDisabled={isDisabled}
        />
    )
}
