import classNames from 'classnames';
import React, { useState, useEffect, useMemo, useRef } from 'react';
import { LoadingIcon, CheckIcon, EyeIcon, MinusIcon, AddIcon, CloseIcon, SearchIcon, AvatarIcon } from '@ye-lib/icons';
import PhoneInput from 'react-phone-input-2';

function _extends() {
  _extends = Object.assign ? Object.assign.bind() : function (target) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];

      for (var key in source) {
        if (Object.prototype.hasOwnProperty.call(source, key)) {
          target[key] = source[key];
        }
      }
    }

    return target;
  };
  return _extends.apply(this, arguments);
}

function _objectWithoutPropertiesLoose(source, excluded) {
  if (source == null) return {};
  var target = {};
  var sourceKeys = Object.keys(source);
  var key, i;

  for (i = 0; i < sourceKeys.length; i++) {
    key = sourceKeys[i];
    if (excluded.indexOf(key) >= 0) continue;
    target[key] = source[key];
  }

  return target;
}

var _excluded = ["children", "text", "type", "className", "align", "isFullWidth"];
var Typography = function Typography(_ref) {
  var _classNames;

  var children = _ref.children,
      text = _ref.text,
      _ref$type = _ref.type,
      type = _ref$type === void 0 ? 'body' : _ref$type,
      className = _ref.className,
      _ref$align = _ref.align,
      align = _ref$align === void 0 ? 'left' : _ref$align,
      isFullWidth = _ref.isFullWidth,
      props = _objectWithoutPropertiesLoose(_ref, _excluded);

  var Tag = ['body', 'button', 'macro'].includes(type) ? 'span' : type;
  var typographyClass = classNames((_classNames = {}, _classNames['typography'] = true, _classNames['typography-fullWidth'] = isFullWidth, _classNames["typography-" + type] = true, _classNames["align-" + align] = !!align, _classNames), className); // @ts-ignore

  return React.createElement(Tag, Object.assign({
    className: typographyClass
  }, props), text || children);
};

var _excluded$1 = ["className", "fullWidth", "isLink", "typography", "text", "children"];
var Button = function Button(_ref) {
  var _classNames;

  var className = _ref.className,
      _ref$fullWidth = _ref.fullWidth,
      fullWidth = _ref$fullWidth === void 0 ? false : _ref$fullWidth,
      _ref$isLink = _ref.isLink,
      isLink = _ref$isLink === void 0 ? false : _ref$isLink,
      typography = _ref.typography,
      text = _ref.text,
      children = _ref.children,
      props = _objectWithoutPropertiesLoose(_ref, _excluded$1);

  var buttonClass = classNames((_classNames = {}, _classNames['btn'] = true, _classNames['btn-link'] = isLink, _classNames['btn-primary'] = !isLink, _classNames['btn-disabled'] = props.disabled, _classNames['btn-adaptive'] = fullWidth, _classNames), className);
  return React.createElement(React.Fragment, null, React.createElement("button", Object.assign({
    className: buttonClass,
    type: "button"
  }, props), children ? children : text ? React.createElement(Typography, Object.assign({
    isFullWidth: true,
    text: text,
    align: 'center'
  }, typography)) : null));
};

var _excluded$2 = ["className", "style", "isLoading", "loadingStatus", "children"];
var LoadingWrapper = function LoadingWrapper(_ref) {
  var className = _ref.className,
      style = _ref.style,
      isLoading = _ref.isLoading,
      loadingStatus = _ref.loadingStatus,
      children = _ref.children,
      props = _objectWithoutPropertiesLoose(_ref, _excluded$2);

  return React.createElement("div", {
    className: 'loading ' + className || '',
    style: style
  }, isLoading && React.createElement("div", {
    className: 'loading-wrapper',
    style: style
  }, React.createElement(LoadingIcon, Object.assign({
    className: 'loading-icon'
  }, props)), loadingStatus && React.createElement("span", null, loadingStatus)), children);
};

var Radiobutton = function Radiobutton(_ref) {
  var _classNames;

  var className = _ref.className,
      _onClick = _ref.onClick,
      hasError = _ref.hasError,
      status = _ref.status,
      label = _ref.label,
      value = _ref.value,
      disabled = _ref.disabled;
  var RBClass = classNames((_classNames = {}, _classNames['RB'] = true, _classNames['RB-hasError'] = hasError, _classNames['RB-disabled'] = disabled, _classNames), className);
  return React.createElement("div", {
    className: RBClass,
    onClick: function onClick() {
      return _onClick && !disabled && _onClick(value, !status);
    }
  }, React.createElement("div", {
    className: "check"
  }, React.createElement("div", {
    className: "dot" + (status ? ' active' : '')
  })), React.createElement(Typography, {
    className: "label",
    type: 'body',
    text: label
  }));
};

