import MenuItem from "@mui/material/MenuItem";
import TextField from "@mui/material/TextField";
import { restorePlaceholderAfterAllSelected } from "@/shared/ui/selectAllBehavior.js";

export function RegionSelect({
  className,
  disabled = false,
  emptyLabel,
  label = "区域",
  loading = false,
  onChange,
  options = [],
  required = false,
  size = "small",
  value
}) {
  const isEmpty = !loading && options.length === 0;
  const selectedValue = value === undefined || value === null ? "" : String(value);
  const hasSelectedOption = !selectedValue || options.some((option) => option.value === selectedValue);

  const handleChange = (event) => {
    const nextValue = event.target.value;
    const selectedOption = nextValue === "" ? { label: emptyLabel } : options.find((option) => option.value === nextValue);
    onChange(nextValue);
    restorePlaceholderAfterAllSelected(selectedOption?.label);
  };
  const rootClassName = ["region-select", className].filter(Boolean).join(" ");

  return (
    <TextField
      className={rootClassName}
      disabled={disabled || loading}
      label={label}
      required={required}
      select
      size={size}
      value={selectedValue}
      onChange={handleChange}
    >
      {emptyLabel ? <MenuItem value="">{emptyLabel}</MenuItem> : null}
      {!hasSelectedOption ? <MenuItem value={selectedValue}>{selectedValue}</MenuItem> : null}
      {isEmpty ? (
        <MenuItem disabled value="__empty">
          暂无区域
        </MenuItem>
      ) : null}
      {options.map((option) => (
        <MenuItem key={option.value} value={option.value}>
          {option.label}
        </MenuItem>
      ))}
    </TextField>
  );
}
