import AddRowButton from './AddRowButton.js';
import { TableFormWrapper, DraggableHandleWrapper } from './style.js';
import TableFormBodyRows from './TableFormBodyRows.js';
import { BatchInputListHeaderCell } from './TableFormHeaderCell.js';
import { List } from 'antd';
import React__default, { useState, useRef, useCallback, useImperativeHandle, useMemo } from '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 TableForm = React__default.forwardRef(
  (props, ref) => {
    var _a, _b;
    const {
      // The empty array is valid data so do not initialize "defaultData" with it
      defaultData,
      columns,
      disabled,
      rowAddConfig,
      deleteConfig,
      size = "default",
      className,
      disableBatchFilling = false,
      validateTriggerType,
      maxHeight,
      renderRowDescription,
      rowValidator,
      onHeaderChange,
      onHeaderBlur,
      onBodyChange,
      onBodyAdd,
      onBodyBlur,
      row,
      errors,
      hideEmptyTable
    } = props;
    const [data, setData] = useState(defaultData || []);
    const [passwordVisible, setPasswordVisible] = useState(false);
    const [latestData, setLatestData] = useState(defaultData || []);
    const [validateAllCount, setValidateAllCount] = useState(0);
    const rowSplitType = (row == null ? void 0 : row.splitType) || props.rowSplitType || "border";
    const draggable = (_b = (_a = row == null ? void 0 : row.draggable) != null ? _a : props.draggable) != null ? _b : false;
    const formValidMapRef = useRef({});
    const updateData = useCallback(
      (value, rowIndex, columnKey) => {
        setLatestData(value);
        setData(value);
        onBodyChange == null ? void 0 : onBodyChange(value, rowIndex, columnKey);
      },
      [onBodyChange]
    );
    const addData = useCallback(
      (value) => {
        setLatestData(value);
        setData(value);
        onBodyChange == null ? void 0 : onBodyChange(value);
        const rowIndex = value.length - 1;
        onBodyAdd == null ? void 0 : onBodyAdd(value, rowIndex);
      },
      [onBodyChange, onBodyAdd]
    );
    const handleBatchChange = useCallback(
      (newData, columnKey, shouldUpdateData) => {
        setLatestData(newData);
        onHeaderChange == null ? void 0 : onHeaderChange(newData, columnKey);
        if (shouldUpdateData) {
          setData(newData);
          onBodyChange == null ? void 0 : onBodyChange(newData, void 0, columnKey);
        }
      },
      [onHeaderChange, onBodyChange]
    );
    const handleBatchBlur = useCallback(
      (columnKey, error) => {
        if (error) {
          const newData = latestData.map((cell) => {
            return __spreadProps(__spreadValues({}, cell), {
              [columnKey]: ""
            });
          });
          setLatestData(newData);
          onHeaderBlur == null ? void 0 : onHeaderBlur(newData, columnKey);
        } else {
          setData(latestData);
          onBodyChange == null ? void 0 : onBodyChange(latestData, void 0, columnKey);
          onHeaderBlur == null ? void 0 : onHeaderBlur(latestData, columnKey);
        }
      },
      [latestData, onHeaderBlur, onBodyChange]
    );
    useImperativeHandle(
      ref,
      () => ({
        setData: (data2) => {
          updateData(data2);
        },
        setDataWithoutTriggerChange: (data2) => {
          setLatestData(data2);
          setData(data2);
        },
        validateWholeFields() {
          formValidMapRef.current = {};
          setValidateAllCount((c) => c + 1);
        },
        isValid() {
          return Object.values(formValidMapRef.current).every(
            (v) => v === true
          );
        }
      }),
      [updateData]
    );
    const onValidate = (id, isValid) => {
      formValidMapRef.current[id] = isValid;
    };
    const headerCells = columns.map((col) => {
      return /* @__PURE__ */ React__default.createElement(
        BatchInputListHeaderCell,
        {
          key: col.key,
          data,
          latestData,
          disabled,
          column: col,
          disableBatchFilling,
          onChange: handleBatchChange,
          onBlur: handleBatchBlur,
          onVisibleChange: setPasswordVisible
        }
      );
    });
    const tableFormWrapperStyle = useMemo(
      () => maxHeight ? {
        maxHeight: typeof maxHeight === "number" ? maxHeight + "px" : maxHeight
      } : void 0,
      [maxHeight]
    );
    return /* @__PURE__ */ React__default.createElement("div", { className }, hideEmptyTable && data.length < 1 ? null : /* @__PURE__ */ React__default.createElement(
      TableFormWrapper,
      {
        "data-testid": "eagle-table-form-wrapper",
        className: `table-form row-split-by-${rowSplitType}`,
        style: tableFormWrapperStyle
      },
      /* @__PURE__ */ React__default.createElement(List, { size, className: `size-${size}` }, /* @__PURE__ */ React__default.createElement(
        List.Item,
        {
          className: "eagle-table-form-header",
          actions: (deleteConfig == null ? void 0 : deleteConfig.deletable) || (row == null ? void 0 : row.deletable) ? [/* @__PURE__ */ React__default.createElement(React__default.Fragment, null)] : void 0
        },
        draggable ? /* @__PURE__ */ React__default.createElement(DraggableHandleWrapper, null) : null,
        headerCells
      ), /* @__PURE__ */ React__default.createElement(
        TableFormBodyRows,
        {
          data,
          latestData,
          columns,
          passwordVisible,
          deleteConfig,
          disabled,
          draggable,
          rowSplitType,
          validateTriggerType,
          row,
          onBodyBlur,
          updateData,
          renderRowDescription,
          rowValidator,
          validateAllCount,
          errors,
          onValidate
        }
      ))
    ), (rowAddConfig == null ? void 0 : rowAddConfig.addible) ? /* @__PURE__ */ React__default.createElement(
      AddRowButton,
      {
        style: { marginTop: hideEmptyTable && !data.length ? 0 : 8 },
        config: rowAddConfig,
        addData,
        columns,
        data
      }
    ) : null);
  }
);
var TableForm$1 = TableForm;

export { TableForm$1 as default };
