import { Autocomplete, TextField } from "@mui/material";

function AutoCompleteSearch({
  data,
  noneBg,
  clearText,
  inputValue,
  placeholder,
  handleSearch,
  setInputValue,
  setSelectedOption,
}) {
  const clearIndicatorProps = clearText
    ? {
        clearIndicator: {
          onClick: () => {
            clearText();
          },
        },
      }
    : {};

  return (
    <Autocomplete
      freeSolo
      options={data}
      getOptionLabel={(option) => option.name}
      inputValue={inputValue}
      className="!w-full"
      onInputChange={(_, newInputValue) => {
        setInputValue && setInputValue(newInputValue);
        handleSearch(newInputValue);
      }}
      onChange={(_, newValue) => {
        setSelectedOption && setSelectedOption(newValue);
        handleSearch(newValue ? newValue.name : "");
      }}
      componentsProps={clearIndicatorProps}
      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 AutoCompleteSearch;
