import React from "react";
import { FormControl, InputLabel, Select, MenuItem, FormHelperText } from "@mui/material";
import PropTypes from "prop-types";

function SelectInput({ field, disabled, onChange, error, helperText }) {
  let options = [];
if (field.Options && typeof field.Options === "string" && field.Options.trim().startsWith("[")) {
  try {
    options = JSON.parse(field.Options);
  } catch {
    console.warn(`Invalid JSON for field: ${field.Label}`);
    options = [];
  }
} else {
  options = [];
}

  return (
    <FormControl fullWidth disabled={disabled} error={error}>
      <InputLabel>{field.ProValue ? "" : field.Label}</InputLabel>
      <Select
        value={field.ProValue || ""}
        onChange={(e) => onChange(e.target.value)}
        id={`field-${field.Id}`}
      >
        {options.map((opt, idx) => (
          <MenuItem key={opt?.value || opt} value={opt?.value || opt}>
            {opt?.label || opt}
          </MenuItem>
        ))}
      </Select>
      <FormHelperText>{helperText}</FormHelperText>
    </FormControl>
  );
}

export default SelectInput;

SelectInput.propTypes = {
  field: PropTypes.shape({
    Id: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
    Label: PropTypes.string.isRequired,
    ProValue: PropTypes.string,
    Options: PropTypes.string,
  }).isRequired,
  disabled: PropTypes.bool,
  onChange: PropTypes.func.isRequired,
  error: PropTypes.bool,
  helperText: PropTypes.string,
};
