import { useEffect, useMemo } from 'react';
import type { LayoutNode } from 'officerdev';
import { WorkspaceView } from 'officerdev';
import { useDashboardState } from 'state/useDashboardState';
import { defaultLayout } from './defaultLayout';

// /system-monitor uses the Workspace/Panel system (like /music): a horizontal split with an (empty for
// now) left panel and the system snapshot on the right.

const ALLOWED_APP_TYPES = new Set<string | null>(['monitor-side', 'monitor-main', null]);

function normalizeLayout(node: LayoutNode): LayoutNode {
  if (node.type === 'panel') {
    return ALLOWED_APP_TYPES.has(node.appType) ? node : { ...node, appType: 'monitor-main' };
  }
  const children = node.children.map((c) => {
    const fixed = normalizeLayout(c.node);
    return fixed === c.node ? c : { ...c, node: fixed };
  });
  const changed = children.some((c, i) => c !== node.children[i]);
  return changed ? { ...node, children } : node;
}

export const SystemMonitorScreen = () => {
  const rawWorkspace = useDashboardState<LayoutNode>('screens/system-monitor', defaultLayout);

  const workspace = useMemo(() => {
    const fixed = normalizeLayout(rawWorkspace.value);
    if (fixed === rawWorkspace.value) return rawWorkspace;
    return { ...rawWorkspace, value: fixed };
  }, [rawWorkspace]);

  useEffect(() => {
    if (rawWorkspace.isLoaded && workspace.value !== rawWorkspace.value) {
      rawWorkspace.setValue(workspace.value);
    }
  }, [rawWorkspace.isLoaded, workspace.value, rawWorkspace.value]);

  return (
    <div className="h-full w-full pt-2">
      <WorkspaceView workspace={workspace} locked />
    </div>
  );
};
