import { Autocomplete, TextField } from '@mui/material';
import { useEffect, useState } from 'react';
import {useIntl } from "react-intl";

export default function Combo({
  valueName,
  disabled,
  form,
  dataList = [],
  filterOptions,
  getOptionLabel,
  isOptionEqualToValue,
  onInputChange,
  onChange,
  /** TextField-only: must not be spread onto Autocomplete (root is a div). */
  error,
  helperText,
  ...props
}) {
  const formValue = form.values[valueName] ?? null;
  const intl = useIntl();

  const [inputValue, setInputValue] = useState("");

  // optional: keep input text in sync when form value changes (e.g. after reload/reset)
  useEffect(() => {
    if (!formValue) return;
    try {
      const label = getOptionLabel ? getOptionLabel(formValue) : "";
      if (label != null) setInputValue(typeof label === "string" ? label : String(label));
    } catch {
      // ignore label errors
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [formValue]);

  const defaultIsEqual = (option, value) => option?.id != null && value?.id != null
    ? option.id === value.id
    : option === value;

  return (
    <Autocomplete
      {...props}
      disablePortal
      fullWidth
      id={valueName}
      disabled={disabled}
      // consider removing disableClearable if you allow empty
      disableClearable
      options={Array.isArray(dataList) ? dataList : []}
      value={formValue}
      inputValue={inputValue}
      filterOptions={filterOptions}
      getOptionLabel={(opt) => {
        if (opt == null) return "";
        let v;
        try {
          v = getOptionLabel ? getOptionLabel(opt) : String(opt);
        } catch {
          v = "";
        }
        if (v == null) return "";
        return typeof v === "string" ? v : String(v);
      }}
      isOptionEqualToValue={(option, value) => {
        return isOptionEqualToValue
          ? isOptionEqualToValue(option, value)
          : defaultIsEqual(option, value);
      }}
      onInputChange={(event, newValue) => {
        if (onInputChange) onInputChange(event, newValue, setInputValue);
        else setInputValue(newValue);
      }}
      onChange={(event, newValue) => {
        if (onChange) onChange(event, newValue);
        else form.setFieldValue(valueName, newValue);
      }}
      sx={{
        '& .MuiInputBase-root': { alignItems: 'center' },
        '& .MuiAutocomplete-endAdornment': { top: '50%', transform: 'translateY(-50%)' },
        '& .MuiOutlinedInput-root': { height: 40 },
        "& .MuiInputBase-input.Mui-disabled": {
          WebkitTextFillColor: "#000000",
          background: "#f8f8f8",
        },
      }}
      renderInput={(params) => (
        <TextField
          {...params}
          error={error}
          helperText={helperText}
          sx={{
            "& .MuiInputBase-input.Mui-disabled": {
              WebkitTextFillColor: "#000000",
              background: "#f8f8f8",
            },
          }}
        />
      )}
      clearText={intl.formatMessage({ id: "muiClear" })}
      closeText={intl.formatMessage({ id: "muiClose" })}
      openText={intl.formatMessage({ id: "muiOpen" })}
      noOptionsText={intl.formatMessage({ id: "muiNoOptions" })}
    />
  );
}