var Checkbox = function Checkbox(_ref) {
  var _classNames;

  var className = _ref.className,
      isHalf = _ref.isHalf,
      _onClick = _ref.onClick,
      hasError = _ref.hasError,
      status = _ref.status,
      label = _ref.label,
      value = _ref.value,
      disabled = _ref.disabled;
  var RBClass = classNames((_classNames = {}, _classNames['checkbox'] = true, _classNames['checkbox-hasError'] = hasError, _classNames['checkbox-disabled'] = disabled, _classNames.className = className, _classNames));
  return React.createElement("div", {
    className: RBClass,
    onClick: function onClick() {
      return _onClick && !disabled && _onClick(value, !status);
    }
  }, React.createElement("div", {
    className: "check"
  }, status ? isHalf ? React.createElement("hr", {
    className: "half"
  }) : React.createElement(CheckIcon, null) : null), typeof label === 'string' ? React.createElement(Typography, {
    type: 'body',
    text: label
  }) : label);
};

var isEqualStringArray = function isEqualStringArray(oldArr, newArr) {
  var codesCount = {};
  newArr.forEach(function (code) {
    codesCount[code] = 1;
  });
  oldArr.forEach(function (code) {
    codesCount[code] = codesCount[code] ? 2 : 1;
  });
  var status = false;
  Object.keys(codesCount).forEach(function (code) {
    if (!status && codesCount[code] !== 2) status = true;
  });
  return status;
};

var CheckGroup = function CheckGroup(_ref) {
  var _classNames;

  var type = _ref.type,
      data = _ref.data,
      disabled = _ref.disabled,
      onChange = _ref.onChange,
      groupTitle = _ref.groupTitle,
      selected = _ref.selected,
      hasAll = _ref.hasAll;

  var _useState = useState([]),
      mySelected = _useState[0],
      setMySelected = _useState[1];

  var CGClass = classNames((_classNames = {}, _classNames['checkGroup'] = true, _classNames["checkGroup-" + type] = true, _classNames));
  useEffect(function () {
    if (isEqualStringArray(selected, mySelected)) {
      setMySelected([].concat(selected));
    }
  }, [selected]);

  var handleChange = function handleChange(value, status) {
    if (type === 'radio') onChange([value]);
    if (type === 'check') onChange(status ? [].concat(mySelected, [value]) : mySelected.filter(function (i) {
      return i !== value;
    }));
  };

  var handleCheckAll = function handleCheckAll() {
    return onChange(mySelected.length !== visible.length ? visible.map(function (i) {
      return i.value;
    }) : []);
  };

  var visible = useMemo(function () {
    return data.filter(function (i) {
      return !i.disabled;
    });
  }, [data]);
  return React.createElement("div", {
    className: CGClass
  }, React.createElement("div", {
    className: 'group-title'
  }, hasAll ? React.createElement(Checkbox, {
    onClick: handleCheckAll,
    status: !!mySelected.length,
    label: React.createElement(Typography, {
      type: 'h3',
      text: groupTitle
    }),
    value: 'all',
    isHalf: mySelected.length !== visible.length
  }) : React.createElement(Typography, {
    type: 'h3',
    text: groupTitle
  })), React.createElement("div", {
    className: "group-content"
  }, data.map(function (item) {
    return type === 'radio' ? React.createElement(Radiobutton, Object.assign({
      key: item.value
    }, item, {
      status: item.status || mySelected.includes(item.value),
      disabled: disabled || item.disabled,
      onClick: handleChange
    })) : React.createElement(Checkbox, Object.assign({
      key: item.value
    }, item, {
      status: item.status || mySelected.includes(item.value),
      disabled: disabled || item.disabled,
      onClick: handleChange
    }));
  })));
};

var Switch = function Switch(_ref) {
  var _classNames;

  var _onClick = _ref.onClick,
      status = _ref.status,
      disabled = _ref.disabled,
      hasError = _ref.hasError;
  var switchClass = classNames((_classNames = {}, _classNames['switch'] = true, _classNames['switch-active'] = status, _classNames['switch-disabled'] = disabled, _classNames['switch-error'] = hasError, _classNames));
  return React.createElement(React.Fragment, null, React.createElement("div", {
    className: switchClass,
    onClick: function onClick() {
      return _onClick && !disabled && _onClick(!status);
    }
  }, React.createElement("span", null)));
};

