"use strict";

exports.__esModule = true;
exports.default = void 0;

var _react = _interopRequireWildcard(require("react"));

var _material = require("@mui/material");

var _styles = require("@mui/material/styles");

var _reactIntl = require("react-intl");

var _Icon = _interopRequireDefault(require("@mui/material/Icon"));

var _reactSortablejs = require("react-sortablejs");

var _InputAdornment = _interopRequireDefault(require("@mui/material/InputAdornment"));

var _lab = require("@mui/lab");

var _AdapterDateFns = _interopRequireDefault(require("@mui/lab/AdapterDateFns"));

var _Composer = require("../../../constants/Composer");

var _it = _interopRequireDefault(require("date-fns/locale/it"));

var _enUS = _interopRequireDefault(require("date-fns/locale/en-US"));

var _classnames = _interopRequireDefault(require("classnames"));

var _useThemeProps = _interopRequireDefault(require("@mui/material/styles/useThemeProps"));

const _excluded = ["children"];

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _extends() { _extends = Object.assign || 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; }

const localeMap = {
  en: _enUS.default,
  it: _it.default
};
const PREFIX = 'SCComposerPoll';
const classes = {
  root: `${PREFIX}-root`,
  title: `${PREFIX}-title`,
  choices: `${PREFIX}-choices`,
  choiceNew: `${PREFIX}-choice-new`,
  metadata: `${PREFIX}-metadata`
};
const Root = (0, _styles.styled)(_material.Box, {
  name: PREFIX,
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})(({
  theme
}) => ({
  padding: theme.spacing(2),
  [`& .${classes.title}, & .${classes.choices}, & .${classes.choiceNew}, & .${classes.metadata}`]: {
    marginBottom: theme.spacing(3)
  },
  [`& .${classes.choices} .MuiTextField-root`]: {
    marginBottom: theme.spacing()
  },
  [`& .${classes.metadata}`]: {
    marginTop: theme.spacing(3)
  }
}));
const messages = (0, _reactIntl.defineMessages)({
  choicePlaceholder: {
    id: 'ui.composer.poll.choice.placeholder',
    defaultMessage: 'ui.composer.poll.choice.placeholder'
  }
});
const SortableComponent = /*#__PURE__*/(0, _react.forwardRef)((_ref, ref) => {
  let {
    children
  } = _ref,
      props = _objectWithoutPropertiesLoose(_ref, _excluded);

  return /*#__PURE__*/_react.default.createElement(_material.FormGroup, _extends({
    direction: "column",
    ref: ref
  }, props), children);
});
/**
 * Default poll
 */

const DEFAULT_CHOICE = {
  choice: ''
};
const DEFAULT_POLL = {
  title: '',
  multiple_choices: false,
  expiration_at: null,
  choices: [Object.assign({}, DEFAULT_CHOICE), Object.assign({}, DEFAULT_CHOICE)]
};

