import _createForOfIteratorHelper from "@babel/runtime/helpers/createForOfIteratorHelper";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
import { defineMessage, useIntl } from 'react-intl';
import { uniqueId } from 'lodash';
import { useState } from 'react';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import TextField from '@material-ui/core/TextField';
import IconButton from '@material-ui/core/IconButton';
import DeleteIcon from '@material-ui/icons/Delete';
import AddIcon from '@material-ui/icons/Add';
import { makeStyles } from '@material-ui/core/styles';
import { defineMessages } from '@formatjs/intl';
import { utils } from '@visma/rjsf-core';
import { FormHelperText } from '@material-ui/core';
import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
var useStyles = makeStyles({
  inputLabelRoot: {
    clip: "rect(0 0 0 0)",
    clipPath: "inset(50%)",
    height: 1,
    overflow: "hidden",
    position: "absolute",
    whiteSpace: "nowrap",
    width: 1
  },
  inputFormControl: {
    "label + &": {
      marginTop: 0
    }
  }
});
var tableLabel = defineMessage({
  id: "Od6CNk",
  defaultMessage: [{
    "type": 1,
    "value": "tableName"
  }, {
    "type": 0,
    "value": " sarake "
  }, {
    "type": 1,
    "value": "columnName"
  }, {
    "type": 0,
    "value": " rivi "
  }, {
    "type": 1,
    "value": "row"
  }]
});
var defaultValue = '';

var makeTable = function makeTable(initValues, rows, cols) {
  return _toConsumableArray(Array(rows)).map(function (_, rowNum) {
    return _toConsumableArray(Array(cols)).map(function (_, colNum) {
      return initValues[rowNum] && initValues[rowNum][colNum] || defaultValue;
    });
  });
};

var getTotalRows = function getTotalRows(_ref) {
  var _uiSchema$uiOptions, _formData$table;

  var formData = _ref.formData,
      uiSchema = _ref.uiSchema;
  var field = ((_uiSchema$uiOptions = uiSchema['ui:options']) === null || _uiSchema$uiOptions === void 0 ? void 0 : _uiSchema$uiOptions.element) || {};
  var _field$tableRowMinimu = field.tableRowMinimum,
      tableRowMinimum = _field$tableRowMinimu === void 0 ? 0 : _field$tableRowMinimu;
  return Math.max(Number(tableRowMinimum), (formData === null || formData === void 0 ? void 0 : (_formData$table = formData.table) === null || _formData$table === void 0 ? void 0 : _formData$table.length) || 0);
};

var getTotalColumns = function getTotalColumns(_ref2) {
  var uiSchema = _ref2.uiSchema;
  var field = uiSchema['ui:options'].element || {};
  var _field$tableColumns = field.tableColumns,
      tableColumns = _field$tableColumns === void 0 ? [] : _field$tableColumns;
  return tableColumns.length || 0;
};