var validators = {
  phone: function phone(value) {
    if (!value) return "Please type phone";
    if (value.length !== 11) return "Phone s short";
    return '';
  },
  login: function login(value) {
    if (!value) return 'Please put the login!';
    if (value.length < 10) return "The login is short";
    if (value.length > 12) return "The login is longer";
    if (value.length !== value.replace(/\s/g, '').length) return "Don't use spaces on login";
    return '';
  },
  email: function email(value) {
    if (!value) return 'Please put the email!';
    if (!String(value).toLowerCase().match(/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)) return "This is not a email";
    return '';
  },
  pass: function pass(value) {
    if (!value) return 'Please put the password!'; // eslint-disable-next-line

    if (!value.match(/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})/)) return "Incorrect password";
    return '';
  },
  pass2: function pass2(pass, _pass) {
    var pass2Error = this.pass(_pass);
    if (pass2Error.length) return pass2Error;
    if (_pass !== pass) return 'Incorrect password';
    return '';
  },
  name: function name(value) {
    if (!value || 0 === value.trim().length) return 'Please put this field!';
    return '';
  },
  user: function user(_user) {
    var nameError = this.name(_user.name);
    if (nameError.length) return false;
    var emailError = this.email(_user.email);
    if (emailError.length) return false;
    var passError = this.pass(_user.pass);
    if (passError.length) return false;
    var pass2Error = this.pass2(_user.pass, _user.pass2);
    return !pass2Error.length;
  }
};

var _excluded$3 = ["offRealTime", "align", "readonly", "error", "disabled", "charCount", "label", "required"];
var BaseInput = function BaseInput(_ref) {
  var _classNames;

  var _ref$baseProps = _ref.baseProps,
      value = _ref$baseProps.value,
      onChange = _ref$baseProps.onChange,
      name = _ref$baseProps.name,
      className = _ref.className,
      _ref$options = _ref.options,
      offRealTime = _ref$options.offRealTime,
      _ref$options$align = _ref$options.align,
      align = _ref$options$align === void 0 ? 'left' : _ref$options$align,
      readonly = _ref$options.readonly,
      error = _ref$options.error,
      disabled = _ref$options.disabled,
      charCount = _ref$options.charCount,
      label = _ref$options.label,
      required = _ref$options.required,
      otherOptions = _objectWithoutPropertiesLoose(_ref$options, _excluded$3),
      validator = _ref.validator,
      type = _ref.type;

  var _useState = useState(''),
      myValue = _useState[0],
      setMyValue = _useState[1];

  var _useState2 = useState(),
      myError = _useState2[0],
      setMyError = _useState2[1];

  var _useState3 = useState(false),
      visible = _useState3[0],
      setVisible = _useState3[1];

  var inputClass = classNames((_classNames = {}, _classNames['input-disabled'] = disabled, _classNames['input-error'] = myError, _classNames['input-resizeable'] = otherOptions == null ? void 0 : otherOptions.resizeable, _classNames["input-" + align] = true, _classNames["input-" + type] = true, _classNames), 'input', className);
  useEffect(function () {
    if (offRealTime) {
      if (value !== undefined && value !== myValue) setMyValue(charCount ? value.substring(0, charCount) : value);
    }
  }, [value]);
  useEffect(function () {
    if (error !== undefined && error !== myError) setMyError(error);
  }, [error]);

  var validate = function validate(value, fromBlur) {
    if (fromBlur === void 0) {
      fromBlur = false;
    }

    if (!validator) return;

    if (fromBlur && !validator.isRunTime || validator.isRunTime || myError) {
      var _error = validators[validator.type](value, validator.message);

      setMyError(_error);
    }
  };

  var handleTextChange = function handleTextChange(name, value, fromBlur) {
    if (fromBlur === void 0) {
      fromBlur = false;
    }

    onChange(name, value);
    validate(value, fromBlur);
  };

  var handleChange = function handleChange(e) {
    if (disabled || readonly) return;
    if (charCount && myValue.length > charCount) return;
    if (!offRealTime) handleTextChange(name, charCount ? e.target.value.substring(0, charCount) : e.target.value);else setMyValue(charCount ? e.target.value.substring(0, charCount) : e.target.value);
  };

  var onBlur = function onBlur() {
    if (disabled || readonly) return;
    if (offRealTime) handleTextChange(name, myValue, true);
    validate(value, true);
  };

  var props = _extends({
    className: type,
    onBlur: onBlur,
    value: !offRealTime ? value : myValue,
    onChange: handleChange,
    readOnly: disabled || readonly,
    type: type === 'Password' ? visible ? 'text' : 'password' : 'text'
  }, otherOptions);

  var changeVisible = function changeVisible() {
    if (disabled || readonly) return;
    setVisible(function (v) {
      return !v;
    });
  };

  return React.createElement("div", {
    className: inputClass
  }, label && React.createElement(Typography, {
    type: 'macro',
    isFullWidth: true,
    className: "label",
    text: label + (required ? ' *' : '')
  }), React.createElement("div", {
    className: "content"
  }, type === 'Textarea' ? React.createElement("textarea", Object.assign({}, props)) : React.createElement("input", Object.assign({}, props)), type === 'Password' && React.createElement(EyeIcon, {
    className: "icon",
    onClick: changeVisible,
    visible: visible
  })), React.createElement("div", {
    className: "foot"
  }, typeof myError === 'string' && React.createElement(Typography, {
    type: 'macro',
    align: charCount ? 'left' : 'right',
    isFullWidth: true,
    className: "error",
    text: myError
  }), charCount && React.createElement(Typography, {
    type: 'macro',
    align: 'right',
    isFullWidth: true,
    className: "charCount",
    text: (!offRealTime ? value : myValue).length + "/" + charCount
  })));
};

