import React from "react";
import PropTypes from "prop-types";
import { makeStyles } from "@material-ui/core/styles";
import TextField from "@material-ui/core/TextField";
import { isEmpty } from "lodash";
import { generate } from "shortid";
var useStyles = makeStyles(function () {
  return {
    root: {
      display: "block !important",
      padding: "5px !important"
    }
  };
});

var SelectField = function SelectField(_ref) {
  var id = _ref.id,
      label = _ref.label,
      options = _ref.options,
      formik = _ref.formik,
      isRequired = _ref.isRequired;
  var classes = useStyles();
  var optionValues = options.values;

  if (options.values && !options.values[0].value) {
    optionValues = options.values.map(function (x) {
      return {
        value: x,
        label: x
      };
    });
  }

  if (options.limitByField && options.limitByValues && !isEmpty(formik.values[options.limitByField])) {
    var includeValues = options.limitByValues[formik.values[options.limitByField]];
    optionValues = optionValues.filter(function (x) {
      return includeValues.indexOf(x.value) !== -1;
    });

    if (!optionValues.some(function (e) {
      return e.value === formik.values[id];
    }) && formik.values[id] !== "") {
      formik.values[id] = "";
    }
  }

  return React.createElement(TextField, {
    required: isRequired,
    select: true,
    SelectProps: {
      "native": true
    },
    InputLabelProps: {
      shrink: true
    },
    id: id,
    label: label,
    helperText: formik.touched[id] ? formik.errors[id] : "",
    error: formik.touched[id] && Boolean(formik.errors[id]),
    value: formik.values[id] || "",
    onChange: formik.handleChange,
    onBlur: function onBlur() {
      formik.touched[id] = true;
      formik.handleBlur(id);
    },
    inputProps: {
      name: id,
      id: id
    },
    fullWidth: true
  }, React.createElement("option", {
    value: "",
    key: "",
    disabled: true
  }, "Select option"), optionValues.map(function (option) {
    return React.createElement("option", {
      value: option.value,
      key: generate(),
      className: classes.root
    }, option.label);
  }));
};

SelectField.propTypes = {
  id: PropTypes.string,
  isRequired: PropTypes.bool,
  label: PropTypes.string,
  options: PropTypes.shape({
    limitByField: PropTypes.string,
    limitByValues: function limitByValues(props, propName) {
      if (props.limitByField !== undefined && props[propName] === undefined) {
        return new Error("limitByValues array is required when limitByField is set");
      }
    },
    values: PropTypes.array
  }),
  formik: PropTypes.shape({})
};
export default SelectField;