function TableField(props) {
  var disabled = props.disabled,
      readonly = props.readonly,
      onChange = props.onChange,
      formData = props.formData,
      errorSchema = props.errorSchema,
      uiSchema = props.uiSchema,
      idSchema = props.idSchema,
      schema = props.schema,
      rawErrors = props.rawErrors;
  var config = uiSchema['ui:options'].element;
  var _config$tableAddAllow = config.tableAddAllowed,
      tableAddAllowed = _config$tableAddAllow === void 0 ? false : _config$tableAddAllow,
      _config$tableRowMinim = config.tableRowMinimum,
      tableRowMinimum = _config$tableRowMinim === void 0 ? 0 : _config$tableRowMinim,
      _config$tableRowMaxim = config.tableRowMaximum,
      tableRowMaximum = _config$tableRowMaxim === void 0 ? Number.MAX_SAFE_INTEGER : _config$tableRowMaxim,
      _config$useLabel = config.useLabel,
      useLabel = _config$useLabel === void 0 ? false : _config$useLabel,
      _config$tableColumns = config.tableColumns,
      tableColumns = _config$tableColumns === void 0 ? [] : _config$tableColumns,
      _config$rowTitles = config.rowTitles,
      rowTitles = _config$rowTitles === void 0 ? [] : _config$rowTitles,
      _config$useRowTitles = config.useRowTitles,
      useRowTitles = _config$useRowTitles === void 0 ? false : _config$useRowTitles,
      label = config.label,
      title = config.title,
      description = config.description,
      id = config.id;
  var totalRows = getTotalRows(props);
  var totalCols = getTotalColumns(props);
  var intl = useIntl();

  var _useState = useState(uniqueId()),
      _useState2 = _slicedToArray(_useState, 2),
      rev = _useState2[0],
      setRev = _useState2[1];

  var classes = useStyles();
  var ariaDescribedby = utils.ariaDescribedBy(idSchema.$id, uiSchema, rawErrors);

  var onPropertyChange = function onPropertyChange(tableData) {
    onChange({
      table: tableData
    }, errorSchema);

    if (totalRows !== tableData.length) {
      setRev(uniqueId());
    }
  };

  var onAddRow = function onAddRow(_) {
    onPropertyChange(makeTable(tableData, totalRows + 1, totalCols));
  };

  var onRemoveRow = function onRemoveRow(rowNum) {
    onPropertyChange(tableData.filter(function (_, index) {
      return index !== rowNum;
    }));
  };

  var tableData = makeTable((formData === null || formData === void 0 ? void 0 : formData.table) || [], totalRows, totalCols);

  var tableHeaders = function tableHeaders(ignoreTitleColumn) {
    var headers = tableColumns.map(function (columnName, index) {
      return /*#__PURE__*/_jsx(TableCell, {
        children: columnName
      }, index);
    });

    if (useRowTitles && !ignoreTitleColumn) {
      headers.unshift( /*#__PURE__*/_jsx(TableCell, {
        children: ""
      }, -1));
    }

    return headers;
  };

  var tableCells = tableData.map(function (row, rowNum) {
    return /*#__PURE__*/_jsxs(TableRow, {
      children: [useRowTitles && /*#__PURE__*/_jsx(TableCell, {
        style: {
          fontWeight: 'bold'
        },
        children: rowNum < rowTitles.length ? rowTitles[rowNum] : ''
      }), row.map(function (_, colNum) {
        return /*#__PURE__*/_jsx(TableCell, {
          children: /*#__PURE__*/_jsx(TextField, {
            id: "".concat(id, "-").concat(rowNum, "-").concat(colNum),
            style: {
              width: '100%'
            },
            variant: "outlined",
            size: "small",
            "aria-label": intl.formatMessage(tableLabel, {
              tableName: useLabel ? label : title,
              columnName: tableColumns[colNum],
              row: rowNum + 1
            }),
            label: useLabel ? label : title,
            defaultValue: tableData[rowNum][colNum],
            disabled: disabled,
            readOnly: readonly,
            onChange: function onChange(event) {
              tableData[rowNum][colNum] = event.target.value || defaultValue;
              onPropertyChange(tableData);
            },
            InputProps: {
              classes: {
                formControl: classes.inputFormControl
              },
              'aria-describedby': ariaDescribedby
            },
            InputLabelProps: {
              htmlFor: "".concat(id, "-").concat(rowNum, "-").concat(colNum),
              shrink: false,
              className: classes.inputLabelRoot
            }
          })
        }, "col-".concat(colNum));
      }).concat(tableData.length > tableRowMinimum ? rowNum >= tableRowMinimum ? /*#__PURE__*/_jsx(TableCell, {
        children: /*#__PURE__*/_jsx(IconButton, {
          "aria-label": intl.formatMessage({
            id: "7A0Mm1",
            defaultMessage: [{
              "type": 0,
              "value": "Poista rivi"
            }]
          }),
          onClick: function onClick(_) {
            onRemoveRow(rowNum);
          },
          disabled: disabled || readonly,
          children: /*#__PURE__*/_jsx(DeleteIcon, {
            alt: intl.formatMessage({
              id: "7A0Mm1",
              defaultMessage: [{
                "type": 0,
                "value": "Poista rivi"
              }]
            })
          })
        })
      }, 'remove') : /*#__PURE__*/_jsx(TableCell, {
        children: "\xA0"
      }, 'remove') : [])]
    }, "row-".concat(rowNum, "-").concat(rev));
  });
  return /*#__PURE__*/_jsxs("div", {
    children: [/*#__PURE__*/_jsx(FormHelperText, {
      id: "".concat(idSchema.$id, "__description"),
      component: "span",
      children: description
    }), /*#__PURE__*/_jsx(TableContainer, {
      children: /*#__PURE__*/_jsxs(Table, {
        size: "small",
        children: [/*#__PURE__*/_jsx(TableHead, {
          children: /*#__PURE__*/_jsx(TableRow, {
            children: tableHeaders()
          })
        }), /*#__PURE__*/_jsx(TableBody, {
          children: tableCells
        })]
      })
    }), tableAddAllowed && totalRows < tableRowMaximum && /*#__PURE__*/_jsx(IconButton, {
      "aria-label": intl.formatMessage({
        id: "06GmPX",
        defaultMessage: [{
          "type": 0,
          "value": "Lisää rivi"
        }]
      }),
      onClick: onAddRow,
      disabled: disabled || readonly,
      edge: "start",
      style: {
        margin: '5px'
      },
      children: /*#__PURE__*/_jsx(AddIcon, {
        alt: intl.formatMessage({
          id: "06GmPX",
          defaultMessage: [{
            "type": 0,
            "value": "Lisää rivi"
          }]
        })
      })
    })]
  });
}