var Code = function Code(_ref) {
  var _ref$baseProps = _ref.baseProps,
      value = _ref$baseProps.value,
      onChange = _ref$baseProps.onChange,
      name = _ref$baseProps.name,
      options = _ref.options,
      _ref$length = _ref.length,
      length = _ref$length === void 0 ? 4 : _ref$length;
  var keys = useMemo(function () {
    return Array.from(Array(length).keys());
  }, [length]);
  var inputs = keys.map(function () {
    return useRef();
  });

  var onChangeCode = function onChangeCode(id, key) {
    var newValue = id ? value.slice(0, id) : '';
    if (key.match(/\D+/)) return;

    if (!key.length) {
      var _inputs$current;

      if (id) (_inputs$current = inputs[id - 1].current) == null ? void 0 : _inputs$current.focus();
    } else {
      if (key.length === 1) {
        newValue += key;
      }

      if (key.length === 2) {
        newValue += key[1];
      }

      if (id + 1 < length) {
        var _inputs$current2;

        (_inputs$current2 = inputs[id + 1].current) == null ? void 0 : _inputs$current2.focus();
      } else {
        var _inputs$id, _inputs$id$current;

        (_inputs$id = inputs[id]) == null ? void 0 : (_inputs$id$current = _inputs$id.current) == null ? void 0 : _inputs$id$current.blur();
      }
    } // setValid(newValue.length === keyLength)


    onChange(name || '', newValue);
  };

  return React.createElement("div", {
    className: "input-code"
  }, React.createElement("div", {
    className: "codes"
  }, keys.map(function (i) {
    return React.createElement("div", {
      key: i,
      className: "codes-item"
    }, React.createElement("input", Object.assign({}, options != null && options.error ? {
      className: 'error'
    } : {}, {
      ref: inputs[i],
      value: value[i] || '',
      autoFocus: !i,
      onChange: function onChange(e) {
        return onChangeCode(i, e.target.value);
      }
    })));
  })), (options == null ? void 0 : options.error) && React.createElement(Typography, {
    type: "macro",
    className: "error",
    text: "Incorrect Code",
    align: "center",
    isFullWidth: true
  }));
};

var _excluded$4 = ["label", "readonly", "canBeNegative", "max", "min", "value", "hasDot", "disabled", "error", "className", "onChange"];

var getNumber = function getNumber(value, hasDot, canBeNegative) {
  var k = '';
  value.split('').forEach(function (t) {
    if (canBeNegative && '-' === t && k === '') {
      k += t;
    } else if (hasDot && '.' === t && k.indexOf('.') === -1) {
      k += t;
    } else if ('0123456789'.indexOf(t) !== -1) {
      k += t;
    }
  });
  return k;
};

