import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import React, { useState, useEffect } from "react";
import FormHelperText from "@material-ui/core/FormHelperText";
import List from "@material-ui/core/List";
import ListItem from "@material-ui/core/ListItem";
import ListSubheader from "@material-ui/core/ListSubheader";
import TextField from "@material-ui/core/TextField";
import { ListItemText, InputAdornment, FormControlLabel, Checkbox, Link, Menu } from "@material-ui/core";
import styled from "styled-components";
import { DataUtilities } from "../Common/DataUtilities";
import { XDataType } from "../Common/Data/XDataType";
import { DropdownIcon } from "./Icon/DropdownIcon";
import { ObjectDataDefinition } from "../Common/Data/Definitions/ObjectDataDefinition";
import { SearchGrayIcon } from "./Icon/SearchGrayIcon";
import { StyledButton } from "./BuildUI/Button";
const VariablePicker = (props) => {
    var _a, _b, _c, _d;
    const [showContent, setShowContent] = useState(false);
    const [selected, setSelected] = useState(props.selected);
    const [searchStr, setSearchStr] = useState("");
    const [mode, setMode] = useState(props.data.fields.length === 0 && props.allowNewVariable ? "new" : "pick");
    const [value, setValue] = useState(null);
    let selectedField;
    const ref = React.useRef(null);
    let show = showContent;
    try {
        selectedField = DataUtilities.getFieldFromDataDefinitionByProperty(props.data.fields, selected, "name");
    }
    catch (e) { }
    const [newVariable, setNewVariable] = useState(() => {
        let state = {
            name: "",
            type: XDataType.STRING,
            path: "",
            islist: props.isList || false,
        };
        if (!selectedField) {
            if (props.selected) {
                state.name = props.selected;
            }
            if (props.requiredType && !(props.requiredType instanceof ObjectDataDefinition)) {
                state.type = props.requiredType;
            }
        }
        return state;
    });
    let error;
    if (selectedField && props.requiredType) {
        if (props.requiredType instanceof ObjectDataDefinition &&
            !DataUtilities.compareStructureToPath(props.requiredType, props.data, selected || "")) {
            error = "Selected field does not match with required type.";
        }
        else if (!(props.requiredType instanceof ObjectDataDefinition) &&
            (selectedField.type !== props.requiredType ||
                ((props.isList || selectedField.list) && props.isList !== selectedField.list))) {
            error = "Selected field does not match with required type.";
        }
    }
    else if (selected && !selectedField) {
        error = "Selected field does not exists in fields.";
    }
    const filteredFields = DataUtilities.filterFieldsByProperty(props.data.fields, "name", value || searchStr);
    useEffect(() => {
        setSelected(props.selected);
    }, [props.selected, setSelected]);
    const onChange = (event) => {
        setValue(event.target.value);
        setNewVariable(Object.assign(Object.assign({}, newVariable), { name: event.target.value }));
    };
    const onSelect = (path) => {
        setSelected(path);
        setValue(null);
    };
    const onChangeNewVariableName = (event) => {
        setNewVariable(Object.assign(Object.assign({}, newVariable), { name: event.target.value }));
    };
    const onChangeNewValueIsList = (event) => {
        setNewVariable(Object.assign(Object.assign({}, newVariable), { islist: event.target.checked }));
    };
    const onChangeNewVariableType = (event) => {
        setNewVariable(Object.assign(Object.assign({}, newVariable), { type: event.target.value }));
    };
    const onAddNew = () => {
        if (newVariable && newVariable.name.trim() !== "" && props.allowNewVariable) {
            let def = null;
            if (typeof props.requiredType === "object") {
                const type = Reflect.get(props.requiredType, "type");
                def = DataUtilities.createDataByType(type);
                DataUtilities.spreadDeepData(def, props.requiredType);
            }
            else if (props.requiredType) {
                def = DataUtilities.createDataByType(props.requiredType);
            }
            else {
                def = DataUtilities.createDataByType(newVariable.type);
            }
            def.name = newVariable.name;
            def.list = newVariable.islist;
            setValue(null);
            setNewVariable({
                name: "",
                type: XDataType.STRING,
                path: "",
                islist: false,
            });
            setMode("pick");
            setShowContent(false);
            props.onVariableSet(newVariable.path, def);
        }
    };
    const renderListFields = (fields, keys = [], subheader) => {
        return (_jsx(_Fragment, { children: _jsx(List, Object.assign({ subheader: subheader ? subheader() : undefined }, { children: fields.map((f) => {
                    const path = [...keys, f.name || ""].join(".");
                    if (f.type === XDataType.OBJECT) {
                        const subfields = Reflect.get(f, "fields");
                        return (_jsxs(React.Fragment, { children: [_jsx(ListItem, Object.assign({ selected: selected === path, button: true, onClick: () => onSelect(path), "data-testid": `${path}${selected === path ? "-selected" : ""}` }, { children: _jsx(ListItemText, { primary: f.name, classes: {
                                            primary: "MuiListItemText-object",
                                        } }, void 0) }), void 0),
                                _jsx(NestedListWrapper, { children: subfields.length ? renderListFields(subfields, [...keys, f.name || ""]) : null }, void 0)] }, path));
                    }
                    else {
                        return (_jsxs(ListItem, Object.assign({ selected: selectedField === f, button: true, color: "primary", onClick: () => onSelect(path), "data-testid": `${path}${selectedField === f ? "-selected" : ""}` }, { children: [_jsx(ListItemText, { primary: f.name }, void 0),
                                _jsx(ListItemText, { secondary: f.type }, void 0)] }), `${path}`));
                    }
                }) }), void 0) }, void 0));
    };
    const renderExistingFields = () => {
        return (_jsxs(ExistingWrapper, { children: [renderListFields(filteredFields, [], () => (_jsx(ListSubheader, { children: _jsx(TextField, { value: searchStr, onChange: (event) => setSearchStr(event.target.value || ""), placeholder: "Search", "data-testid": "variable-picker-search", fullWidth: true, classes: {
                            root: "Search_TextField",
                        }, InputProps: {
                            endAdornment: _jsx(SearchGrayIcon, {}, void 0),
                        } }, void 0) }, void 0))),
                filteredFields.length === 0 && (_jsx(FormHelperText, Object.assign({ classes: { root: "VariablePicker-nofieldMessage" } }, { children: "There is no fields." }), void 0)),
                props.allowNewVariable && (_jsx(ButtonGroupDiv, Object.assign({ marginTop: 16 }, { children: _jsx(Link, Object.assign({ classes: {
                            root: "BtnVariablePicker-to-create",
                        }, "data-testid": "VariablePicker_NewMode", onClick: (event) => {
                            event.stopPropagation();
                            setMode("new");
                        } }, { children: "Add new" }), void 0) }), void 0)),
                _jsxs(ButtonGroupDiv, Object.assign({ marginTop: 16 }, { children: [_jsx(Link, Object.assign({ onClick: (event) => {
                                event.stopPropagation();
                                props.onVariableSet(props.selected || "");
                                setSelected(props.selected);
                                setShowContent(false);
                            } }, { children: "Cancel" }), void 0),
                        _jsx(StyledButton, Object.assign({ "data-testid": "VariablePicker_Select", variant: "contained", color: "primary", disabled: props.selected === selected, onClick: (event) => {
                                event.stopPropagation();
                                props.onVariableSet(selected || "");
                                setShowContent(false);
                            } }, { children: "Choose" }), void 0)] }), void 0)] }, void 0));
    };
    const renderNewField = () => (_jsxs(NewFieldDiv, { children: [_jsxs(FormControl, { children: [_jsx(StyledInputLabel, { children: "Data Name" }, void 0),
                    _jsx(TextField, { variant: "outlined", value: newVariable.name, onChange: onChangeNewVariableName, error: newVariable.name === "", helperText: newVariable.name === "" ? "name is required" : "", "data-testid": "variable-picker-add", onKeyUp: (event) => {
                            if (event.key === "Enter") {
                                onAddNew();
                            }
                        } }, void 0)] }, void 0),
            _jsxs(FormControl, { children: [_jsx(StyledInputLabel, { children: "Type" }, void 0),
                    _jsxs(TextField, Object.assign({ select: true, variant: "outlined", SelectProps: { native: true, disabled: !!props.requiredType }, value: newVariable.type, onChange: onChangeNewVariableType, "data-testid": "variable-picker-change-type" }, { children: [_jsx("option", { children: XDataType.STRING }, void 0),
                            _jsx("option", { children: XDataType.NUMBER }, void 0),
                            _jsx("option", { children: XDataType.BOOLEAN }, void 0),
                            _jsx("option", { children: XDataType.DATE }, void 0),
                            _jsx("option", { children: XDataType.FILE }, void 0),
                            _jsx("option", { children: XDataType.OBJECT }, void 0),
                            _jsx("option", { children: XDataType.UNDEFINED }, void 0)] }), void 0)] }, void 0),
            _jsx(FormControl, { children: _jsx(FormControlLabel, { "data-testid": "variable-picker-is-list", control: _jsx(Checkbox, { checked: newVariable.islist, onChange: onChangeNewValueIsList, name: "islist", color: "primary" }, void 0), label: "is list" }, void 0) }, void 0),
            _jsxs(ButtonGroupDiv, Object.assign({ marginTop: 16, className: "VariablePicker-buttonGroups" }, { children: [_jsx(Link, Object.assign({ onClick: (event) => {
                            event.stopPropagation();
                            if (props.data.fields.length > 0) {
                                setMode("pick");
                            }
                            else {
                                setShowContent(false);
                                props.onVariableSet("");
                            }
                        } }, { children: "Cancel" }), void 0),
                    _jsx(StyledButton, Object.assign({ variant: "contained", color: "primary", onClick: (event) => {
                            event.stopPropagation();
                            onAddNew();
                        }, "data-testid": "BtnCreateVariable" }, { children: "Create" }), void 0)] }), void 0)] }, void 0));
    return (_jsxs(VariablePickerDiv, Object.assign({ className: "VariablePicker_root", fullWidth: (_a = props.inputProps) === null || _a === void 0 ? void 0 : _a.fullWidth, inputSize: ((_b = props.inputProps) === null || _b === void 0 ? void 0 : _b.size) || "medium", ref: ref }, { children: [!props.hideInput && (_jsx(TextField, { classes: {
                    root: "VariablePicker_TextField",
                }, value: value || (selectedField === null || selectedField === void 0 ? void 0 : selectedField.name) || props.selected, onChange: onChange, onFocus: () => setShowContent(true), variant: ((_c = props.inputProps) === null || _c === void 0 ? void 0 : _c.variant) || "outlined", error: !!error, helperText: error, "data-testid": `variable-picker-value${props.requiredType && error ? "-error" : ""}`, InputProps: {
                    endAdornment: (_jsx(InputAdornment, Object.assign({ position: "end" }, { children: _jsx(DropdownIcon, {}, void 0) }), void 0)),
                    readOnly: !props.allowNewVariable && props.data.fields.length === 0,
                }, label: props.label, InputLabelProps: { shrink: true }, fullWidth: (_d = props.inputProps) === null || _d === void 0 ? void 0 : _d.fullWidth, autoFocus: !!props.startOpenIfEmptyOrInvalid && !selectedField }, void 0)),
            props.notPopup ? (_jsxs(VariablePickerContentDiv, Object.assign({ className: "VariablePicker_Content" }, { children: [props.renderTitle && props.renderTitle(), mode === "new" ? renderNewField() : renderExistingFields()] }), void 0)) : (_jsx(Menu, Object.assign({ open: show, anchorEl: props.anchorEl || ref.current, anchorOrigin: {
                    vertical: "bottom",
                    horizontal: "left",
                }, disableEnforceFocus: true, disableRestoreFocus: true, onClose: () => {
                    if (props.selected !== selected && selected) {
                        props.onVariableSet(selected);
                    }
                    setShowContent(false);
                }, getContentAnchorEl: null }, { children: _jsxs(VariablePickerContentDiv, Object.assign({ className: "VariablePicker_Content" }, { children: [props.renderTitle && props.renderTitle(), mode === "new" ? renderNewField() : renderExistingFields()] }), void 0) }), void 0))] }), void 0));
};
export default VariablePicker;
const VariablePickerDiv = styled.div `
    position: relative;
    display: inline-block;
    width: ${(props) => (props.fullWidth ? "100%" : "auto")};

    .MuiInputBase-root {
        font-family: Inter;
        font-size: 12px;
        font-style: normal;
        font-weight: 500;
        line-height: 20px;
        letter-spacing: 0em;
        text-align: left;
    }

    .MuiOutlinedInput-input {
        padding: 6px 12px;
        font-size: 14px;
        font-style: normal;
        font-weight: 400;
        height: auto;
        background: #fcfcfe;
    }

    .VariablePicker_TextField .MuiOutlinedInput-input {
        ${(props) => (props.inputSize === "large" ? "padding: 10px 12px;" : "")}
        ${(props) => (props.inputSize === "medium" ? "padding: 8px 12px;" : "")}
        ${(props) => (props.inputSize === "small" ? "padding: 6px 12px;" : "")}
    }

    .MuiOutlinedInput-notchedOutline {
        border: 1px solid rgba(39, 41, 50, 0.2);
        border-radius: 4px;
    }

    .MuiList-root {
        &.MuiList-padding {
            padding-top: 0;
            padding-bottom: 0;
        }

        .MuiListItem-root {
            padding: 5px 12px;
            display: flex;
            justify-content: space-between;
        }

        .MuiListSubheader-gutters {
            padding: 0 12px;
        }

        .MuiListItemText-root {
            flex: inherit;
            margin: 0;
            .MuiTypography-body1 {
                font-family: Inter;
                font-size: 12px;
                font-style: normal;
                font-weight: 400;
                line-height: 17px;
                letter-spacing: 0px;
                text-align: left;
            }

            .MuiListItemText-primary {
                color: #272932;
            }

            .MuiListItemText-object {
                color: rgba(39, 41, 50, 0.4);
            }

            .MuiListItemText-secondary {
                color: rgba(64, 80, 166, 0.5);
                text-transform: capitalize;
            }
        }
    }
`;
const VariablePickerContentDiv = styled.div `
    padding: 5px 10px;

    width: 300px;
    min-height: 150px;

    max-width: 100%;

    background: white;

    .MuiInputBase-root {
        font-family: Inter;
        font-size: 12px;
        font-style: normal;
        font-weight: 500;
        line-height: 20px;
        letter-spacing: 0em;
        text-align: left;
    }

    .MuiOutlinedInput-input {
        padding: 6px 12px;
        font-size: 14px;
        font-style: normal;
        font-weight: 400;
        height: auto;
        background: #fcfcfe;
    }
    .MuiOutlinedInput-notchedOutline {
        border: 1px solid rgba(39, 41, 50, 0.2);
        border-radius: 4px;
    }

    .MuiList-root {
        &.MuiList-padding {
            padding-top: 0;
            padding-bottom: 0;
        }

        .MuiListItem-root {
            padding: 5px 12px;
            display: flex;
            justify-content: space-between;
        }

        .MuiListSubheader-gutters {
            padding: 0 12px;
        }

        .MuiListItemText-root {
            flex: inherit;
            margin: 0;
            .MuiTypography-body1 {
                font-family: Inter;
                font-size: 12px;
                font-style: normal;
                font-weight: 400;
                line-height: 17px;
                letter-spacing: 0px;
                text-align: left;
            }

            .MuiListItemText-primary {
                color: #272932;
            }

            .MuiListItemText-object {
                color: rgba(39, 41, 50, 0.4);
            }

            .MuiListItemText-secondary {
                color: rgba(64, 80, 166, 0.5);
                text-transform: capitalize;
            }
        }
    }
`;
const NestedListWrapper = styled.div `
    padding-left: 10px;
`;
const NewFieldDiv = styled.div `
    display: flex;
    flex-direction: column;
`;
const StyledInputLabel = styled.label `
    display: flex;
    font-family: Inter;
    font-size: 12px;
    font-style: normal;
    font-weight: 400;
    line-height: 17px;
    letter-spacing: 0px;
    text-align: left;
    color: #272932;

    margin-bottom: 4px;
`;
const FormControl = styled.div `
    display: flex;
    flex-direction: column;
    margin-bottom: 11px;
`;
const ExistingWrapper = styled.div `
    .Search_TextField {
        padding: 7px 0 3px;
        .MuiOutlinedInput-input {
            padding: 5px 10px;
        }
        .MuiInputBase-input {
            font-family: Inter;
            font-size: 14px;
            font-style: normal;
            font-weight: 400;
            line-height: 20px;
            letter-spacing: 0em;
            text-align: left;
        }
    }

    .VariablePicker-nofieldMessage {
        padding: 0 12px;
    }
`;
const ButtonGroupDiv = styled.div `
    display: flex;
    align-items: center;

    ${(props) => (props.marginTop ? `margin-top: ${props.marginTop}px;` : "")}

    > * {
        width: 50%;
    }

    .BtnVariablePicker-to-create {
        margin-left: auto;
    }

    .MuiLink-root {
        text-align: center;
    }
`;
//# sourceMappingURL=VariablePicker.js.map