import { 
  FormControl, 
  FormLabel, 
  Grid2 as Grid, 
  TextField 
} from "@mui/material";
import { Theme } from "@mui/material";
import { withStyles, WithStyles } from "@mui/styles";
import React from "react";

const styles = (theme: Theme) => {
  return ({
    borderedContainer: {
      padding: theme.spacing(1),
      marginBottom: theme.spacing(2),
      border: "1px solid rgba(255, 255, 255, 0.12)",
      borderRadius: "4px"
    }
  });
}
export interface Range {
  min?: number;
  max?: number;
}

interface Props extends WithStyles<typeof styles> {
  range: Range;
  onChange: (newRange: Range) => void;
  label: string;
  disabled?: boolean;
}

interface State {}

class RangeInput extends React.Component<Props, State> {
  handleChange = (field: "min" | "max", value: string) => {
    const { range, onChange } = this.props;

    let updatedRange = range;
    updatedRange[field] = value && !isNaN(parseFloat(value)) ? parseFloat(value) : undefined;
    onChange(updatedRange);
  };

  render() {
    const { classes, range, label, disabled } = this.props;

    return (
      <FormControl
        component="fieldset"
        variant="outlined"
        className={classes.borderedContainer}
        disabled={disabled}>
        <FormLabel component="legend">{label}</FormLabel>
        <Grid container direction="row" justifyContent="flex-start" spacing={2}>
          <Grid size={{ xs: 6 }} >
            <TextField
              type="text"
              label="Min"
              defaultValue={range.min}
              onChange={event => this.handleChange("min", event.target.value)}
            />
          </Grid>
          <Grid size={{ xs: 6 }}>
            <TextField
              type="text"
              label="Max"
              defaultValue={range.max}
              onChange={event => this.handleChange("max", event.target.value)}
            />
          </Grid>
        </Grid>
      </FormControl>
    );
  }
}

export default withStyles(styles)(RangeInput);