var NumberInput = function NumberInput(_ref) {
  var _classNames;

  var label = _ref.label,
      readonly = _ref.readonly,
      canBeNegative = _ref.canBeNegative,
      max = _ref.max,
      min = _ref.min,
      value = _ref.value,
      hasDot = _ref.hasDot,
      disabled = _ref.disabled,
      error = _ref.error,
      className = _ref.className,
      onChange = _ref.onChange,
      props = _objectWithoutPropertiesLoose(_ref, _excluded$4);

  var numberInputClass = classNames((_classNames = {}, _classNames['number-input-disabled'] = disabled, _classNames['number-input-error'] = error, _classNames), 'number-input', className);
  min = min !== undefined ? min : !canBeNegative ? 0 : undefined;

  var _useState = useState(''),
      myValue = _useState[0],
      setMyValue = _useState[1];

  useEffect(function () {
    if (value && value.toString() !== myValue) setMyValue((value == null ? void 0 : value.toString()) || '');
  }, [value]);

  var onChangeInput = function onChangeInput(val) {
    if (val === void 0) {
      val = myValue;
    }

    if (onChange) onChange(+val);
  };

  var dec = function dec() {
    return clickChange(-1);
  };

  var inc = function inc() {
    return clickChange(1);
  };

  var clickChange = function clickChange(change) {
    if (disabled || readonly) return;
    var newValue = +myValue + change;
    if (max && newValue > max) return;
    if (min !== undefined && newValue < min) return;

    if (hasDot) {
      var _myValue$toString$spl;

      newValue = +newValue.toFixed(((_myValue$toString$spl = myValue.toString().split('.')[1]) == null ? void 0 : _myValue$toString$spl.length) || 0);
    }

    setMyValue(newValue.toString());
    onChangeInput(newValue);
  };

  var handleChange = function handleChange(e) {
    setMyValue(getNumber(e.target.value, hasDot, canBeNegative));
  };

  var handleBlur = function handleBlur() {
    return onChangeInput();
  };

  return React.createElement("div", {
    className: numberInputClass
  }, label && React.createElement(Typography, {
    type: 'macro',
    isFullWidth: true,
    className: "label",
    text: label
  }), React.createElement("div", {
    className: "content"
  }, React.createElement(MinusIcon, {
    className: "icon icon-dec",
    onClick: dec
  }), React.createElement("input", Object.assign({
    className: 'input',
    onBlur: handleBlur,
    disabled: disabled,
    readOnly: readonly,
    onChange: handleChange,
    value: myValue
  }, props)), React.createElement(AddIcon, {
    className: "icon icon-inc",
    onClick: inc
  })), error && React.createElement(Typography, {
    type: 'macro',
    align: 'right',
    isFullWidth: true,
    className: "error",
    text: typeof error === 'boolean' ? 'invalid number' : error
  }));
};

var _excluded$5 = ["readonly", "error", "disabled", "offRealTime", "label", "placeholder"],
    _excluded2 = ["baseProps", "options", "className"];
var Phone = function Phone(_ref) {
  var _classNames;

  var _ref$baseProps = _ref.baseProps,
      value = _ref$baseProps.value,
      onChange = _ref$baseProps.onChange,
      name = _ref$baseProps.name,
      _ref$options = _ref.options,
      readonly = _ref$options.readonly,
      error = _ref$options.error,
      disabled = _ref$options.disabled,
      offRealTime = _ref$options.offRealTime,
      label = _ref$options.label,
      placeholder = _ref$options.placeholder,
      options = _objectWithoutPropertiesLoose(_ref$options, _excluded$5),
      className = _ref.className,
      props = _objectWithoutPropertiesLoose(_ref, _excluded2);

  var inputPhoneClass = classNames((_classNames = {}, _classNames['input-PN-disabled'] = disabled, _classNames['input-PN-error'] = error, _classNames), 'input-PN', className);

  var _useState = useState(''),
      myValue = _useState[0],
      setMyValue = _useState[1];

  useEffect(function () {
    if (offRealTime) {
      if (value !== undefined && value !== myValue) setMyValue(value);
    }
  }, [value]);

  var handleChange = function handleChange(val) {
    if (disabled || readonly) return;
    if (!offRealTime) onChange(name, val);else setMyValue(val);
  };

  var onBlur = function onBlur() {
    if (disabled || readonly) return;
    if (offRealTime) onChange(name, myValue);
  };

  return React.createElement("div", {
    className: inputPhoneClass
  }, label && React.createElement(Typography, {
    type: 'macro',
    isFullWidth: true,
    className: "label",
    text: label
  }), React.createElement("div", {
    className: "content"
  }, React.createElement(PhoneInput, Object.assign({
    disabled: disabled || readonly,
    placeholder: placeholder,
    onChange: handleChange,
    value: offRealTime ? myValue : value,
    country: "cz",
    inputProps: {
      disabled: disabled || readonly,
      onBlur: onBlur
    }
  }, props, options))), error && React.createElement(Typography, {
    type: 'macro',
    align: 'right',
    isFullWidth: true,
    className: "error",
    text: typeof error === 'boolean' ? 'invalid number' : error
  }));
};

