import { Autocomplete, TextField } from "@mui/material";
import { useEffect, useRef, useState } from "react";

function AutoSearch({
  data,
  noneBg,
  inputValue,
  placeholder,
  handleSearch,
  setInputValue,
  setSelectedOption,
  debounce = 500,
}) {
  const typingTimeoutRef = useRef(null);
  const [localInput, setLocalInput] = useState(inputValue || "");

  useEffect(() => {
    setLocalInput(inputValue || "");
  }, [inputValue]);

  useEffect(() => {
    return () => {
      if (typingTimeoutRef.current) clearTimeout(typingTimeoutRef.current);
    };
  }, []);

  const onInputChange = (_, newInputValue) => {
    setLocalInput(newInputValue);

    if (setInputValue) setInputValue(newInputValue);

    if (typingTimeoutRef.current) clearTimeout(typingTimeoutRef.current);
    typingTimeoutRef.current = setTimeout(() => {
      handleSearch(newInputValue);
    }, debounce);
  };

  const onChange = (_, newValue) => {
    if (typingTimeoutRef.current) {
      clearTimeout(typingTimeoutRef.current);
      typingTimeoutRef.current = null;
    }

    const val = newValue
      ? typeof newValue === "string"
        ? newValue
        : newValue.name
      : "";
    setLocalInput(val);
    setSelectedOption && setSelectedOption(newValue);
    handleSearch(val);
    if (setInputValue) setInputValue(val);
  };

  return (
    <Autocomplete
      freeSolo
      options={data}
      getOptionLabel={(option) =>
        typeof option === "string" ? option : option.name
      }
      disableClearable
      inputValue={localInput}
      className="!w-full"
      onInputChange={onInputChange}
      onChange={onChange}
      renderOption={(props, option) => (
        <li {...props} key={option.id}>
          {option.name}
        </li>
      )}
      sx={{
        "& .MuiAutocomplete-input": {
          background: noneBg ? "" : "#ffffff !important",
        },
      }}
      renderInput={(params) => (
        <TextField
          {...params}
          variant="standard"
          placeholder={placeholder}
          dir="rtl"
          InputProps={{
            ...params.InputProps,
            disableUnderline: true,
            style: { height: "100%" },
          }}
          sx={{
            background: "transparent !important",
            "& .MuiInputBase-input": {
              background: "#FAFAFA",
              color: "#6C757D",
              padding: "0 16px",
              fontSize: "14px",
              fontFamily: "inherit",
            },
          }}
          className="!shadow-none !w-full !px-5 !h-full !text-[14px] md:!text-[16px] !min-w-[50%] !rounded-0 !font-normal"
        />
      )}
    />
  );
}

export default AutoSearch;
