import React, { useState, useEffect, useMemo, useCallback } from 'react';
import { UdpDrawer } from '../../UI/fluent-web-components/UdpDrawer';
import { UdpCard } from '../../UI/fluent-web-components/UdpCard';
import { UdpFlexbox } from '../../UI/fluent-web-components/UdpFlexbox';
import { UdpTextInput } from '../../UI/fluent-web-components/UdpTextInput';
import { UdpDropdown } from '../../UI/fluent-web-components/UdpDropdown';
import { UdpButton } from '../../UI/fluent-web-components/UdpButton';
import { UdpIconButton } from '../../UI/fluent-web-components/UdpIconButton';
import { UdpText } from '../../UI/fluent-web-components/UdpText';
import { UdpBadge } from '../../UI/fluent-web-components/UdpBadge';
import { UdpMessageBar } from '../../UI/fluent-web-components/UdpMessageBar';
import { isCatalogModelObject, LookupTypeId, LookupColumnTypeId } from 'udp-stencil-component-library';
const LOOKUP_TYPE_OPTIONS = [
    { label: 'Domain', value: LookupTypeId.Domain },
    { label: 'Virtual', value: LookupTypeId.Lookup }
];
export const COLUMN_TYPE_OPTIONS = [
    { label: 'String', value: LookupColumnTypeId.String },
    { label: 'Long', value: LookupColumnTypeId.Long },
    { label: 'Boolean', value: LookupColumnTypeId.Boolean },
    { label: 'DateTime', value: LookupColumnTypeId.DateTime },
    { label: 'Double', value: LookupColumnTypeId.Double }
];
const BOOLEAN_OPTIONS = [
    { label: 'true', value: 'true' },
    { label: 'false', value: 'false' }
];
const getSimpleName = (name) => {
    if (!name)
        return '';
    const parts = name.split('.');
    return parts[parts.length - 1];
};
/**
 * LookupCreationSheet — create or edit a lookup.
 *
 * Pass `lookup` to enter edit mode. When omitted, the sheet is in create mode.
 */