var Input = {
  Number: NumberInput,
  Phone: Phone,
  Code: Code,
  Pass: function Pass(props) {
    return React.createElement(BaseInput, Object.assign({}, {
      baseProps: _extends({
        name: 'password'
      }, props.baseProps),
      options: _extends({}, props.options),
      type: 'Password',
      className: props.className,
      validator: props.validator
    }));
  },
  Area: function Area(props) {
    return React.createElement(BaseInput, Object.assign({}, {
      baseProps: _extends({
        name: 'description'
      }, props.baseProps),
      options: _extends({}, props.options),
      type: 'Textarea',
      className: props.className,
      validator: props.validator
    }));
  },
  Login: function Login(props) {
    return React.createElement(BaseInput, Object.assign({}, {
      baseProps: _extends({
        name: 'login'
      }, props.baseProps),
      options: _extends({}, props.options),
      type: 'Text',
      className: props.className,
      validator: props.validator
    }));
  },
  Text: function Text(props) {
    return React.createElement(BaseInput, Object.assign({}, props, {
      type: "Text"
    }));
  },
  Name: function Name(props) {
    return React.createElement(BaseInput, Object.assign({}, {
      baseProps: _extends({
        name: 'name'
      }, props.baseProps),
      options: _extends({}, props.options),
      type: 'Text',
      className: props.className,
      validator: props.validator
    }));
  },
  Email: function Email(props) {
    return React.createElement(BaseInput, Object.assign({}, {
      baseProps: _extends({
        name: 'email'
      }, props.baseProps),
      options: _extends({}, props.options),
      type: 'Email',
      className: props.className,
      validator: props.validator
    }));
  }
};

var useBody = function useBody() {
  var scroll = {
    off: function off() {
      // @ts-ignore
      document.querySelector('body').style.overflow = 'hidden';
    },
    on: function on() {
      // @ts-ignore
      document.querySelector('body').style.overflow = 'auto';
    }
  };
  return {
    scroll: scroll
  };
};

var BackgroundWrapper = function BackgroundWrapper(_ref) {
  var children = _ref.children,
      status = _ref.status,
      ovh = _ref.ovh,
      onClick = _ref.onClick;

  var _useBody = useBody(),
      scroll = _useBody.scroll;

  useEffect(function () {
    return ovh && status ? scroll.off() : scroll.on();
  }, [status]);
  return React.createElement(React.Fragment, null, status ? React.createElement("div", {
    className: "bg-wrapper",
    onClick: onClick
  }) : null, children);
};

var Modal = function Modal(_ref) {
  var outSideClose = _ref.outSideClose,
      children = _ref.children,
      title = _ref.title,
      footer = _ref.footer,
      _ref$unClosable = _ref.unClosable,
      unClosable = _ref$unClosable === void 0 ? false : _ref$unClosable,
      visible = _ref.visible,
      onCancel = _ref.onCancel,
      onOk = _ref.onOk,
      width = _ref.width,
      className = _ref.className,
      _ref$okText = _ref.okText,
      okText = _ref$okText === void 0 ? 'ok' : _ref$okText,
      _ref$cancelText = _ref.cancelText,
      cancelText = _ref$cancelText === void 0 ? 'cancel' : _ref$cancelText,
      offFooter = _ref.offFooter,
      isLoading = _ref.isLoading;

  var onClose = function onClose() {
    return onCancel ? onCancel() : {};
  };

  return React.createElement("div", {
    className: "modal" + (visible ? ' visible' : '')
  }, React.createElement(BackgroundWrapper, {
    onClick: function onClick() {
      return outSideClose ? onClose() : {};
    },
    status: visible
  }, React.createElement(React.Fragment, null, visible ? React.createElement(LoadingWrapper, {
    isLoading: !!isLoading,
    className: "modal-body " + (className ? className : ''),
    style: {
      width: width
    }
  }, React.createElement("div", {
    className: "title"
  }, typeof title === 'string' ? React.createElement(Typography, {
    type: 'h3',
    text: title
  }) : title, !unClosable ? React.createElement(CloseIcon, {
    onClick: onClose,
    className: "close-icon"
  }) : null), React.createElement("div", {
    className: 'modal-content'
  }, children), React.createElement("div", {
    className: "footer"
  }, offFooter ? null : footer !== undefined ? footer : React.createElement(React.Fragment, null, React.createElement(Button, {
    text: cancelText,
    onClick: onCancel
  }), React.createElement(Button, {
    text: okText,
    onClick: onOk
  })))) : null)));
};

var getChosenOptions = function getChosenOptions(options, selected) {
  var chosenOptions = [];
  selected.forEach(function (value) {
    var option = options.find(function (o) {
      return o.value === value;
    });
    if (option) chosenOptions.push(option);
  });
  return chosenOptions;
};

var ChosenOptions = function ChosenOptions(_ref) {
  var canRemove = _ref.canRemove,
      selected = _ref.selected,
      options = _ref.options,
      onUnSelect = _ref.onUnSelect;
  if (!selected.length) return null;
  var chosenOptions = useMemo(function () {
    return getChosenOptions(options, selected);
  }, [options, selected]);

  var _onClick = function onClick(e, value) {
    e.preventDefault();
    e.stopPropagation();
    onUnSelect(value, false);
  };

  return React.createElement("div", {
    className: "chosen-options"
  }, chosenOptions.map(function (option) {
    return React.createElement("div", {
      key: option.value,
      className: "chosen-option"
    }, React.createElement(Typography, {
      text: option.label
    }), canRemove && React.createElement(CloseIcon, {
      size: 15,
      className: "chosen-unselect",
      onClick: function onClick(e) {
        return _onClick(e, option.value);
      }
    }));
  }));
};

