import * as React from "react";
import { get } from "lodash";

import Grid from "@material-ui/core/Grid";
import IconButton from "@material-ui/core/IconButton";
import Slider from "@material-ui/core/Slider";
import RemoveIcon from "@material-ui/icons/Remove";
import AddIcon from "@material-ui/icons/Add";

import { ButtonSliderGroupProps } from "./types";

/**
 * Renders two buttons and an optional slider
 *
 * Used for use cases like incrementing/decrementing a property, or setting a precise value (using the slider)
 */
export const ButtonSliderGroup: React.FC<ButtonSliderGroupProps> = ({
  value = 0,
  minValue = 0,
  maxValue,
  showSlider = false,
  label,
  toolTip,
  button1 = {
    command: "SHRINK",
    style: {},
  },
  button2 = {
    command: "GROW",
    style: {},
  },
  children,
  __testSliderValue = 111,
  onValueChange = () => false,
}) => {
  // const [sliderValue, setSliderValue] = React.useState<number>(value);

  const handleChange = (
    command: any,
    newValue: number | number[] | React.ReactText
  ) => {
    // console.log(newValue);
    onValueChange(command, newValue);
  };

  return (
    <fieldset
      data-testid="ButtonSliderGroup"
      title={toolTip}
      style={{ width: "100%" }}
    >
      <legend>{label}</legend>
      <Grid container spacing={2}>
        <Grid item>
          <IconButton
            data-testid="ButtonSliderGroup-Button1"
            onClick={() => handleChange(button1.command, value)}
            style={{ ...button1.style }}
          >
            {get(button1, "icon") || <RemoveIcon />}
          </IconButton>
        </Grid>

        {showSlider && (
          <Grid item xs>
            <Slider
              data-testid="ButtonSliderGroup-slider"
              value={value}
              onChange={(e, v) => handleChange(null, v)}
              aria-labelledby="continuous-slider"
              max={maxValue}
              min={minValue}
            />
          </Grid>
        )}
        <Grid item>
          <IconButton
            data-testid="ButtonSliderGroup-Button2"
            onClick={() => handleChange(button2.command, value)}
            style={{ ...button2.style }}
          >
            {get(button2, "icon") || <AddIcon />}
          </IconButton>
        </Grid>
      </Grid>

      {children}

      {/* This is for (jest) testing purposes */}
      {__testSliderValue && (
        <div
          data-testid="__testSliderValueUpdate"
          onClick={() => handleChange(null, __testSliderValue)}
        />
      )}
    </fieldset>
  );
};

export default ButtonSliderGroup;