export const LookupCreationSheet = ({ open, onClose, 
// Optional: when provided the sheet is in edit mode
lookup = null, 
// CRUD callbacks
onCreateLookup, onCreateLookupColumn, onCreateLookupValue, onUpdateLookup, onUpdateLookupColumn, onDeleteLookupValue, onLookupCreated, 
// Shared
fetchColumns, fetchValues, catalogObjectList = [], lookupMethodStatus = {} }) => {
    var _a, _b, _c;
    const isEditMode = !!lookup;
    const [name, setName] = useState('');
    const [description, setDescription] = useState('');
    const [typeOption, setTypeOption] = useState(LOOKUP_TYPE_OPTIONS[0]);
    const [saving, setSaving] = useState(false);
    // ── Domain lookup state ────────────────────────────────────
    const [selectedEntity, setSelectedEntity] = useState(null);
    const [keyNameOption, setKeyNameOption] = useState(null);
    const [valueNameOption, setValueNameOption] = useState(null);
    // Edit-mode domain text fields (entity is read-only in edit)
    const [keyName, setKeyName] = useState('');
    const [valueName, setValueName] = useState('');
    // ── Virtual lookup state ───────────────────────────────────
    const [virtualColumns, setVirtualColumns] = useState([
        { name: 'Key', typeOption: COLUMN_TYPE_OPTIONS[0] },
        { name: 'Value', typeOption: COLUMN_TYPE_OPTIONS[0] }
    ]);
    const [virtualRows, setVirtualRows] = useState([['', '']]);
    // Edit-mode virtual state (rows track existing IDs)
    const [editColumns, setEditColumns] = useState([]);
    const [editRows, setEditRows] = useState([]);
    const [loadingData, setLoadingData] = useState(false);
    const { lookupCreateAvailable, lookupUpdateAvailable, columnCreateAvailable, valueCreateAvailable } = lookupMethodStatus;
    const virtualAvailable = columnCreateAvailable && valueCreateAvailable;
    const typeOptions = useMemo(() => LOOKUP_TYPE_OPTIONS.map((o) => (Object.assign(Object.assign({}, o), { disabled: o.value === 4 && !virtualAvailable }))), [virtualAvailable]);
    const isDomain = isEditMode ? (lookup === null || lookup === void 0 ? void 0 : lookup.typeId) === LookupTypeId.Domain : (typeOption === null || typeOption === void 0 ? void 0 : typeOption.value) === LookupTypeId.Domain;
    const isVirtual = isEditMode ? (lookup === null || lookup === void 0 ? void 0 : lookup.typeId) === LookupTypeId.Lookup : (typeOption === null || typeOption === void 0 ? void 0 : typeOption.value) === LookupTypeId.Lookup;
    // ── Load data when editing ─────────────────────────────────
    useEffect(() => {
        var _a, _b, _c, _d, _e;
        if (!open || !isEditMode)
            return;
        setName((_a = lookup.name) !== null && _a !== void 0 ? _a : '');
        setDescription((_b = lookup.description) !== null && _b !== void 0 ? _b : '');
        setTypeOption((_c = LOOKUP_TYPE_OPTIONS.find((o) => o.value === lookup.typeId)) !== null && _c !== void 0 ? _c : LOOKUP_TYPE_OPTIONS[0]);
        setKeyName((_d = lookup.keyName) !== null && _d !== void 0 ? _d : '');
        setValueName((_e = lookup.valueName) !== null && _e !== void 0 ? _e : '');
        if (lookup.typeId === LookupTypeId.Lookup && fetchColumns && fetchValues) {
            loadVirtualData(lookup.id);
        }
    }, [open, lookup === null || lookup === void 0 ? void 0 : lookup.id, lookup === null || lookup === void 0 ? void 0 : lookup.typeId]); // eslint-disable-line react-hooks/exhaustive-deps
    const loadVirtualData = async (lookupId) => {
        setLoadingData(true);
        try {
            const [allColumns, allValues] = await Promise.all([
                fetchColumns(),
                fetchValues()
            ]);
            const lookupColumns = allColumns
                .filter((c) => c.lookupId === lookupId)
                .sort((a, b) => a.order - b.order);
            const lookupValues = allValues.filter((v) => lookupColumns.some((c) => c.id === v.lookupColumnId));
            const colState = lookupColumns.map((c) => {
                var _a;
                return (Object.assign(Object.assign({}, c), { typeOption: (_a = COLUMN_TYPE_OPTIONS.find((o) => o.value === c.lookupColumnTypeId)) !== null && _a !== void 0 ? _a : COLUMN_TYPE_OPTIONS[0] }));
            });
            setEditColumns(colState);
            const maxRow = lookupValues.reduce((max, v) => Math.max(max, v.rowNumber), 0);
            const rowState = [];
            for (let r = 1; r <= maxRow; r++) {
                const row = colState.map((col) => {
                    var _a, _b;
                    const val = lookupValues.find((v) => v.lookupColumnId === col.id && v.rowNumber === r);
                    return { value: (_a = val === null || val === void 0 ? void 0 : val.value) !== null && _a !== void 0 ? _a : '', id: (_b = val === null || val === void 0 ? void 0 : val.id) !== null && _b !== void 0 ? _b : null };
                });
                rowState.push(row);
            }
            if (rowState.length === 0) {
                rowState.push(colState.map(() => ({ value: '', id: null })));
            }
            setEditRows(rowState);
        }
        finally {
            setLoadingData(false);
        }
    };
    // ── Domain helpers ─────────────────────────────────────────
    const entityOptions = useMemo(() => catalogObjectList
        .filter((obj) => isCatalogModelObject(obj))
        .map((obj) => {
        var _a;
        return ({
            label: getSimpleName(obj.catalogObjectName),
            value: obj.catalogObjectName,
            properties: (_a = obj.properties) !== null && _a !== void 0 ? _a : []
        });
    }), [catalogObjectList]);
    const fieldOptions = useMemo(() => {
        if (!(selectedEntity === null || selectedEntity === void 0 ? void 0 : selectedEntity.properties))
            return [];
        return selectedEntity.properties.map((p) => ({
            label: p.name,
            value: p.name
        }));
    }, [selectedEntity]);
    // Edit-mode: derive field options from the lookup's domainName
    const editDomainFieldOptions = useMemo(() => {
        if (!isEditMode || !isDomain || !(lookup === null || lookup === void 0 ? void 0 : lookup.domainName))
            return [];
        const entity = catalogObjectList.find((obj) => obj.catalogObjectName === lookup.domainName);
        if (!(entity === null || entity === void 0 ? void 0 : entity.properties))
            return [];
        return entity.properties.map((p) => ({
            label: p.name,
            value: p.name
        }));
    }, [isEditMode, isDomain, lookup === null || lookup === void 0 ? void 0 : lookup.domainName, catalogObjectList]);
    // ── Create-mode virtual column/row helpers ─────────────────
    const updateColumn = useCallback((index, field, value) => {
        setVirtualColumns((prev) => {
            const updated = [...prev];
            updated[index] = Object.assign(Object.assign({}, updated[index]), { [field]: value });
            return updated;
        });
    }, []);
    const addColumn = useCallback(() => {
        setVirtualColumns((prev) => [
            ...prev,
            { name: '', typeOption: COLUMN_TYPE_OPTIONS[0] }
        ]);
        setVirtualRows((prev) => prev.map((row) => [...row, '']));
    }, []);
    const removeColumn = useCallback((index) => {
        if (virtualColumns.length <= 2)
            return;
        setVirtualColumns((prev) => prev.filter((_, i) => i !== index));
        setVirtualRows((prev) => prev.map((row) => row.filter((_, i) => i !== index)));
    }, [virtualColumns.length]);
    const updateRowValue = useCallback((rowIndex, colIndex, value) => {
        setVirtualRows((prev) => {
            const updated = [...prev];
            updated[rowIndex] = [...updated[rowIndex]];
            updated[rowIndex][colIndex] = value;
            return updated;
        });
    }, []);
    const addRow = useCallback(() => {
        setVirtualRows((prev) => [...prev, virtualColumns.map(() => '')]);
    }, [virtualColumns]);
    const removeRow = useCallback((index) => {
        if (virtualRows.length <= 1)
            return;
        setVirtualRows((prev) => prev.filter((_, i) => i !== index));
    }, [virtualRows.length]);
    // ── Edit-mode virtual column/row helpers ───────────────────
    const updateEditColumnField = (index, field, value) => {
        setEditColumns((prev) => {
            const updated = [...prev];
            updated[index] = Object.assign(Object.assign({}, updated[index]), { [field]: value });
            return updated;
        });
    };
    const addEditColumn = () => {
        setEditColumns((prev) => [
            ...prev,
            { name: '', typeOption: COLUMN_TYPE_OPTIONS[0], id: null, _new: true }
        ]);
        setEditRows((prev) => prev.map((row) => [...row, { value: '', id: null }]));
    };
    const removeEditColumn = (index) => {
        if (editColumns.length <= 2)
            return;
        setEditColumns((prev) => prev.filter((_, i) => i !== index));
        setEditRows((prev) => prev.map((row) => row.filter((_, i) => i !== index)));
    };
    const updateEditRowValue = (rowIdx, colIdx, value) => {
        setEditRows((prev) => {
            const updated = [...prev];
            updated[rowIdx] = [...updated[rowIdx]];
            updated[rowIdx][colIdx] = Object.assign(Object.assign({}, updated[rowIdx][colIdx]), { value });
            return updated;
        });
    };
    const addEditRow = () => {
        setEditRows((prev) => [
            ...prev,
            editColumns.map(() => ({ value: '', id: null }))
        ]);
    };
    const removeEditRow = (index) => {
        if (editRows.length <= 1)
            return;
        setEditRows((prev) => prev.filter((_, i) => i !== index));
    };
    // ── Reset / Close ──────────────────────────────────────────
    const resetForm = () => {
        setName('');
        setDescription('');
        setTypeOption(LOOKUP_TYPE_OPTIONS[0]);
        setSelectedEntity(null);
        setKeyNameOption(null);
        setValueNameOption(null);
        setKeyName('');
        setValueName('');
        setVirtualColumns([
            { name: 'Key', typeOption: COLUMN_TYPE_OPTIONS[0] },
            { name: 'Value', typeOption: COLUMN_TYPE_OPTIONS[0] }
        ]);
        setVirtualRows([['', '']]);
        setEditColumns([]);
        setEditRows([]);
    };
    const handleClose = () => {
        resetForm();
        onClose();
    };
    const handleEntityChange = (e) => {
        const selected = e.target.value;
        const entity = selected
            ? entityOptions.find((o) => o.value === selected.value)
            : null;
        setSelectedEntity(entity);
        setKeyNameOption(null);
        setValueNameOption(null);
    };
    // ── Save (create) ─────────────────────────────────────────
    const handleCreate = async () => {
        var _a, _b, _c;
        var _d, _e, _f, _g, _h;
        if (!name.trim())
            return;
        setSaving(true);
        try {
            if (isDomain) {
                const created = await onCreateLookup({
                    name: name.trim(),
                    description: description.trim() || undefined,
                    typeId: LookupTypeId.Domain,
                    keyName: (_d = keyNameOption === null || keyNameOption === void 0 ? void 0 : keyNameOption.value) !== null && _d !== void 0 ? _d : '',
                    valueName: (_e = valueNameOption === null || valueNameOption === void 0 ? void 0 : valueNameOption.value) !== null && _e !== void 0 ? _e : '',
                    domainName: (_f = selectedEntity === null || selectedEntity === void 0 ? void 0 : selectedEntity.value) !== null && _f !== void 0 ? _f : '',
                    isProductLookup: false
                });
                if (created) {
                    onLookupCreated === null || onLookupCreated === void 0 ? void 0 : onLookupCreated(created);
                    handleClose();
                }
            }
            else {
                const created = await onCreateLookup({
                    name: name.trim(),
                    description: description.trim() || undefined,
                    typeId: LookupTypeId.Lookup,
                    keyName: ((_a = virtualColumns[0]) === null || _a === void 0 ? void 0 : _a.name) || 'key',
                    valueName: ((_b = virtualColumns[1]) === null || _b === void 0 ? void 0 : _b.name) || 'value',
                    isProductLookup: false
                });
                if (!(created === null || created === void 0 ? void 0 : created.id))
                    return;
                const columnIds = [];
                for (let i = 0; i < virtualColumns.length; i++) {
                    const col = virtualColumns[i];
                    const colResult = await onCreateLookupColumn({
                        lookupId: created.id,
                        name: col.name || `Column ${i + 1}`,
                        order: i + 1,
                        lookupColumnTypeId: (_g = (_c = col.typeOption) === null || _c === void 0 ? void 0 : _c.value) !== null && _g !== void 0 ? _g : 1
                    });
                    columnIds.push((_h = colResult === null || colResult === void 0 ? void 0 : colResult.id) !== null && _h !== void 0 ? _h : null);
                }
                for (let rowIdx = 0; rowIdx < virtualRows.length; rowIdx++) {
                    const row = virtualRows[rowIdx];
                    for (let colIdx = 0; colIdx < row.length; colIdx++) {
                        const columnId = columnIds[colIdx];
                        if (!columnId || !row[colIdx])
                            continue;
                        await onCreateLookupValue({
                            lookupColumnId: columnId,
                            value: row[colIdx],
                            rowNumber: rowIdx + 1
                        });
                    }
                }
                onLookupCreated === null || onLookupCreated === void 0 ? void 0 : onLookupCreated(created);
                handleClose();
            }
        }
        finally {
            setSaving(false);
        }
    };
    // ── Save (edit) ────────────────────────────────────────────
    const handleUpdate = async () => {
        var _a, _b, _c, _d, _e;
        var _f, _g;
        if (!name.trim())
            return;
        setSaving(true);
        try {
            await onUpdateLookup(Object.assign(Object.assign({}, lookup), { name: name.trim(), description: description.trim() || null, keyName: isVirtual ? ((_a = editColumns[0]) === null || _a === void 0 ? void 0 : _a.name) || keyName : keyName, valueName: isVirtual ? ((_b = editColumns[1]) === null || _b === void 0 ? void 0 : _b.name) || valueName : valueName }));
            if (isVirtual) {
                for (let i = 0; i < editColumns.length; i++) {
                    const col = editColumns[i];
                    if (col._new || !col.id) {
                        const created = await onCreateLookupColumn({
                            lookupId: lookup.id,
                            name: col.name || `Column ${i + 1}`,
                            order: i + 1,
                            lookupColumnTypeId: (_f = (_c = col.typeOption) === null || _c === void 0 ? void 0 : _c.value) !== null && _f !== void 0 ? _f : 1
                        });
                        if (created === null || created === void 0 ? void 0 : created.id) {
                            editColumns[i] = Object.assign(Object.assign({}, col), { id: created.id, _new: false });
                        }
                    }
                    else {
                        await onUpdateLookupColumn(Object.assign(Object.assign({}, col), { name: col.name || `Column ${i + 1}`, order: i + 1, lookupColumnTypeId: (_g = (_d = col.typeOption) === null || _d === void 0 ? void 0 : _d.value) !== null && _g !== void 0 ? _g : 1 }));
                    }
                }
                const createValueFn = onCreateLookupValue;
                for (let rowIdx = 0; rowIdx < editRows.length; rowIdx++) {
                    const row = editRows[rowIdx];
                    for (let colIdx = 0; colIdx < row.length; colIdx++) {
                        const cell = row[colIdx];
                        const columnId = (_e = editColumns[colIdx]) === null || _e === void 0 ? void 0 : _e.id;
                        if (!columnId)
                            continue;
                        if (cell.id && !cell.value.trim()) {
                            await (onDeleteLookupValue === null || onDeleteLookupValue === void 0 ? void 0 : onDeleteLookupValue({ id: cell.id }));
                        }
                        else if (cell.id) {
                            // update existing value — reuse the create fn pattern isn't right,
                            // but we don't have an updateValue prop. For now, skip unchanged.
                            // The caller can pass onUpdateLookupValue if needed.
                        }
                        else if (cell.value.trim()) {
                            await (createValueFn === null || createValueFn === void 0 ? void 0 : createValueFn({
                                lookupColumnId: columnId,
                                value: cell.value,
                                rowNumber: rowIdx + 1
                            }));
                        }
                    }
                }
            }
            onLookupCreated === null || onLookupCreated === void 0 ? void 0 : onLookupCreated(lookup);
            handleClose();
        }
        finally {
            setSaving(false);
        }
    };
    const handleSave = isEditMode ? handleUpdate : handleCreate;
    // ── Validation ─────────────────────────────────────────────
    const canSave = name.trim().length > 0 &&
        (isEditMode
            ? true
            : isDomain
                ? !!selectedEntity
                : virtualColumns.every((c) => c.name.trim()) &&
                    virtualRows.some((r) => r.some((v) => v.trim())));
    const saveDisabled = isEditMode
        ? !canSave || !lookupUpdateAvailable
        : !canSave || !lookupCreateAvailable;
    // ── Active column/row state (create vs edit) ───────────────
    const activeCols = isEditMode ? editColumns : virtualColumns;
    const activeRows = isEditMode ? editRows : virtualRows;
    return (React.createElement(UdpDrawer, { open: open, drawerTitle: isEditMode ? `Edit Lookup: ${lookup === null || lookup === void 0 ? void 0 : lookup.name}` : 'Create Lookup', size: "medium", onDrawerClose: handleClose, excludeVerticalPadding: true }, React.createElement(UdpFlexbox, { gap: "md" }, !isEditMode && !lookupCreateAvailable && (React.createElement(UdpMessageBar, { intent: "warning" }, "UdpLookup create method is not promoted. Lookup creation i disabled")), !isEditMode && lookupCreateAvailable && !virtualAvailable && (React.createElement(UdpMessageBar, { intent: "warning" }, !columnCreateAvailable && !valueCreateAvailable
        ? 'UdpLookupColumn and UdpLookupValue create methods are not promoted.'
        : !columnCreateAvailable
            ? 'UdpLookupColumn create method is not promoted.'
            : 'UdpLookupValue create method is not promoted.', ' ', "Virtual lookup creation is disabled")), React.createElement(UdpCard, { label: "Lookup Details" }, React.createElement(UdpFlexbox, { direction: "column", gap: "sm" }, React.createElement(UdpTextInput, { label: "Display Name", value: name, onChange: (e) => setName(e.target.value), required: true, disabled: isEditMode ? !lookupUpdateAvailable : !lookupCreateAvailable }), React.createElement(UdpTextInput, { label: "Description", value: description, onChange: (e) => setDescription(e.target.value), disabled: isEditMode ? !lookupUpdateAvailable : !lookupCreateAvailable }), isEditMode ? (React.createElement(UdpFlexbox, { direction: "row", gap: "sm", style: { alignItems: 'center' } }, React.createElement(UdpText, { variant: "caption1" }, "Type:"), React.createElement(UdpBadge, { appearance: "tint", color: (lookup === null || lookup === void 0 ? void 0 : lookup.typeId) === LookupTypeId.Domain ? 'warning' : 'informative' }, (lookup === null || lookup === void 0 ? void 0 : lookup.typeId) === LookupTypeId.Domain ? 'Domain' : 'Virtual'))) : (React.createElement(UdpDropdown, { label: "Type", hint: "Domain: backed by an entity table. Virtual: custom key/value pairs", options: typeOptions, value: typeOption, optionLabel: "label", optionValue: "value", onChange: (e) => setTypeOption(e.target.value), disabled: !lookupCreateAvailable })))), isDomain && !isEditMode && (React.createElement(UdpCard, { label: "Field Mapping" }, React.createElement(UdpFlexbox, { direction: "column", gap: "md" }, React.createElement(UdpDropdown, { label: "Domain Entity", hint: "The entity table this lookup resolves against", options: entityOptions, value: selectedEntity, optionLabel: "label", optionValue: "value", onChange: handleEntityChange }), fieldOptions.length > 0 && (React.createElement(React.Fragment, null, React.createElement(UdpDropdown, { label: "Key Name", hint: "The field used to match values (e.g. the ID field)", options: fieldOptions, value: keyNameOption, optionLabel: "label", optionValue: "value", onChange: (e) => setKeyNameOption(e.target.value) }), React.createElement(UdpDropdown, { label: "Value Name", hint: "The field displayed to the user (e.g. name)", options: fieldOptions, value: valueNameOption, optionLabel: "label", optionValue: "value", onChange: (e) => setValueNameOption(e.target.value) })))))), isDomain && isEditMode && (React.createElement(UdpCard, { label: "Field Mapping" }, React.createElement(UdpFlexbox, { direction: "column", gap: "sm" }, React.createElement(UdpTextInput, { label: "Domain Name", value: (_a = getSimpleName(lookup === null || lookup === void 0 ? void 0 : lookup.domainName)) !== null && _a !== void 0 ? _a : '', disabled: true }), React.createElement(UdpDropdown, { label: "Key Name", hint: "The field used to match values (e.g. the ID field)", options: editDomainFieldOptions, value: (_b = editDomainFieldOptions.find((o) => o.value === keyName)) !== null && _b !== void 0 ? _b : null, optionLabel: "label", optionValue: "value", onChange: (e) => {
            var _a;
            var _b;
            return setKeyName((_b = (_a = e.target.value) === null || _a === void 0 ? void 0 : _a.value) !== null && _b !== void 0 ? _b : '');
        } }), React.createElement(UdpDropdown, { label: "Value Name", hint: "The field displayed to the user (e.g. name)", options: editDomainFieldOptions, value: (_c = editDomainFieldOptions.find((o) => o.value === valueName)) !== null && _c !== void 0 ? _c : null, optionLabel: "label", optionValue: "value", onChange: (e) => {
            var _a;
            var _b;
            return setValueName((_b = (_a = e.target.value) === null || _a === void 0 ? void 0 : _a.value) !== null && _b !== void 0 ? _b : '');
        } })))), isVirtual && !(isEditMode && loadingData) && (React.createElement(React.Fragment, null, React.createElement(UdpCard, { label: "Columns", subtitle: "The first two columns are used as the key and display value." }, React.createElement(UdpFlexbox, { direction: "column", gap: "md" }, activeCols.map((col, i) => {
        var _a;
        return (React.createElement(UdpFlexbox, { key: isEditMode ? (_a = col.id) !== null && _a !== void 0 ? _a : `new-${i}` : i, direction: "row", gap: "sm", style: { alignItems: 'flex-end' } }, React.createElement(UdpTextInput, { label: i === 0
                ? 'Column 1 (Key)'
                : i === 1
                    ? 'Column 2 (Value)'
                    : `Column ${i + 1}`, value: col.name, onChange: (e) => isEditMode
                ? updateEditColumnField(i, 'name', e.target.value)
                : updateColumn(i, 'name', e.target.value), style: { flex: 1 }, includeErrorPadding: false }), React.createElement(UdpDropdown, { label: "Type", includeErrorPadding: false, options: COLUMN_TYPE_OPTIONS, value: col.typeOption, optionLabel: "label", optionValue: "value", onChange: (e) => isEditMode
                ? updateEditColumnField(i, 'typeOption', e.target.value)
                : updateColumn(i, 'typeOption', e.target.value), style: { width: '120px' } }), activeCols.length > 2 && (React.createElement(UdpIconButton, { iconName: "delete", appearance: "transparent", size: "small", onClick: () => isEditMode ? removeEditColumn(i) : removeColumn(i), ariaLabel: "Remove column" }))));
    }), (isEditMode ? columnCreateAvailable : true) && (React.createElement(UdpButton, { startIconName: "add", appearance: "subtle", size: "small", onClick: isEditMode ? addEditColumn : addColumn, ariaLabel: "Add column" }, "Add Additional Colum")))), React.createElement(UdpCard, { label: "Values" }, React.createElement(UdpFlexbox, { direction: "column", gap: "md" }, activeRows.map((row, rowIdx) => (React.createElement(UdpFlexbox, { key: rowIdx, direction: "row", gap: "sm", style: { alignItems: 'flex-end' } }, row.map((cell, colIdx) => {
        var _a;
        var _b;
        const col = activeCols[colIdx];
        const colLabel = (col === null || col === void 0 ? void 0 : col.name) || `Column ${colIdx + 1}`;
        const cellValue = isEditMode ? cell.value : cell;
        const onCellChange = (val) => isEditMode
            ? updateEditRowValue(rowIdx, colIdx, val)
            : updateRowValue(rowIdx, colIdx, val);
        const colTypeId = (_a = col === null || col === void 0 ? void 0 : col.typeOption) === null || _a === void 0 ? void 0 : _a.value;
        if (colTypeId === LookupColumnTypeId.Boolean) {
            return (React.createElement(UdpDropdown, { key: colIdx, label: colLabel, options: BOOLEAN_OPTIONS, value: (_b = BOOLEAN_OPTIONS.find((o) => o.value === cellValue)) !== null && _b !== void 0 ? _b : null, optionLabel: "label", optionValue: "value", onChange: (e) => {
                    var _a;
                    var _b;
                    return onCellChange((_b = (_a = e.target.value) === null || _a === void 0 ? void 0 : _a.value) !== null && _b !== void 0 ? _b : '');
                }, style: { flex: 1 }, includeErrorPadding: false }));
        }
        return (React.createElement(UdpTextInput, { key: colIdx, label: colLabel, value: cellValue, onChange: (e) => onCellChange(e.target.value), style: { flex: 1 }, includeErrorPadding: false, autocomplete: "off", type: colTypeId === LookupColumnTypeId.Long || colTypeId === LookupColumnTypeId.Double ? 'number' : 'text' }));
    }), activeRows.length > 1 && (React.createElement(UdpIconButton, { iconName: "delete", appearance: "transparent", size: "small", onClick: () => isEditMode ? removeEditRow(rowIdx) : removeRow(rowIdx), ariaLabel: "Remove row" }))))), (isEditMode ? valueCreateAvailable : true) && (React.createElement(UdpButton, { startIconName: "add", appearance: "subtle", size: "small", onClick: isEditMode ? addEditRow : addRow, ariaLabel: "Add value mapping" }, "Add Value Mappin")))))), isVirtual && isEditMode && loadingData && (React.createElement(UdpText, { variant: "caption1" }, "Loading columns and values..."))), React.createElement("div", { slot: "footer" }, React.createElement(UdpButton, { appearance: "primary", onClick: handleSave, disabled: saveDisabled, loading: saving }, isEditMode ? 'Save' : 'Create Lookup'))));
};
export default LookupCreationSheet;
//# sourceMappingURL=LookupCreationSheet.js.map