import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useState } from "react";
import { TableCell, TableRow, IconButton, FormControlLabel, MenuItem, Tooltip, Menu, FormControl, InputLabel, } from "@material-ui/core";
import styled from "styled-components";
import { Draggable } from 'react-beautiful-dnd';
import { ObserveState } from "../../CommonUI/StateManagement/ObserveState";
import VariablePicker from "../../CommonUI/VariablePicker";
import { StateManager } from "../../CommonUI/StateManagement/StateManager";
import { InlineTextEdit } from "../../CommonUI/InlineTextEdit";
import { FormRuleType } from "../FormRule";
import { AttentionIcon } from "../../CommonUI/Icon/AttentionIcon";
import { StyledCheckBox } from "../../CommonUI/Components/Checkbox";
import { StyledSwitch } from "../../CommonUI/Components/Switch";
import { XExpressionView } from "../../Expressions/XExpressionView";
import { DeleteIcon } from "../../CommonUI/Icon/DeleteIcon";
import { StyledFormControlLabel } from "../../CommonUI/Components/FormControlLabel";
import { StyledSelect } from "../../CommonUI/Components/Select";
import RadioGroupWithContent from "../../CommonUI/Components/RadioGroupWithContent";
import { StyledButton } from "../../CommonUI/Components/Button";
import { CloseGrayIcon } from "../../CommonUI/Icon/CloseGrayIcon";
export const XFormRuleRow = ({ form, rule, index, onAction, }) => {
    return (_jsx(ObserveState, { listenTo: rule, control: () => {
            let designIssues = rule.getDesignValidationIssues(form);
            let expressionIssues = rule.expression.expressionRoot.getValidationIssues();
            return (_jsx(Draggable, Object.assign({ draggableId: "ruleRowDrag" + index, index: index }, { children: (provided, snapshot) => {
                    return (_jsxs(StyledTableRow, Object.assign({ ref: (node) => {
                            provided.innerRef(node);
                        } }, provided.draggableProps, provided.dragHandleProps, { children: [_jsx(TableCell, { children: _jsxs(CellRender, { children: [_jsxs(StyledSelect, Object.assign({ value: rule.ruleType, fullWidth: true, onChange: (event) => {
                                                rule.ruleType = event.target.value;
                                                StateManager.propertiesChanged(rule, ["ruleType", "data"]);
                                            }, "data-testid": "XFormRule-ruleType" }, { children: [_jsx(MenuItem, Object.assign({ value: FormRuleType.CHANGE_FOCUS }, { children: FormRuleType.CHANGE_FOCUS }), void 0),
                                                _jsx(MenuItem, Object.assign({ value: FormRuleType.CHANGE_VALUE }, { children: FormRuleType.CHANGE_VALUE }), void 0),
                                                _jsx(MenuItem, Object.assign({ value: FormRuleType.CONTROL_ENABLED }, { children: FormRuleType.CONTROL_ENABLED }), void 0),
                                                _jsx(MenuItem, Object.assign({ value: FormRuleType.CONTROL_VISIBILITY }, { children: FormRuleType.CONTROL_VISIBILITY }), void 0),
                                                _jsx(MenuItem, Object.assign({ value: FormRuleType.EXIT_FORM }, { children: FormRuleType.EXIT_FORM }), void 0),
                                                _jsx(MenuItem, Object.assign({ value: FormRuleType.VALIDATION }, { children: FormRuleType.VALIDATION }), void 0)] }), void 0),
                                        _jsx(WatchValuesRender, Object.assign({ "data-testid": "XFormRule-watchingValues" }, { children: _jsx(CheckboxListLayer, { items: form.getAllFormData().map((f) => ({ label: f.name })), onChange: (mode, newValues) => {
                                                    rule.watchingValuesMode = mode;
                                                    rule.watchingValues = newValues;
                                                    StateManager.propertyChanged(rule, "watchingValues");
                                                }, value: rule.watchingValues, placeholder: "Select watching values...", label: "Run Rules On Value Change", valueMode: rule.watchingValuesMode }, void 0) }), void 0)] }, void 0) }, void 0),
                            _jsx(TableCell, { children: _jsx(CellRender, Object.assign({ align: "center", "data-testid": "XFormRule-formEnabled" }, { children: _jsx(FormControlLabel, { control: _jsx(StyledSwitch, { color: "primary", checked: rule.enabled, onChange: (event) => {
                                                rule.enabled = event.target.checked;
                                                StateManager.propertyChanged(rule, "enabled");
                                            } }, void 0), label: "" }, void 0) }), void 0) }, void 0),
                            _jsx(TableCell, { children: _jsx(CellRender, Object.assign({ "data-testid": "XFormRule-expressions" }, { children: _jsxs(ExpressionViewRender, { children: [_jsx(XExpressionView, { expression: rule.expression, color: {
                                                    result: "#4050A6",
                                                    expression: "#4050A6",
                                                    variable: "rgba(39, 41, 50, 0.6)",
                                                    value: "rgb(39, 41, 50)",
                                                }, hideValidation: true }, void 0),
                                            expressionIssues.length > 0 && (_jsx(Tooltip, Object.assign({ title: expressionIssues[0].issue }, { children: _jsx("div", Object.assign({ className: "error-icon" }, { children: _jsx(AttentionIcon, {}, void 0) }), void 0) }), void 0))] }, void 0) }), void 0) }, void 0),
                            _jsx(TableCell, { children: _jsx(CellRender, { children: _jsxs(OtherParameters, Object.assign({ "data-testid": "XFormRule-otherparameters" }, { children: [_jsx(RuleDataPropertyEditor, { rule: rule, form: form }, void 0),
                                            designIssues.length > 0 && (_jsx(Tooltip, Object.assign({ title: designIssues[0].issue }, { children: _jsx("div", Object.assign({ className: "error-icon" }, { children: _jsx(AttentionIcon, {}, void 0) }), void 0) }), void 0))] }), void 0) }, void 0) }, void 0),
                            _jsx(TableCell, { children: _jsx(CellRender, Object.assign({ "data-testid": "XFormRule-actions" }, { children: _jsx(IconButton, Object.assign({ onClick: (event) => {
                                            onAction(event.currentTarget);
                                        }, className: "ActionButton" }, { children: _jsx(DeleteIcon, {}, void 0) }), void 0) }), void 0) }, void 0)] }), void 0));
                } }), void 0));
        } }, void 0));
};
const CellRender = styled.div `
    ${(props) => (props.hideBorder ? `border-left: none;` : `border-left: solid 1px rgba(39, 41, 50, 0.05);`)}

    display: flex;
    padding: 0 16px;
    align-items: ${(props) => props.align || "start"};
    min-height: 82px;

    flex-direction: column;

    position: relative;

    .MuiFormControlLabel-root {
        margin-left: 0;
    }
`;
const StyledTableRow = styled(TableRow) `
    > td {
        border-bottom: 1px solid rgba(39, 41, 50, 0.05)};
        position: relative;

        .error-icon {
            position: absolute;
            right: 10px;
            bottom: 10px;
        }
    }
`;
const WatchValuesRender = styled.div `
    margin: 0;

    max-width: 216px;
    width: 100%;
`;
const ExpressionViewRender = styled.div `
    background: #fcfcfe;
    border: 1px solid rgba(39, 41, 50, 0.1);
    box-sizing: border-box;
    border-radius: 2px;
    width: 100%;
    height: 82px;
    position: relative;
`;
const OtherParameters = styled.div `
    box-sizing: border-box;
    border-radius: 2px;
    min-height: 82px;
    width: 280px;
    position: relative;

    .VariablePicker_Content {
        z-index: 1;
        background: #fff;
    }
`;
export const RuleDataPropertyEditor = ({ rule, form }) => {
    switch (rule.ruleType) {
        case FormRuleType.VALIDATION:
            return (_jsxs(_Fragment, { children: [_jsx(VariablePicker, { selected: Reflect.get(rule.data, 'controlId'), data: form.getFormDatDefinition(), onVariableSet: function (path, def) {
                            Reflect.set(rule.data, 'controlId', path);
                            StateManager.propertyChanged(rule, "data");
                        }, label: "Attach Validation To", allowNewVariable: false, inputProps: {
                            variant: "standard",
                            fullWidth: true
                        } }, void 0),
                    _jsxs(WrapperWithLabel, { children: [_jsx("label", Object.assign({ className: "label" }, { children: "Validation Message" }), void 0),
                            _jsx(InlineTextEdit, { text: Reflect.get(rule.data, "validationMessage"), fullWidth: true, variant: "caption", onEdit: (newText) => {
                                    Reflect.set(rule.data, "validationMessage", newText);
                                    StateManager.propertyChanged(rule, "data");
                                }, placeholder: "Validation Message" }, void 0)] }, void 0)] }, void 0));
        case FormRuleType.CONTROL_ENABLED:
        case FormRuleType.CONTROL_VISIBILITY:
            let selectedControls = Reflect.get(rule.data, "controlId");
            if (typeof selectedControls === "string") {
                if (selectedControls !== "")
                    selectedControls = [selectedControls];
                else {
                    selectedControls = [];
                }
            }
            return (_jsxs(WrapperWithLabel, { children: [_jsx("label", Object.assign({ className: "label" }, { children: "Control Id" }), void 0),
                    _jsx(CheckboxListLayer, { items: form
                            .getAllControls()
                            .map((control) => ({ label: control.toString() || "", value: control.id })), onChange: (mode, newValue) => {
                            Reflect.set(rule, "watchingValuesMode", mode);
                            Reflect.set(rule.data, "controlId", newValue);
                            StateManager.propertyChanged(rule, "data");
                        }, valueMode: rule.watchingValuesMode, placeholder: "Select controls...", label: "Select controls", value: selectedControls, renderValue: (selected) => {
                            return selected
                                .map((controlId) => {
                                var _a;
                                return (_a = form.find(controlId)) === null || _a === void 0 ? void 0 : _a.toString();
                            })
                                .filter((v) => !!v)
                                .join(", ");
                        } }, void 0)] }, void 0));
        case FormRuleType.CHANGE_FOCUS:
            return (_jsxs(FormControl, Object.assign({ fullWidth: true }, { children: [_jsx(InputLabel, Object.assign({ shrink: true }, { children: "Control Id" }), void 0),
                    _jsx(StyledSelect, Object.assign({ value: Reflect.get(rule.data, "controlId"), fullWidth: true, onChange: (event) => {
                            Reflect.set(rule.data, "controlId", event.target.value);
                            StateManager.propertyChanged(rule, "data");
                        } }, { children: form.getAllControls().filter(control => control.canFocus).map((control) => (_jsx(MenuItem, Object.assign({ value: control.id }, { children: control.toString() }), control.id))) }), void 0)] }), void 0));
        case FormRuleType.CHANGE_VALUE:
            return (_jsxs(_Fragment, { children: [_jsx(VariablePicker, { selected: Reflect.get(rule.data, "dataPath"), data: form.getFormDatDefinition(), onVariableSet: (path) => {
                            Reflect.set(rule.data, "dataPath", path);
                            const field = form.getFormDatDefinition().getFieldByDataPath(path);
                            if (field) {
                                const expression = Reflect.get(rule.data, "value");
                                expression.executionResult = field;
                            }
                            StateManager.propertyChanged(rule, "data");
                        }, label: "data path", inputProps: {
                            variant: "standard",
                            size: "small",
                            fullWidth: true,
                        } }, void 0),
                    _jsxs(ExpressionViewWithLabel, { children: [_jsx("label", Object.assign({ className: "label" }, { children: "Value" }), void 0),
                            _jsx(XExpressionView, { expression: Reflect.get(rule.data, "value"), onUpdate: () => {
                                    StateManager.propertyChanged(rule, "data");
                                }, hideValidation: true, color: {
                                    result: "#4050A6",
                                    expression: "#4050A6",
                                    variable: "rgba(39, 41, 50, 0.6)",
                                    value: "rgb(39, 41, 50)",
                                } }, void 0)] }, void 0)] }, void 0));
        case FormRuleType.EXIT_FORM:
            return (_jsxs(FormControl, Object.assign({ fullWidth: true }, { children: [_jsx(InputLabel, Object.assign({ shrink: true }, { children: "Exit on Path" }), void 0),
                    _jsx(StyledSelect, Object.assign({ value: Reflect.get(rule.data, "exitOnPath"), fullWidth: true, onChange: (event) => {
                            Reflect.set(rule.data, "exitOnPath", event.target.value);
                            StateManager.propertyChanged(rule, "data");
                        } }, { children: form.getOutcomes().map((outcome, idx) => {
                            return (_jsx(MenuItem, Object.assign({ value: outcome.name }, { children: outcome.name }), idx));
                        }) }), void 0)] }), void 0));
    }
};
const CheckboxListLayer = ({ items, onChange, value, renderValue, placeholder, label, valueMode }) => {
    const [anchorEl, setAnchorEl] = useState(null);
    const [mode, setMode] = useState(valueMode);
    return (_jsxs(_Fragment, { children: [_jsx(ValuesRender, Object.assign({ onClick: (event) => {
                    setAnchorEl(event.currentTarget);
                }, className: "CheckboxListLayer-values" }, { children: value.length ? (renderValue ? renderValue(value) : value.join(", ")) : placeholder }), void 0),
            _jsx(Menu, Object.assign({ open: !!anchorEl, getContentAnchorEl: null, anchorEl: anchorEl, onClose: () => {
                    setAnchorEl(null);
                } }, { children: _jsxs(ValuesEditRender, { children: [_jsx(CloseButton, Object.assign({ onClick: (event) => {
                                event.stopPropagation();
                                setAnchorEl(null);
                            } }, { children: _jsx(CloseGrayIcon, {}, void 0) }), void 0),
                        label && _jsx(ValuesEditLabel, { children: label }, void 0),
                        _jsx(RadioGroupWithContent, { items: [
                                {
                                    value: "all",
                                },
                                {
                                    value: "value used in rule",
                                },
                                {
                                    value: "pick",
                                    renderUI: () => {
                                        return (_jsx(CheckListRender, { children: items.map((item, idx) => (_jsx(StyledFormControlLabel, { label: item.label, control: _jsx(StyledCheckBox, { checked: value.includes(item.value || item.label), color: "primary", name: item.value || item.label, onChange: (event) => {
                                                        if (event.target.checked) {
                                                            onChange('pick', [...value, item.value || item.label]);
                                                        }
                                                        else {
                                                            onChange('pick', [
                                                                ...value.filter((v) => v !== (item.value || item.label)),
                                                            ]);
                                                        }
                                                    }, "data-testid": item.value || item.label }, void 0) }, idx))) }, void 0));
                                    },
                                },
                            ], value: mode, onChange: (newMode) => {
                                console.log("mode change:", newMode);
                                setMode(newMode);
                                if (newMode === "all") {
                                    console.log("mode change value:", items.map((v) => v.value || v.label));
                                    onChange('all', items.map((v) => v.value || v.label));
                                }
                                else if (newMode === "value used in rule") {
                                    onChange('value used in rule', []);
                                }
                            } }, void 0),
                        _jsx(ActionsGroup, { children: _jsx(StyledButton, Object.assign({ color: "primary", variant: "contained", size: "small", onClick: (event) => {
                                    event.stopPropagation();
                                    setAnchorEl(null);
                                } }, { children: "Done" }), void 0) }, void 0)] }, void 0) }), void 0)] }, void 0));
};
const ValuesRender = styled.div `
    font-family: Source Code Pro;
    font-size: 12px;
    font-style: normal;
    font-weight: 400;
    line-height: 17px;
    letter-spacing: 0em;
    text-align: left;
    color: rgba(39, 41, 50, 0.6);
`;
const CheckListRender = styled.div `
    display: flex;
    flex-direction: column;
    padding-left: 15px;

    width: 200px;
    max-height: 150px;
    overflow: auto;
`;
const ValuesEditRender = styled.div `
    padding: 5px 15px;
`;
const ActionsGroup = styled.div `
    display: flex;
    justify-content: flex-end;

    margin-top: 10px;
`;
const CloseButton = styled.div `
    right: 0;
    top: 0;
    position: absolute;

    width: 24px;
    height: 24px;

    opacity: 0.5;

    transition: all 0.1s ease-in;

    &:hover {
        opacity: 1;
    }
`;
const ValuesEditLabel = styled.div `
    font-size: 14px;
    font-family: Inter;
    font-weight: 600;
    color: #272932;
    margin-bottom: 10px;
`;
const WrapperWithLabel = styled.div `
    display: flex;
    flex-direction: column;

    label.label {
        // color: #272932;
        background: #fff;

        color: rgba(0, 0, 0, 0.54);
        padding: 0;
        font-size: 10px;
        font-family: "Roboto", "Helvetica", "Arial", sans-serif;
        font-weight: 400;
        line-height: 1;
        letter-spacing: 0.00938em;
    }
`;
const ExpressionViewWithLabel = styled.div `
    background: #fcfcfe;
    border: 1px solid rgba(39, 41, 50, 0.1);
    box-sizing: border-box;
    border-radius: 2px;
    width: 100%;

    margin-top: 25px;

    label {
        position: absolute;
        transform: translateY(-15px);

        color: rgba(0, 0, 0, 0.54);
        padding: 0;
        font-size: 10px;
        font-family: "Roboto", "Helvetica", "Arial", sans-serif;
        font-weight: 400;
        line-height: 1;
        letter-spacing: 0.00938em;
    }
`;
//# sourceMappingURL=XFormRuleRow.js.map