import { Autocomplete, CircularProgress, TextField } from "@mui/material";
import { useEffect, useState } from "react";
import useRequest from "@/lib/hooks/useRequest";
import { debounce } from "@mui/material/utils";
import { GET_CAR_LIST_SEARCH } from "@/core/utils/routes";

const CarCode = ({ carCode, setCarCode, inputValueDefault = "", error }) => {
    const [inputValue, setInputValue] = useState(inputValueDefault);
    const [options, setOptions] = useState([]);
    const [loading, setLoading] = useState(false);
    const requestServer = useRequest();
    const fetchCarCodes = (inputValue, controller) => {
        const debouncer = debounce((query) => {
            if (!query || query?.length < 3) {
                setOptions([]);
                return;
            }
            setLoading(true);
            requestServer(`${GET_CAR_LIST_SEARCH}?machine_code=${query}`, "get", {
                requestOptions: { signal: controller.signal },
            })
                .then((response) => {
                    setOptions(response.data.data || []);
                })
                .catch(() => {
                    setOptions([]);
                })
                .finally(() => {
                    setLoading(false);
                });
        }, 500);
        debouncer(inputValue);
    };

    useEffect(() => {
        const controller = new AbortController();
        fetchCarCodes(inputValue, controller);
        return () => controller.abort();
    }, [inputValue]);

    return (
        <Autocomplete
            value={carCode}
            size="small"
            onChange={(event, newValue) => {
                setCarCode(newValue || null); // Set an empty string if no value is selected
            }}
            inputValue={inputValue}
            onInputChange={(event, newInputValue) => {
                setInputValue(newInputValue || ""); // Prevent inputValue from being null or undefined
            }}
            options={options}
            getOptionLabel={(option) => (typeof option === "string" ? option : option.machine_code)}
            isOptionEqualToValue={(option, value) => {
                if (!value) return false; // Handle null/undefined values
                if (value === "") return option.machine_code === ""; // Handle empty string case
                return option.machine_code === (value?.machine_code || value);
            }}
            loading={loading}
            loadingText="درحال جستجوی کد خودرو"
            noOptionsText={inputValue?.length < 3 ? "حداقل سه رقم از کد خودرو را وارد کنید" : "کد خودرویی یافت نشد"}
            fullWidth
            renderInput={(params) => (
                <TextField
                    {...params}
                    label="کد خودرو"
                    fullWidth
                    error={!!error} // نمایش خطا
                    helperText={error?.message} // پیام خطا
                    InputProps={{
                        ...params.InputProps,
                        endAdornment: (
                            <>
                                {loading ? <CircularProgress size="25px" color="inherit" /> : null}
                                {params.InputProps.endAdornment}
                            </>
                        ),
                    }}
                />
            )}
        />
    );
};
export default CarCode;