var _default = inProps => {
  // PROPS
  const props = (0, _useThemeProps.default)({
    props: inProps,
    name: PREFIX
  });
  const {
    id = 'poll',
    className = null,
    value = Object.assign({}, DEFAULT_POLL),
    error = {},
    onChange
  } = props;
  const {
    titleError = null
  } = Object.assign({}, error); // STATE

  const [title, setTitle] = (0, _react.useState)(value !== null ? value.title : DEFAULT_POLL.title);
  const [multiple, setMultiple] = (0, _react.useState)(value !== null ? value.multiple_choices : DEFAULT_POLL.multiple_choices);

  const [expiration, setExpiration] = _react.default.useState(value !== null ? value.expiration_at : DEFAULT_POLL.expiration_at);

  const _choicesInitialState = [...(value !== null ? value.choices : DEFAULT_POLL.choices)];

  while (_choicesInitialState.length < _Composer.COMPOSER_POLL_MIN_CHOICES) {
    _choicesInitialState.push(Object.assign({}, DEFAULT_CHOICE));
  }

  const [choices, setChoices] = (0, _react.useState)(_choicesInitialState); // INTL

  const intl = (0, _reactIntl.useIntl)(); // Component update

  (0, _react.useEffect)(() => {
    if (onChange && (title || expiration !== null || choices.filter(c => c.choice.length > 0).length > 0)) {
      onChange({
        title,
        expiration_at: expiration,
        multiple_choices: multiple,
        choices: choices.filter(c => c.choice.length > 0)
      });
    }
  }, [title, multiple, expiration, choices]); // HANDLERS

  const handleChangeTitle = event => {
    setTitle(event.target.value);
  };

  const handleChangeMultiple = event => {
    setMultiple(event.target.checked);
  };

  const handleChangeExpiration = value => {
    setExpiration(value);
  };

  const handleAddChoice = () => {
    setChoices([...choices, Object.assign({}, DEFAULT_CHOICE)]);
  };

  const handleChangeChoice = index => {
    return event => {
      const _choices = [...choices];
      _choices[index].choice = event.target.value;
      setChoices(_choices);
    };
  };

  const handleDeleteChoice = index => {
    return () => {
      const _choices = [...choices];

      _choices.splice(index, 1);

      setChoices(_choices);
    };
  };

  const minDate = new Date();
  minDate.setDate(minDate.getDate() + _Composer.COMPOSER_POLL_MIN_CLOSE_DATE_DELTA);
  return /*#__PURE__*/_react.default.createElement(Root, {
    id: id,
    className: (0, _classnames.default)(classes.root, className)
  }, /*#__PURE__*/_react.default.createElement(_material.Box, {
    className: classes.title
  }, /*#__PURE__*/_react.default.createElement(_material.TextField, {
    label: /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: "ui.composer.poll.title",
      defaultMessage: "ui.composer.poll.title"
    }),
    variant: "outlined",
    value: title,
    onChange: handleChangeTitle,
    fullWidth: true,
    error: Boolean(titleError),
    helperText: titleError ? titleError.error : null,
    InputProps: {
      endAdornment: /*#__PURE__*/_react.default.createElement(_material.Typography, {
        variant: "body2"
      }, _Composer.COMPOSER_POLL_TITLE_MAX_LENGTH - title.length)
    }
  })), /*#__PURE__*/_react.default.createElement(_material.Box, {
    className: classes.choices
  }, /*#__PURE__*/_react.default.createElement(_reactSortablejs.ReactSortable, {
    list: [...choices],
    setList: newSort => setChoices(newSort),
    tag: SortableComponent
  }, choices.map((choice, index) => /*#__PURE__*/_react.default.createElement(_material.TextField, {
    key: index,
    placeholder: intl.formatMessage(messages.choicePlaceholder),
    value: choice.choice,
    onChange: handleChangeChoice(index),
    variant: "outlined",
    InputProps: {
      startAdornment: /*#__PURE__*/_react.default.createElement(_InputAdornment.default, {
        position: "start"
      }, /*#__PURE__*/_react.default.createElement(_Icon.default, null, "check")),
      endAdornment: /*#__PURE__*/_react.default.createElement(_InputAdornment.default, {
        position: "end"
      }, /*#__PURE__*/_react.default.createElement(_material.Tooltip, {
        title: choices.length <= _Composer.COMPOSER_POLL_MIN_CHOICES ? /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
          id: "ui.composer.poll.choice.delete.disabled",
          defaultMessage: "ui.composer.poll.choice.delete.disabled"
        }) : /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
          id: "ui.composer.poll.choice.delete",
          defaultMessage: "ui.composer.poll.choice.delete"
        })
      }, /*#__PURE__*/_react.default.createElement("span", null, /*#__PURE__*/_react.default.createElement(_material.IconButton, {
        onClick: handleDeleteChoice(index),
        disabled: choices.length <= _Composer.COMPOSER_POLL_MIN_CHOICES,
        edge: "end"
      }, /*#__PURE__*/_react.default.createElement(_Icon.default, null, "delete")))))
    }
  })))), /*#__PURE__*/_react.default.createElement(_material.Box, {
    className: classes.choiceNew
  }, /*#__PURE__*/_react.default.createElement(_material.Button, {
    color: "inherit",
    variant: "text",
    onClick: handleAddChoice
  }, /*#__PURE__*/_react.default.createElement(_Icon.default, null, "add"), /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.composer.poll.choice.add",
    defaultMessage: "ui.composer.choice.add"
  }))), /*#__PURE__*/_react.default.createElement(_material.Divider, null), /*#__PURE__*/_react.default.createElement(_material.FormGroup, {
    className: classes.metadata
  }, /*#__PURE__*/_react.default.createElement(_material.FormControlLabel, {
    control: /*#__PURE__*/_react.default.createElement(_material.Checkbox, {
      checked: multiple,
      onChange: handleChangeMultiple
    }),
    label: /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: "ui.composer.poll.multiple",
      defaultMessage: "ui.composer.poll.multiple"
    })
  }), /*#__PURE__*/_react.default.createElement(_lab.LocalizationProvider, {
    dateAdapter: _AdapterDateFns.default,
    locale: localeMap[intl.locale]
  }, /*#__PURE__*/_react.default.createElement(_lab.DatePicker, {
    label: /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: "ui.composer.poll.expiration",
      defaultMessage: "ui.composer.poll.expiration"
    }),
    value: expiration,
    onChange: handleChangeExpiration,
    renderInput: params => /*#__PURE__*/_react.default.createElement(_material.TextField, params),
    minDate: minDate
  }))));
};

exports.default = _default;