import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _regeneratorRuntime from "@babel/runtime/regenerator";

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

import React, { useState } from "react";
import PropTypes from "prop-types";
import ReactCSSTransitionGroup from "react-addons-css-transition-group";
import isEmpty from "lodash-es/isEmpty";
import Grid from "../Grid";
import TextField from "../TextField";
import Chip from "../Chip";
import Link from "../Link";
import InputAdornment from "../InputAdornment";
import IconButton from "../IconButton";
import Alert from "../Icon/Alert";
import Tooltip from "../Tooltip";
import Circle from "../Icon/Circle";
import Enter from "../Icon/Enter";
import Typography from "../Typography";
import getClasses from "./styles";

var ChipTextField = function ChipTextField(props) {
  var classes = getClasses();
  var type = props.type,
      chips = props.chips,
      addChip = props.addChip,
      deleteChip = props.deleteChip,
      clearAll = props.clearAll;
  var loadingChips = props.loadingChips,
      update = props.update,
      validate = props.validate,
      maxChips = props.maxChips,
      copies = props.copies;
  var autoFocus = props.autoFocus,
      scores = props.scores,
      chipsColor = props.chipsColor,
      maxChars = props.maxChars,
      minChars = props.minChars;
  var className = props.className;

  var _useState = useState(chips.map(function (aux) {
    return aux.text;
  })),
      _useState2 = _slicedToArray(_useState, 2),
      selected = _useState2[0],
      setSelected = _useState2[1];

  var _useState3 = useState(""),
      _useState4 = _slicedToArray(_useState3, 2),
      text = _useState4[0],
      setText = _useState4[1];

  var _useState5 = useState(false),
      _useState6 = _slicedToArray(_useState5, 2),
      showAlertSave = _useState6[0],
      setShowAlertSave = _useState6[1];

  var _useState7 = useState(false),
      _useState8 = _slicedToArray(_useState7, 2),
      showError = _useState8[0],
      setShowError = _useState8[1]; // const [error, setError] = useState(false);  Para el scoring


  var defaultCopies = _objectSpread({
    placeholder: "Enter an item",
    maxChipsAlert: "You can add up to ".concat(maxChips, " items"),
    minLengthAlert: "String must contain at least ".concat(minChars, " characters"),
    duplicatedItemAlert: "You already added this string",
    maxLengthAlert: "String must not exceed ".concat(maxChars, " characters"),
    inputError: "There are illegal characters in the string",
    clearAll: "Clear all",
    saveWarning: "Please, press Enter to submit",
    chipsAdded: "chips added"
  }, copies);

  var handleChange = function handleChange(event) {
    var textValue = event.target.value;
    setText(textValue);

    if (!!validate && textValue.length > 0 && (selected.indexOf(textValue) > -1 || textValue.length < minChars || !validate(textValue, maxChars))) {
      setShowAlertSave(false);
      setShowError(true);
    } else {
      if (!showAlertSave) setShowAlertSave(true);
      setShowError(false);
    }
  };

  var addNew = /*#__PURE__*/function () {
    var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
      var isValid;
      return _regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              setShowAlertSave(false);
              isValid = validate(text, maxChars);

              if (!(selected.length >= maxChips || text.length < minChars || selected.indexOf(text) > -1)) {
                _context.next = 5;
                break;
              }

              _context.next = 11;
              break;

            case 5:
              if (!(!!text && isValid)) {
                _context.next = 11;
                break;
              }

              setSelected(selected.concat(text));
              addChip(text);
              setText("");
              _context.next = 11;
              return update(text, type.substring(0, type.length - 1).toLowerCase());

            case 11:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    }));

    return function addNew() {
      return _ref.apply(this, arguments);
    };
  }();

  var onKeyPress = function onKeyPress(event) {
    var isValid = validate(text, maxChars);

    if (selected.length >= maxChips || text.length < minChars || selected.indexOf(text) > -1) {// setError(true);
    } else if (event.key === "Enter" && !!text && isValid) {
      setShowAlertSave(false);
      addNew();
    }
  };

  var handleDelete = /*#__PURE__*/function () {
    var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(id, nText) {
      var selectedDelete, index;
      return _regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              selectedDelete = _toConsumableArray(selected);
              index = selectedDelete.indexOf(nText);
              selectedDelete.splice(index, 1);
              setSelected(selectedDelete);
              deleteChip(index);
              _context2.next = 7;
              return update(id, type.substring(0, type.length - 1).toLowerCase(), 0);

            case 7:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2);
    }));

    return function handleDelete(_x, _x2) {
      return _ref2.apply(this, arguments);
    };
  }();

  var deleteAll = function deleteAll() {
    clearAll();
    setSelected([]);
  };

  var handleOnBlur = function handleOnBlur(event) {
    if (!(!!event.target && event.target.value.length > 0 && !showError)) {
      setShowAlertSave(false);
    }
  };

  var handleOnFocus = function handleOnFocus() {
    if (!showError && !showAlertSave) setShowAlertSave(true);
  };

  var errorType = function errorType() {
    if (!!maxChars && text.length > maxChars) {
      return defaultCopies.maxLengthAlert;
    }

    if (!!minChars && text.length < minChars) {
      return defaultCopies.minLengthAlert;
    }

    if (selected.indexOf(text) > -1) {
      return defaultCopies.duplicatedItemAlert;
    }

    if (!validate(text, maxChars)) {
      return defaultCopies.inputError;
    }

    return "";
  };

  return /*#__PURE__*/React.createElement(Grid, {
    container: true,
    className: className
  }, /*#__PURE__*/React.createElement(Grid, {
    item: true,
    xs: 12,
    className: classes.autocomplete
  }, /*#__PURE__*/React.createElement(Grid, {
    container: true,
    justify: "center",
    alignItems: "center",
    spacing: true
  }, /*#__PURE__*/React.createElement(Grid, {
    item: true,
    xs: 12
  }, /*#__PURE__*/React.createElement(Grid, {
    container: true,
    justify: "center",
    alignItems: "center",
    spacing: true
  }, /*#__PURE__*/React.createElement(Grid, {
    item: true,
    xs: 10
  }, /*#__PURE__*/React.createElement(TextField, {
    className: selected.length > 0 ? "" : classes.error,
    autoFocus: autoFocus,
    value: text,
    placeholder: selected.length >= maxChips ? defaultCopies.maxChipsAlert : defaultCopies.placeholder,
    onChange: function onChange(ev) {
      return handleChange(ev);
    },
    onKeyPress: onKeyPress,
    error: showError,
    color: "secondary",
    disabled: selected.length >= maxChips,
    InputProps: {
      endAdornment: /*#__PURE__*/React.createElement(InputAdornment, {
        position: "end"
      }, /*#__PURE__*/React.createElement(IconButton, {
        color: "primary",
        outlined: false,
        disabled: !text,
        icon: /*#__PURE__*/React.createElement(Enter, null),
        onClick: addNew
      }))
    },
    onBlur: function onBlur(ev) {
      return handleOnBlur(ev);
    },
    onFocus: function onFocus() {
      return handleOnFocus();
    }
  })), /*#__PURE__*/React.createElement(Grid, {
    item: true,
    xs: 2
  }, /*#__PURE__*/React.createElement(Typography, {
    className: classes.alignRight
  }, "".concat(text.length, " / ").concat(maxChars)))), /*#__PURE__*/React.createElement(ReactCSSTransitionGroup, {
    transitionName: {
      enter: classes.inputEnter,
      enterActive: classes.inputEnterActive,
      leave: classes.inputLeave,
      leaveActive: classes.inputLeaveActive
    },
    className: classes.inputTransition,
    transitionEnterTimeout: 500,
    transitionLeaveTimeout: 300
  }, showError && errorType() ? /*#__PURE__*/React.createElement(Grid, {
    container: true,
    className: classes.alertText
  }, /*#__PURE__*/React.createElement(Grid, {
    item: true
  }, /*#__PURE__*/React.createElement(Alert, {
    color: "danger",
    className: classes.icon
  })), /*#__PURE__*/React.createElement(Grid, {
    item: true
  }, /*#__PURE__*/React.createElement(Typography, {
    variant: "body1",
    weight: "bold"
  }, errorType()))) : null), /*#__PURE__*/React.createElement(ReactCSSTransitionGroup, {
    transitionName: {
      enter: classes.inputEnter,
      enterActive: classes.inputEnterActive,
      leave: classes.inputLeave,
      leaveActive: classes.inputLeaveActive
    },
    className: classes.inputTransition,
    transitionEnterTimeout: 500,
    transitionLeaveTimeout: 300
  }, showAlertSave ? /*#__PURE__*/React.createElement(Grid, {
    container: true,
    className: classes.alertText
  }, /*#__PURE__*/React.createElement(Grid, {
    item: true
  }, /*#__PURE__*/React.createElement(Alert, {
    color: "warning",
    className: classes.icon
  })), /*#__PURE__*/React.createElement(Grid, {
    item: true
  }, /*#__PURE__*/React.createElement(Typography, {
    color: "warning",
    variant: "body1",
    weight: "bold"
  }, defaultCopies.saveWarning))) : null)))), /*#__PURE__*/React.createElement(Grid, {
    item: true,
    xs: 10
  }, /*#__PURE__*/React.createElement(Grid, {
    container: true,
    justify: "space-between",
    className: classes.tools
  }, /*#__PURE__*/React.createElement(Grid, {
    item: true,
    xs: 6
  }, /*#__PURE__*/React.createElement(Typography, {
    variant: "f2-16",
    gutterBottom: true
  }, "".concat(chips.length, " ").concat(defaultCopies.chipsAdded))), /*#__PURE__*/React.createElement(Grid, {
    item: true
  }, /*#__PURE__*/React.createElement(Link, {
    disabled: isEmpty(selected),
    onClick: deleteAll,
    color: "danger"
  }, defaultCopies.clearAll))), chips.length > 0 && /*#__PURE__*/React.createElement(Grid, {
    item: true,
    xs: 12,
    className: classes.chips
  }, /*#__PURE__*/React.createElement(Grid, {
    container: true
  }, chips.map(function (chip) {
    if (!scores[chip.text] || scores[chip.text] < 0) {
      return /*#__PURE__*/React.createElement(Chip, {
        key: chip.text,
        label: chip.text,
        onDelete: function onDelete() {
          return handleDelete(chip.id, chip.text);
        },
        className: classes.chip,
        loading: !!loadingChips && loadingChips[chip.text],
        color: chipsColor[chip.text],
        clickable: false
      });
    }

    return /*#__PURE__*/React.createElement(Tooltip, {
      key: chip.text,
      title: loadingChips[chip.text] ? "Waiting" : "Score",
      description: scores[chip.text] >= 80 || loadingChips[chip.text] ? "" : "Score",
      icon: /*#__PURE__*/React.createElement(Circle, {
        size: 24,
        color: chipsColor[chip.text],
        className: classes.iconTooltip
      }),
      type: "complete"
    }, /*#__PURE__*/React.createElement(Chip, {
      label: chip.text,
      onDelete: function onDelete() {
        return handleDelete(chip.id, chip.text);
      },
      className: classes.chip,
      loading: !!loadingChips && loadingChips[chip.text],
      color: chipsColor[chip.text],
      clickable: false
    }));
  })))));
};

ChipTextField.propTypes = {
  type: PropTypes.string.isRequired,
  className: PropTypes.string,
  chips: PropTypes.instanceOf(Object).isRequired,
  addChip: PropTypes.func.isRequired,
  deleteChip: PropTypes.func.isRequired,
  clearAll: PropTypes.func.isRequired,
  update: PropTypes.func.isRequired,
  validate: PropTypes.func.isRequired,
  loadingChips: PropTypes.instanceOf(Object),
  scores: PropTypes.instanceOf(Object),
  chipsColor: PropTypes.instanceOf(Object),
  maxChars: PropTypes.number,
  minChars: PropTypes.number,
  maxChips: PropTypes.number,
  autoFocus: PropTypes.bool,
  copies: PropTypes.instanceOf(Object)
};
ChipTextField.defaultProps = {
  className: "",
  loadingChips: {},
  scores: {},
  chipsColor: {},
  maxChars: 90,
  minChars: 1,
  maxChips: 10,
  autoFocus: false,
  copies: {}
};
export default ChipTextField;