"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TableEditableCell = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const Text_1 = require("../Text");
const Icon_1 = require("../Icon");
const DatePicker_1 = require("../DatePicker");
const Select_1 = require("../Select");
const icons_1 = require("../../theme/icons");
const TableEditableCell = ({ cell, data, updateData, setSkipTableReset, }) => {
    const [currentValue, setCurrentValue] = (0, react_1.useState)(cell.value);
    const [isEditting, setIsEditting] = (0, react_1.useState)(false);
    const isOnClickEditor = cell.column.editor &&
        (cell.column.editor.name === DatePicker_1.DatePicker.name ||
            cell.column.editor.name === Select_1.Select.name);
    const editCell = () => {
        if (cell.column.editor)
            setIsEditting(true);
    };
    const saveNewData = (value) => {
        setSkipTableReset(true);
        updateData(data.map((row, index) => {
            if (index === cell.row.index) {
                return Object.assign(Object.assign({}, data[index]), { [cell.column.id]: value !== undefined ? value : currentValue });
            }
            return row;
        }));
        setIsEditting(false);
        setTimeout(() => {
            setSkipTableReset(false);
        }, 300);
    };
    const handleChange = (e) => {
        const newValue = e && e.target ? e.target.value : e;
        setCurrentValue(newValue);
        if (isOnClickEditor)
            saveNewData(newValue);
    };
    const handleBlur = () => {
        if (!isOnClickEditor)
            saveNewData();
    };
    (0, react_1.useEffect)(() => {
        if (cell.value !== currentValue) {
            setCurrentValue(cell.value);
        }
    }, [cell.value]);
    return isEditting ? ((0, jsx_runtime_1.jsx)(cell.column.editor, Object.assign({ value: currentValue, onChange: handleChange, onBlur: handleBlur, autoFocus: true }, cell.column.editorProps), void 0)) : ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(Text_1.Text, Object.assign({ variant: "span", format: "b2", color: "gray1" }, { onClick: editCell }, (cell.column.editor ? { className: 'canEdit' } : {}), { children: cell.column.formatter
                    ? cell.column.formatter(cell.value, cell.row.index)
                    : cell.render('Cell') }), void 0), cell.column.editor && ((0, jsx_runtime_1.jsx)(Icon_1.Icon, { variant: "basic", icon: icons_1.polyIcons.PencilOutline, size: "16px", color: "gray3", margin: "-2px 0 0 s" }, void 0)), cell.column.footer && (0, jsx_runtime_1.jsx)("div", { children: cell.column.footer(cell.row.index) }, void 0)] }, void 0));
};
exports.TableEditableCell = TableEditableCell;
//# sourceMappingURL=TableEditableCell.js.map