import { useCallback, useMemo } from 'react';

import { useWorkspace } from './WorkspaceContext';
import type { PanelConfig } from './types';

/**
 * Read and write one panel's own settings.
 *
 * The blob lives on the panel node in the dashboard layout, which means it is persisted server-side,
 * survives a reload and a restart, travels with the panel through swap and drag, and is deleted exactly
 * when the panel is. The framework never looks inside it — `T` is a promise the calling app makes to
 * itself, so validate on read if the shape has changed since a config was written.
 *
 * `setConfig` takes a whole object or an updater, like `useState`. Writing `undefined` — or an object
 * with no keys — removes the config entirely, so an untouched panel adds nothing to the persisted layout.
 *
 * Returns a no-op setter in a locked or preview workspace (`WorkspaceLayout`, the dashboard-creation
 * preview): those render a layout they do not own, and a write would have nowhere to go.
 */
export function usePanelConfig<T extends PanelConfig = PanelConfig>(
  panelId: string,
): [T | undefined, (next: T | undefined | ((prev: T | undefined) => T | undefined)) => void] {
  const { panelConfigs, setPanelConfig } = useWorkspace();

  const config = panelConfigs[panelId] as T | undefined;

  const setConfig = useCallback(
    (next: T | undefined | ((prev: T | undefined) => T | undefined)) => {
      const value = typeof next === 'function' ? next(config) : next;
      setPanelConfig(panelId, value);
    },
    [panelId, config, setPanelConfig],
  );

  return useMemo(() => [config, setConfig], [config, setConfig]);
}