var SelectOption = function SelectOption(_ref) {
  var _onClick = _ref.onClick,
      value = _ref.value,
      label = _ref.label,
      disabled = _ref.disabled,
      selected = _ref.selected;
  return React.createElement("div", {
    className: "option " + (disabled ? 'option-disabled' : '') + " " + (selected ? 'option-selected' : ''),
    onClick: function onClick() {
      return !disabled ? _onClick(value, !selected) : {};
    }
  }, React.createElement(Typography, {
    text: label
  }));
};

var Select = function Select(_ref) {
  var _classNames;

  var options = _ref.options,
      selected = _ref.selected,
      onSelect = _ref.onSelect,
      isMulti = _ref.isMulti,
      className = _ref.className,
      label = _ref.label,
      placeholder = _ref.placeholder,
      error = _ref.error,
      disabled = _ref.disabled,
      readonly = _ref.readonly,
      searchable = _ref.searchable,
      searchIcon = _ref.searchIcon;

  var _useState = useState(false),
      status = _useState[0],
      setStatus = _useState[1];

  var _useState2 = useState([]),
      mySelected = _useState2[0],
      setMySelected = _useState2[1];

  var _useState3 = useState(''),
      mySelectedFilter = _useState3[0],
      setMySelectedFilter = _useState3[1];

  var inputClass = classNames((_classNames = {}, _classNames['select-disabled'] = disabled, _classNames['select-readonly'] = readonly, _classNames['select-error'] = error, _classNames['select-hasClose'] = mySelected.length, _classNames['select-hasSearchIcon'] = searchIcon, _classNames['select-active'] = status, _classNames), 'select', className);
  useEffect(function () {
    if (isEqualStringArray(mySelected, selected)) setMySelected(selected);
  }, [selected]);
  useEffect(function () {
    if (!status) onSelect(mySelected);
  }, [status]);

  var toggleStatus = function toggleStatus() {
    if (disabled || readonly) return;
    setStatus(function (s) {
      return !s;
    });
  };

  var onOptionClick = function onOptionClick(value, status) {
    // setMySelected(values => !status ? values.filter(v => v !== value) : [...values, value])
    if (!isMulti) {
      setMySelected(function (values) {
        return values[0] && values[0] === value ? [] : [value];
      });
      toggleStatus();
    } else {
      setMySelected(function (values) {
        return !status ? values.filter(function (v) {
          return v !== value;
        }) : [].concat(values, [value]);
      });
    }

    if (status) setMySelectedFilter('');
  };

  var clearSelected = function clearSelected() {
    onSelect([]);
    if (status) setStatus(false);
  };

  var visibleOptions = useMemo(function () {
    return options.filter(function (o) {
      return o.label.indexOf(mySelectedFilter) !== -1 || o.label.toLowerCase().indexOf(mySelectedFilter.toLowerCase()) !== -1;
    });
  }, [mySelectedFilter]);
  return React.createElement("div", {
    className: inputClass
  }, label && React.createElement(Typography, {
    type: 'macro',
    isFullWidth: true,
    className: "label",
    text: label
  }), React.createElement("div", {
    className: "content"
  }, React.createElement("div", {
    className: "selecting",
    onClick: toggleStatus
  }, searchIcon && React.createElement(SearchIcon, {
    className: "search-icon"
  }), mySelected.length ? React.createElement(ChosenOptions, {
    options: options,
    selected: mySelected,
    onUnSelect: onOptionClick,
    canRemove: isMulti && !(disabled || readonly)
  }) : null, isMulti || searchable || searchIcon ? React.createElement("input", {
    readOnly: disabled || readonly,
    placeholder: placeholder || 'select',
    value: mySelectedFilter,
    onChange: function onChange(e) {
      return !(disabled || readonly) ? setMySelectedFilter(e.target.value) : {};
    }
  }) : !mySelected.length && React.createElement(Typography, {
    className: "placeholder",
    text: placeholder || 'select'
  })), mySelected.length ? React.createElement(CloseIcon, {
    className: "close-icon",
    onClick: clearSelected
  }) : null, React.createElement(BackgroundWrapper, {
    status: status,
    onClick: toggleStatus
  }, React.createElement("div", {
    className: "options " + (status ? 'options-active' : '')
  }, visibleOptions.length ? visibleOptions.map(function (option) {
    return React.createElement(SelectOption, Object.assign({
      key: option.value,
      onClick: onOptionClick,
      selected: mySelected.includes(option.value)
    }, option));
  }) : React.createElement(Typography, {
    className: "placeholder",
    isFullWidth: true,
    align: 'center',
    text: 'options not found'
  })))), error && React.createElement(Typography, {
    type: 'macro',
    align: 'right',
    isFullWidth: true,
    className: "error",
    text: error
  }));
};

