import React, { useMemo, useState, } from "react";
import { DEFAULT_LOGS_TABLE_COLUMNS, getLogsAttributeColumnId, normalizeLogsTableColumns, } from "../types";
import useComponentOutsideClick from "../../../Types/UseComponentOutsideClick";
const triggerButtonClassName = "inline-flex items-center gap-1.5 rounded-md border border-gray-200 bg-white px-2.5 py-1.5 text-xs font-medium text-gray-700 shadow-sm transition-colors hover:border-gray-300 hover:bg-gray-50";
const actionButtonClassName = "rounded-md px-2 py-1 text-xs font-medium text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-700";
const ColumnSelector = (props) => {
    const { ref, isComponentVisible, setIsComponentVisible } = useComponentOutsideClick(false);
    const [searchQuery, setSearchQuery] = useState("");
    const selectedColumnIds = useMemo(() => {
        return normalizeLogsTableColumns(props.selectedColumns);
    }, [props.selectedColumns]);
    const availableColumnsById = useMemo(() => {
        return new Map(props.availableColumns.map((column) => {
            return [column.id, column];
        }));
    }, [props.availableColumns]);
    const selectedColumns = useMemo(() => {
        return selectedColumnIds.map((columnId) => {
            return (availableColumnsById.get(columnId) || {
                id: columnId,
                label: columnId,
            });
        });
    }, [availableColumnsById, selectedColumnIds]);
    const availableColumns = useMemo(() => {
        const normalizedSearchQuery = searchQuery.trim().toLowerCase();
        return props.availableColumns.filter((column) => {
            if (selectedColumnIds.includes(column.id)) {
                return false;
            }
            if (!normalizedSearchQuery) {
                return true;
            }
            return column.label.toLowerCase().includes(normalizedSearchQuery);
        });
    }, [props.availableColumns, searchQuery, selectedColumnIds]);
    const trimmedAttributeKey = searchQuery.trim();
    const customAttributeColumnId = trimmedAttributeKey
        ? getLogsAttributeColumnId(trimmedAttributeKey)
        : "";
    const isCustomAttributeAlreadySelected = customAttributeColumnId !== "" &&
        selectedColumnIds.includes(customAttributeColumnId);
    const isCustomAttributeAlreadyAvailable = availableColumns.some((column) => {
        return column.id === customAttributeColumnId;
    });
    const canAddCustomAttribute = trimmedAttributeKey !== "" &&
        !isCustomAttributeAlreadySelected &&
        !isCustomAttributeAlreadyAvailable;
    const updateColumns = (columns) => {
        props.onChange(normalizeLogsTableColumns(columns));
    };
    const moveColumn = (columnId, direction) => {
        const currentIndex = selectedColumnIds.indexOf(columnId);
        if (currentIndex === -1) {
            return;
        }
        const nextIndex = currentIndex + direction;
        if (nextIndex < 0 || nextIndex >= selectedColumnIds.length) {
            return;
        }
        const nextColumns = [...selectedColumnIds];
        const currentColumn = nextColumns[currentIndex];
        nextColumns[currentIndex] = nextColumns[nextIndex];
        nextColumns[nextIndex] = currentColumn;
        updateColumns(nextColumns);
    };
    const removeColumn = (columnId) => {
        if (selectedColumnIds.length <= 1) {
            return;
        }
        updateColumns(selectedColumnIds.filter((selectedColumnId) => {
            return selectedColumnId !== columnId;
        }));
    };
    const addColumn = (columnId) => {
        updateColumns([...selectedColumnIds, columnId]);
    };
    return (React.createElement("div", { className: "relative", ref: ref },
        React.createElement("button", { type: "button", className: triggerButtonClassName, onClick: () => {
                setIsComponentVisible(!isComponentVisible);
            }, "aria-haspopup": "dialog", "aria-expanded": isComponentVisible },
            React.createElement("span", null, "Columns"),
            React.createElement("span", { className: "text-xs text-gray-400" }, selectedColumnIds.length)),
        isComponentVisible && (React.createElement("div", { className: "absolute right-0 z-20 mt-2 w-96 rounded-lg border border-gray-200 bg-white p-4 shadow-xl" },
            React.createElement("div", { className: "flex items-center justify-between gap-3" },
                React.createElement("div", null,
                    React.createElement("h3", { className: "text-sm font-semibold text-gray-900" }, "Columns"),
                    React.createElement("p", { className: "text-xs text-gray-500" }, "Add, remove, and reorder visible columns.")),
                React.createElement("button", { type: "button", className: "text-xs font-medium text-gray-500 transition-colors hover:text-gray-700", onClick: () => {
                        updateColumns(DEFAULT_LOGS_TABLE_COLUMNS);
                    } }, "Reset")),
            React.createElement("div", { className: "mt-4" },
                React.createElement("p", { className: "mb-2 text-[11px] font-semibold uppercase tracking-wider text-gray-400" }, "Selected"),
                React.createElement("div", { className: "space-y-2" }, selectedColumns.map((column, index) => {
                    const isFirst = index === 0;
                    const isLast = index === selectedColumns.length - 1;
                    return (React.createElement("div", { key: column.id, className: "flex items-center justify-between rounded-md border border-gray-200 px-3 py-2" },
                        React.createElement("span", { className: "min-w-0 truncate text-sm text-gray-700" }, column.label),
                        React.createElement("div", { className: "flex items-center gap-1" },
                            React.createElement("button", { type: "button", className: actionButtonClassName, onClick: () => {
                                    moveColumn(column.id, -1);
                                }, disabled: isFirst }, "Up"),
                            React.createElement("button", { type: "button", className: actionButtonClassName, onClick: () => {
                                    moveColumn(column.id, 1);
                                }, disabled: isLast }, "Down"),
                            React.createElement("button", { type: "button", className: actionButtonClassName, onClick: () => {
                                    removeColumn(column.id);
                                }, disabled: selectedColumns.length <= 1 }, "Remove"))));
                }))),
            React.createElement("div", { className: "mt-4" },
                React.createElement("div", { className: "mb-2 flex items-center justify-between gap-3" },
                    React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-wider text-gray-400" }, "Available"),
                    React.createElement("input", { value: searchQuery, onChange: (event) => {
                            setSearchQuery(event.target.value);
                        }, onKeyDown: (event) => {
                            if (event.key === "Enter" && canAddCustomAttribute) {
                                event.preventDefault();
                                addColumn(customAttributeColumnId);
                                setSearchQuery("");
                            }
                        }, placeholder: "Search or type attribute", className: "w-48 rounded-md border border-gray-200 px-2 py-1 text-xs text-gray-600 focus:border-indigo-300 focus:outline-none focus:ring-2 focus:ring-indigo-100" })),
                React.createElement("div", { className: "max-h-72 space-y-2 overflow-y-auto pr-1" },
                    canAddCustomAttribute && (React.createElement("div", { className: "flex items-center justify-between rounded-md border border-dashed border-indigo-200 bg-indigo-50/50 px-3 py-2" },
                        React.createElement("div", { className: "min-w-0 flex-1" },
                            React.createElement("p", { className: "truncate text-sm text-gray-700" },
                                React.createElement("span", { className: "text-gray-500" }, "Attribute: "),
                                React.createElement("span", { className: "font-mono" }, trimmedAttributeKey)),
                            React.createElement("p", { className: "text-[11px] text-gray-500" }, "Add as a column to show this attribute's value.")),
                        React.createElement("button", { type: "button", className: "ml-3 rounded-md px-2 py-1 text-xs font-medium text-indigo-600 transition-colors hover:bg-indigo-100 hover:text-indigo-700", onClick: () => {
                                addColumn(customAttributeColumnId);
                                setSearchQuery("");
                            } }, "Add attribute"))),
                    availableColumns.length === 0 && !canAddCustomAttribute && (React.createElement("div", { className: "rounded-md border border-dashed border-gray-200 px-3 py-4 text-sm text-gray-500" }, trimmedAttributeKey
                        ? "No matching columns available."
                        : "Type an attribute name above to add it as a column.")),
                    availableColumns.map((column) => {
                        return (React.createElement("div", { key: column.id, className: "flex items-center justify-between rounded-md border border-gray-100 px-3 py-2" },
                            React.createElement("span", { className: "min-w-0 truncate text-sm text-gray-700" }, column.label),
                            React.createElement("button", { type: "button", className: actionButtonClassName, onClick: () => {
                                    addColumn(column.id);
                                } }, "Add")));
                    })))))));
};
export default ColumnSelector;
//# sourceMappingURL=ColumnSelector.js.map