import {
  FormControl,
  InputLabel,
  MenuItem,
  Select,
  Typography,
} from "@mui/material";
import { TextInput } from "./TextInput";

export interface SelectOption {
  value?: string;
  label?: string;
  description?: string;
}

export function SelectInput(p: {
  value?: string;
  editable: boolean;
  label?: string;
  options: SelectOption[];
  onValueChange: (o?: string) => void;
}): React.ReactElement {
  if (!p.editable && !p.value) return <></>;

  if (!p.editable) {
    const value = p.options.find((o) => o.value === p.value)?.label ?? p.value;
    return <TextInput label={p.label} editable={p.editable} value={value} />;
  }

  return (
    <FormControl fullWidth variant="standard" style={{ marginBottom: "15px" }}>
      {p.label && <InputLabel>{p.label}</InputLabel>}
      <Select
        value={p.value ?? ""}
        label={p.label}
        onChange={(e) => p.onValueChange(e.target.value)}
      >
        {p.options.map((e) => (
          <MenuItem
            key={e.value}
            value={e.value}
            style={{ fontStyle: e.value === undefined ? "italic" : undefined }}
          >
            <div>
              {e.label ?? e.value}
              {e.description && (
                <Typography
                  component={"div"}
                  variant="caption"
                  style={{ whiteSpace: "normal" }}
                >
                  {e.description}
                </Typography>
              )}
            </div>
          </MenuItem>
        ))}
      </Select>
    </FormControl>
  );
}
