import VendorKendaraanController from "@/actions/App/Http/Controllers/VendorKendaraanController";
import useReactSelectTheme from "@/hooks/use-react-select";
import { VendorKendaraan } 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;
    idVendor?: number;
    placeholder?: string;
    isClearable?: boolean;
    isDisabled?: boolean;
}

export default function SelectVendorKendaraan({ value, onChange, id = "id_kendaraan", idVendor, placeholder = 'Pilih Kendaraan', isClearable = false, isDisabled = false, }: Props) {
    const reactSelectTheme = useReactSelectTheme();
    const [defaultValue, setDefaultValue] = useState<OptionType | null>(null);
    const [key, setKey] = useState(0);

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

        return res?.data?.map((item: VendorKendaraan) => ({
            value: item.id_kendaraan,
            label: `${item.specs ?? `-`} | ${item.nopol ?? `-`}`,
            ...item,
        }));
    }

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

            setDefaultValue({
                value: item.id_kendaraan,
                label: `${item.specs ?? `-`} | ${item.nopol ?? `-`}`,
                ...item,
            });
        }

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

    // Reset component ketika idVendor berubah
    useEffect(() => {
        setDefaultValue(null);
        setKey(prev => prev + 1); // Force re-render AsyncSelect
        onChange(null); // Clear selection
    }, [idVendor, onChange]);

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