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

function AutoComplete({
  data = [], // همیشه آرایه ایمن
  noneBg = false,
  clearText,
  inputValue = "",
  placeholder = "",
  handleSearch,
  debounce = 400,
}) {
  const typingTimeoutRef = useRef(null);
  const [localInput, setLocalInput] = useState(inputValue);

  // sync بین inputValue بیرونی و مقدار محلی
  useEffect(() => {
    if (inputValue !== localInput) setLocalInput(inputValue || "");
  }, [inputValue]);

  // پاک‌سازی تایمر هنگام خروج
  useEffect(() => {
    return () => {
      if (typingTimeoutRef.current) clearTimeout(typingTimeoutRef.current);
    };
  }, []);

  // تایپ در input
  const onInputChange = (_, newValue) => {
    setLocalInput(newValue);
    if (typingTimeoutRef.current) clearTimeout(typingTimeoutRef.current);
    typingTimeoutRef.current = setTimeout(() => {
      handleSearch(newValue);
    }, debounce);
  };

  // انتخاب از بین گزینه‌ها
  const onChange = (_, newValue) => {
    if (typingTimeoutRef.current) clearTimeout(typingTimeoutRef.current);
    const val = typeof newValue === "string" ? newValue : newValue?.name || "";
    setLocalInput(val);
    handleSearch(val);
  };

  return (
    <Autocomplete
      freeSolo
      disableClearable
      options={Array.isArray(data) ? data : []}
      getOptionLabel={(option) =>
        typeof option === "string" ? option : option.name || ""
      }
      inputValue={localInput}
      onInputChange={onInputChange}
      onChange={onChange}
      noOptionsText="پزشکی یافت نشد"
      className="!w-full"
      renderOption={(props, option) => (
        <li {...props} key={option.id || option.name}>
          {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 AutoComplete;