var DropdownWrapper = function DropdownWrapper(_ref) {
  var _bodyRef$current, _buttonRef$current, _contentRef$current;

  var _ref$className = _ref.className,
      className = _ref$className === void 0 ? '' : _ref$className,
      children = _ref.children,
      contentOptions = _ref.contentOptions,
      contentTitle = _ref.contentTitle,
      content = _ref.content,
      _ref$position = _ref.position,
      position = _ref$position === void 0 ? 'right' : _ref$position,
      list = _ref.list,
      icon = _ref.icon,
      disable = _ref.disable,
      maxHeight = _ref.maxHeight;

  var _useState = useState(false),
      status = _useState[0],
      setStatus = _useState[1];

  var bodyRef = useRef(null);
  var buttonRef = useRef(null);
  var contentRef = useRef(null);

  var toggle = function toggle() {
    return !disable ? setStatus(function (c) {
      return !c;
    }) : {};
  };

  maxHeight = maxHeight || parseInt(String(((_bodyRef$current = bodyRef.current) == null ? void 0 : _bodyRef$current.scrollHeight) || 0)) + 16;
  var align = position === 'left' ? {
    left: 0
  } : position === 'right' ? {
    right: 0
  } : {
    left: ((((_buttonRef$current = buttonRef.current) == null ? void 0 : _buttonRef$current.clientWidth) || 0) - (((_contentRef$current = contentRef.current) == null ? void 0 : _contentRef$current.clientWidth) || 0)) / 2
  };
  return React.createElement(BackgroundWrapper, {
    onClick: toggle,
    status: status
  }, React.createElement("div", {
    ref: buttonRef,
    className: "dropdownWrapper " + className
  }, React.createElement("div", {
    ref: buttonRef,
    className: "children",
    onClick: toggle
  }, children || icon), React.createElement("div", {
    ref: contentRef,
    className: "content " + position + " " + (status ? 'opened' : ''),
    style: _extends({
      height: status ? maxHeight : 0
    }, align)
  }, contentTitle ? React.createElement("div", {
    className: 'title'
  }, contentTitle) : null, React.createElement("div", {
    ref: bodyRef,
    onClick: toggle,
    className: "body " + (list ? 'list' : '')
  }, content), contentOptions ? React.createElement("div", {
    className: 'options'
  }, contentOptions) : null)));
};

var PageTitle = function PageTitle(_ref) {
  var title = _ref.title;
  return React.createElement(Typography, {
    type: "h1",
    text: title,
    isFullWidth: true,
    align: 'center'
  });
};

function handleUploadImage(event, CB) {
  if (!event.target.files || !event.target.files.length) return;
  var file = event.target.files[0];
  var reader = new FileReader();
  reader.readAsDataURL(file);

  reader.onload = function () {
    CB(reader.result);
  };
}

var ImageUpload = function ImageUpload(_ref) {
  var title = _ref.title,
      onUpload = _ref.onUpload,
      img = _ref.img;

  var _useState = useState(function () {
    return img || '';
  }),
      myImg = _useState[0],
      setMyImg = _useState[1];

  var imgInput = useRef();

  var handleUpload = function handleUpload() {
    if (myImg !== img) onUpload(myImg);
  };

  var inputChange = function inputChange(e) {
    handleUploadImage(e, function (base64) {
      if (base64) setMyImg(function () {
        return base64;
      });
    });
  };

  var inputClick = function inputClick() {
    var _imgInput$current;

    return (_imgInput$current = imgInput.current) == null ? void 0 : _imgInput$current.click();
  };

  return React.createElement("div", {
    className: "image-uploader"
  }, React.createElement("div", {
    className: "uploader",
    onClick: inputClick
  }, myImg ? React.createElement("img", {
    src: myImg,
    alt: "avatar"
  }) : React.createElement(AvatarIcon, {
    size: 200
  }), React.createElement("input", {
    onChange: inputChange,
    ref: imgInput,
    type: "file",
    accept: "image/*"
  })), React.createElement(Button, {
    fullWidth: true,
    disabled: myImg === img,
    onClick: handleUpload,
    text: title
  }));
};

export { BackgroundWrapper, Button, CheckGroup, Checkbox, DropdownWrapper, ImageUpload, Input, LoadingWrapper, Modal, NumberInput, PageTitle, Radiobutton, Select, Switch, Typography };
//# sourceMappingURL=components.esm.js.map
