//
// Copyright 2023 DXOS.org
//
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { DynamicTable } from '@dxos/react-ui-table';
import { mx } from '@dxos/ui-theme';
import { JsonView } from './JsonView';
import { Placeholder } from './Placeholder';
export const MasterDetailTable = ({ properties, data, detailsTransform, detailsPosition = 'right', onSelectionChanged, }) => {
    const [selected, setSelected] = useState(undefined);
    const [transformedData, setTransformedData] = useState(undefined);
    const [isLoading, setIsLoading] = useState(false);
    const handleRowClicked = useCallback((row) => {
        setSelected(row);
        onSelectionChanged?.(row.id);
    }, [onSelectionChanged, setSelected]);
    useEffect(() => {
        if (!selected) {
            setTransformedData(undefined);
            return;
        }
        if (!detailsTransform) {
            setTransformedData(selected);
            return;
        }
        const result = detailsTransform(selected);
        if (result instanceof Promise) {
            setIsLoading(true);
            result
                .then((data) => {
                setTransformedData(data);
            })
                .catch((error) => {
                setTransformedData({ error: String(error) });
            })
                .finally(() => {
                setIsLoading(false);
            });
        }
        else {
            setTransformedData(result);
        }
    }, [selected, detailsTransform]);
    const gridLayout = useMemo(() => {
        return detailsPosition === 'right' ? 'grid grid-cols-[2fr_1fr]' : 'grid grid-rows-[3fr_4fr]';
    }, [detailsPosition]);
    const features = useMemo(() => ({
        selection: { enabled: true, mode: 'single' },
        dataEditable: false,
    }), []);
    return (React.createElement("div", { className: mx('bs-full divide-y divide-separator', gridLayout) },
        React.createElement(DynamicTable, { properties: properties, rows: data, features: features, onRowClick: handleRowClicked }),
        React.createElement("div", { className: mx('overflow-auto text-sm', detailsPosition === 'right' && 'border-separator border-is') }, selected ? (isLoading ? (React.createElement("p", { className: mx('font-mono text-xs p-1') }, "Loading details...")) : (React.createElement(JsonView, { data: transformedData }))) : (React.createElement(Placeholder, { label: 'Details' })))));
};
//# sourceMappingURL=MasterDetailTable.js.map