'use strict';

var iconsReact = require('@cloudtower/icons-react');
var core = require('@linaria/core');
var index = require('../Icon/index.js');
var style = require('./style.js');
var TableFormBodyCell = require('./TableFormBodyCell.js');
var types = require('./types.js');
var utils = require('./utils.js');
var index$2 = require('../Tooltip/index.js');
var index$1 = require('../Typo/index.js');
var useParrotTranslation = require('../../hooks/useParrotTranslation.js');
var antd = require('antd');
var React = require('react');
var reactBeautifulDnd = require('react-beautiful-dnd');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var React__default = /*#__PURE__*/_interopDefault(React);

var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
  for (var prop in b || (b = {}))
    if (__hasOwnProp.call(b, prop))
      __defNormalProp(a, prop, b[prop]);
  if (__getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(b)) {
      if (__propIsEnum.call(b, prop))
        __defNormalProp(a, prop, b[prop]);
    }
  return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
const TableFormRowDeleteAction = (props) => {
  var _a, _b, _c, _d;
  const { deleteConfig, row, updateData, rowIndex, data } = props;
  const { t } = useParrotTranslation();
  if (typeof (row == null ? void 0 : row.deletable) === "function" && !row.deletable(rowIndex, data)) {
    return /* @__PURE__ */ React__default.default.createElement(React__default.default.Fragment, null);
  }
  const disableActionsFromRowConfig = typeof (row == null ? void 0 : row.disableActions) === "object" ? row.disableActions : (_b = (_a = row == null ? void 0 : row.disableActions) == null ? void 0 : _a.call(row, rowIndex, data)) != null ? _b : [];
  const isRowDeleteDisabled = (_d = disableActionsFromRowConfig.includes("delete") || ((_c = deleteConfig == null ? void 0 : deleteConfig.specifyRowDeleteDisabled) == null ? void 0 : _c.call(deleteConfig, rowIndex, data))) != null ? _d : false;
  const DeleteIcon = /* @__PURE__ */ React__default.default.createElement(
    index,
    {
      "data-testid": "eagle-table-form-row-action",
      className: core.cx("delete-row-icon", isRowDeleteDisabled && "disabled"),
      src: iconsReact.XmarkRemove16SecondaryIcon,
      hoverSrc: isRowDeleteDisabled ? void 0 : iconsReact.XmarkRemove16RegularRedIcon,
      onClick: () => {
        if (isRowDeleteDisabled)
          return;
        const newData = [...data];
        newData.splice(rowIndex, 1);
        updateData(newData);
      }
    }
  );
  const DeleteAction = isRowDeleteDisabled ? DeleteIcon : /* @__PURE__ */ React__default.default.createElement(index$2, { title: t("components.remove") }, DeleteIcon);
  return DeleteAction;
};
const TableFormRow = (props) => {
  var _a;
  const {
    data,
    columns,
    latestData,
    disabled,
    passwordVisible,
    deleteConfig,
    draggable,
    rowIndex,
    provided,
    snapshot,
    validateTriggerType = types.ValidateTriggerType.Normal,
    row,
    errors = [],
    updateData,
    onBodyBlur,
    renderRowDescription,
    validateAllCount,
    onValidate
  } = props;
  const rowData = data[rowIndex];
  const errorFromProps = errors[rowIndex];
  const rowLevelError = typeof errorFromProps === "string" ? errorFromProps : void 0;
  const [rowError, setRowError] = React.useState(rowLevelError);
  const rowValidator = (row == null ? void 0 : row.validator) || props.rowValidator;
  const cellsLevelError = errorFromProps && typeof errorFromProps === "object" ? errorFromProps : null;
  React.useEffect(() => {
    setRowError(rowLevelError);
  }, [rowLevelError]);
  React.useEffect(() => {
    onValidate == null ? void 0 : onValidate(`table_row_${rowIndex}`, !rowError);
  }, [onValidate, rowError, rowIndex]);
  const rowDeletable = typeof (row == null ? void 0 : row.deletable) === "boolean" ? row.deletable : (_a = typeof (row == null ? void 0 : row.deletable) === "function" || (deleteConfig == null ? void 0 : deleteConfig.deletable)) != null ? _a : false;
  const getRowValidateResult = React.useCallback(
    (rowData2) => {
      if (!rowValidator)
        return rowLevelError;
      const result = rowValidator(rowIndex, rowData2);
      setRowError(result);
      return result;
    },
    [rowValidator, rowIndex, rowLevelError]
  );
  const Cells = columns.map((col) => {
    const cellError = cellsLevelError == null ? void 0 : cellsLevelError[col.key];
    return /* @__PURE__ */ React__default.default.createElement(
      TableFormBodyCell.TableFormBodyCell,
      {
        key: col.key,
        column: col,
        data,
        latestData,
        disabled,
        index: rowIndex,
        onChange: updateData,
        onBlur: onBodyBlur,
        visible: passwordVisible,
        validateTriggerType,
        isRowError: !!rowError,
        getRowValidateResult,
        validateAllCount,
        error: cellError,
        onValidate
      }
    );
  });
  const DraggableHandle = React.useMemo(
    () => draggable && provided ? /* @__PURE__ */ React__default.default.createElement(style.DraggableHandleWrapper, __spreadValues({}, provided.dragHandleProps), /* @__PURE__ */ React__default.default.createElement(
      index,
      {
        src: iconsReact.HandlePoint816SecondaryIcon,
        hoverSrc: iconsReact.HandlePoint816BlueIcon
      }
    )) : null,
    [draggable, provided]
  );
  const RowDescription = React.useMemo(() => {
    const rowDescFuncParams = {
      rowIndex,
      rowData,
      latestData
    };
    const DescriptionResult = typeof (row == null ? void 0 : row.descriptions) == "object" ? row.descriptions[rowIndex] : typeof (row == null ? void 0 : row.customizedDescription) === "function" ? row.customizedDescription(rowDescFuncParams) : (renderRowDescription == null ? void 0 : renderRowDescription(rowDescFuncParams)) || null;
    return typeof DescriptionResult === "string" ? /* @__PURE__ */ React__default.default.createElement("p", { className: core.cx(index$1.Typo.Label.l4_regular, "row-description") }, DescriptionResult) : DescriptionResult;
  }, [rowIndex, rowData, latestData, renderRowDescription, row]);
  return /* @__PURE__ */ React__default.default.createElement(
    antd.List.Item,
    {
      key: rowIndex,
      "data-testid": "eagle-table-form-row-for-test",
      className: core.cx(
        "eagle-table-form-row",
        (snapshot == null ? void 0 : snapshot.isDragging) && "isDragging"
      ),
      actions: rowDeletable ? [
        /* @__PURE__ */ React__default.default.createElement(
          TableFormRowDeleteAction,
          {
            data,
            rowIndex,
            deleteConfig,
            row,
            updateData
          }
        )
      ] : void 0
    },
    DraggableHandle,
    Cells,
    rowError ? /* @__PURE__ */ React__default.default.createElement("p", { className: core.cx(index$1.Typo.Label.l4_regular, "row-error-message") }, rowError) : null,
    RowDescription
  );
};
const TableFormBodyRows = React.memo((props) => {
  const { data, draggable, updateData } = props;
  const onDragEnd = React.useCallback(
    (result) => {
      var _a;
      const fromIndex = result.source.index;
      const toIndex = (_a = result.destination) == null ? void 0 : _a.index;
      if (typeof toIndex !== "number" || toIndex === fromIndex)
        return;
      const newData = utils.moveItemInArray(data, fromIndex, toIndex);
      updateData(newData);
    },
    [data, updateData]
  );
  return draggable ? /* @__PURE__ */ React__default.default.createElement(reactBeautifulDnd.DragDropContext, { onDragEnd }, /* @__PURE__ */ React__default.default.createElement(reactBeautifulDnd.Droppable, { droppableId: "droppable" }, (provided) => /* @__PURE__ */ React__default.default.createElement(
    "div",
    __spreadValues({
      className: "draggable-container",
      ref: provided.innerRef
    }, provided.droppableProps),
    data.map((_d, i) => /* @__PURE__ */ React__default.default.createElement(
      reactBeautifulDnd.Draggable,
      {
        draggableId: `draggable-id-${i}`,
        key: `draggable-id-${i}`,
        index: i
      },
      (provided2, snapshot) => /* @__PURE__ */ React__default.default.createElement("div", __spreadValues({ ref: provided2.innerRef }, provided2.draggableProps), /* @__PURE__ */ React__default.default.createElement(
        TableFormRow,
        __spreadProps(__spreadValues({}, props), {
          rowIndex: i,
          provided: provided2,
          snapshot
        })
      ))
    )),
    provided.placeholder
  ))) : /* @__PURE__ */ React__default.default.createElement(React__default.default.Fragment, null, data.map((_d, i) => /* @__PURE__ */ React__default.default.createElement(TableFormRow, __spreadProps(__spreadValues({}, props), { rowIndex: i, key: `table-row-${i}` }))));
});
var TableFormBodyRows$1 = TableFormBodyRows;

module.exports = TableFormBodyRows$1;
