import _ from "lodash";
import { get } from "lodash";
import PropTypes from "prop-types";
import React, { Component } from "react";
import ButtonSliderGroup from "../BuildingBlocks/ButtonSliderGroup";

/**
 * Creates a Button Slider Group to Change the Components Width
 */
class Width extends Component {
  constructor(props) {
    super(props);

    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(value, dbUpdate = true) {
    const {
      updateComponentStyle,
      onChange,
      settings,
      objCoordinates,
    } = this.props;
    const width = settings.properties.width ? settings.properties.width : 0;

    const newWidth = width === "100%" ? objCoordinates.width : width;

    let widthOffset = "auto";
    if (value === "SHRINK") widthOffset = newWidth - 10;
    else if (value === "GROW") widthOffset = newWidth + 10;

    // console.log({ width, newWidth, widthOffset, value });
    const newStyle = {
      width: Number.isInteger(value) ? value : widthOffset,
      maxWidth: "100%",
    };

    if (value === "100%")
      updateComponentStyle(
        settings.id,
        { width: "100%", maxWidth: "100%" },
        dbUpdate,
        !dbUpdate
      );
    else {
      updateComponentStyle(settings.id, newStyle, dbUpdate, !dbUpdate);
    }

    // console.log("Width Change", value, newStyle);
    onChange();
  }

  render() {
    const { settings } = this.props;

    // const maxCheckValue = _.get(settings, "properties.width") === "100%";
    let maxCheckValue = false;

    const maxWidth = _.get(settings, "properties.maxWidth", false);
    const width = _.get(settings, "properties.width", false);
    let value = width;
    if (width === "100%" && maxWidth) value = maxWidth;
    if (maxWidth === "100%" && width) value = width;

    if (width === "100%" && (!maxWidth || maxWidth === "inherit"))
      maxCheckValue = true;
    if (maxWidth === "100%" && (!width || width === "inherit"))
      maxCheckValue = true;
    if (width === "100%" && maxWidth === "100%") maxCheckValue = true;

    return (
      <div>
        <ButtonSliderGroup
          {...this.props}
          onChange={this.handleChange}
          text={get(this.props, "widthLabel", false) || "Width"}
          button1={{ icon: "remove", value: "SHRINK" }}
          button2={{ icon: "add", value: "GROW" }}
          minValue={10}
          maxValue={this.props.parentCoordinates.width || 2000}
          value={value || this.props.objCoordinates.width || 0}
          showMaxCheck
          maxCheckValue={maxCheckValue}
        />
      </div>
    );
  }
}

Width.propTypes = {
  onChange: PropTypes.func,
  updateComponentStyle: PropTypes.func.isRequired,
};

Width.defaultProps = {
  onChange: () => false,
};

export default Width;