export default (function (_ref3) {
  var config = _ref3.config;
  return {
    schema: {
      format: 'table',
      type: 'object',
      properties: {
        table: {
          type: 'array',
          "default": [],
          items: {
            type: 'array',
            items: {
              type: 'string'
            }
          }
        }
      }
    },
    uiSchema: {
      'ui:field': TableField
    }
  };
});
export var name = defineMessage({
  id: "4QvGOn",
  defaultMessage: [{
    "type": 0,
    "value": "Taulukko"
  }]
});
var validationMessages = defineMessages({
  emptyValue: {
    id: "WBQmgL",
    defaultMessage: [{
      "type": 0,
      "value": "\""
    }, {
      "type": 1,
      "value": "title"
    }, {
      "type": 0,
      "value": "\" ei saa sisältää tyhjiä soluja."
    }]
  }
});
export var validators = {
  required: {
    name: defineMessage({
      id: "WHQ4l+",
      defaultMessage: [{
        "type": 0,
        "value": "Pakollinen taulukko"
      }]
    }),
    fn: function fn(value, element) {
      var _value$table;

      if (value && ((_value$table = value.table) === null || _value$table === void 0 ? void 0 : _value$table.length) > 0) {
        var _iterator = _createForOfIteratorHelper(value.table),
            _step;

        try {
          for (_iterator.s(); !(_step = _iterator.n()).done;) {
            var row = _step.value;

            var _iterator2 = _createForOfIteratorHelper(row),
                _step2;

            try {
              for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
                var item = _step2.value;

                if (item === undefined || item === '') {
                  return validationMessages.emptyValue;
                }
              }
            } catch (err) {
              _iterator2.e(err);
            } finally {
              _iterator2.f();
            }
          }
        } catch (err) {
          _iterator.e(err);
        } finally {
          _iterator.f();
        }
      } else {
        return validationMessages.emptyValue;
      }
    }
  }
};
export var elementType = 'field';
//# sourceMappingURL=tableField.js.map