import React, { useCallback, useMemo } from "react";
import DragAndDrop from "../../data/drag-and-drop/root/DragAndDropRoot.js";
import { Checkbox } from "../../form/checkbox/index.js";
import { Fieldset } from "../../form/fieldset/index.js";
function DataGridPreferencesColumnSettings({ columns, onColumnsChange, }) {
    const visibleCount = columns.filter((c) => !!c.visible).length;
    const isAllVisible = visibleCount === columns.length;
    const dndItems = useMemo(() => columns.map(({ id, label }) => ({ id, label })), [columns]);
    const colMap = useMemo(() => new Map(columns.map((c) => [c.id, c])), [columns]);
    const setDndItems = useCallback((items) => {
        const newItems = items;
        onColumnsChange(newItems.flatMap((item) => {
            const col = colMap.get(item.id);
            return col ? [col] : [];
        }));
    }, [colMap, onColumnsChange]);
    const toggleAll = useCallback(() => {
        const newVisible = !isAllVisible;
        onColumnsChange(columns.map((c) => (Object.assign(Object.assign({}, c), { visible: c.visible === "always" ? "always" : newVisible }))));
    }, [columns, isAllVisible, onColumnsChange]);
    const toggleColumn = useCallback((id) => {
        const col = colMap.get(id);
        if ((col === null || col === void 0 ? void 0 : col.visible) === "always")
            return;
        onColumnsChange(columns.map((c) => (c.id === id ? Object.assign(Object.assign({}, c), { visible: !c.visible }) : c)));
    }, [colMap, columns, onColumnsChange]);
    return (React.createElement(Fieldset, { legend: "Kolonner", size: "small" },
        React.createElement(Checkbox, { size: "small", checked: isAllVisible, indeterminate: visibleCount > 0 && !isAllVisible, onChange: toggleAll }, `Velg alle (${visibleCount}/${columns.length})`),
        React.createElement(DragAndDrop, { className: "aksel-data-grid__preferences-dnd", items: dndItems, setItems: setDndItems, renderItem: (item) => {
                var _a, _b;
                const visibleState = (_b = (_a = colMap.get(item.id)) === null || _a === void 0 ? void 0 : _a.visible) !== null && _b !== void 0 ? _b : true;
                const alwaysVisible = visibleState === "always";
                return (React.createElement(Checkbox, { size: "small", checked: visibleState !== false, onChange: () => toggleColumn(item.id), disabled: alwaysVisible }, item.label));
            } })));
}
export { DataGridPreferencesColumnSettings };
//# sourceMappingURL=DataGridPreferencesColumnSettings.js.map