import { useEffect, useMemo } from 'react';
import { useParams, useNavigate } from 'react-router';
import type { LayoutNode, SelectedSession } from 'officerdev';
import { WorkspaceView } from 'officerdev';
import { useIsMobile } from 'hooks/useIsMobile';
import { useDashboardState } from 'state/useDashboardState';
import { usePanelChannel } from 'hooks/usePanelChannel';
import { defaultLayout } from './defaultLayout';

// Allowed panel app types for the /chat screen
const ALLOWED_APP_TYPES = new Set<string | null>(['chat-session-list', 'chat-detail', null]);

/** Recursively fix any panel that uses a wrong app type (e.g. officerdev/chat) */
function normalizeLayout(node: LayoutNode): LayoutNode {
  if (node.type === 'panel') {
    if (!ALLOWED_APP_TYPES.has(node.appType)) {
      return { ...node, appType: 'chat-detail' };
    }
    return node;
  }
  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;
}

type SessionListPageProps = {
  isNew?: boolean;
};

export const SessionListPage = ({ isNew }: SessionListPageProps) => {
  const { sessionId } = useParams<{ sessionId: string }>();
  const [, setSelected] = usePanelChannel<SelectedSession>('chat:selected-session', null);
  const rawWorkspace = useDashboardState<LayoutNode>('screens/chat', defaultLayout);
  const isMobile = useIsMobile();
  const navigate = useNavigate();
  const mobilePanelId = isMobile && (sessionId || isNew) ? 'chat-detail' : undefined;

  // Normalize synchronously so the wrong panel never renders
  const workspace = useMemo(() => {
    const fixed = normalizeLayout(rawWorkspace.value);
    if (fixed === rawWorkspace.value) return rawWorkspace;
    return { ...rawWorkspace, value: fixed };
  }, [rawWorkspace]);

  // Persist the fix to the backend
  useEffect(() => {
    if (rawWorkspace.isLoaded && workspace.value !== rawWorkspace.value) {
      rawWorkspace.setValue(workspace.value);
    }
  }, [rawWorkspace.isLoaded, workspace.value, rawWorkspace.value]);

  useEffect(() => {
    if (isNew) {
      setSelected({ id: `new:${Date.now()}` });
      return;
    }
    if (!sessionId) return;
    setSelected({ id: sessionId });
  }, [sessionId, isNew]);

  return (
    <div className="h-full w-full pt-2">
      <WorkspaceView
        workspace={workspace}
        locked
        mobilePanelId={mobilePanelId}
        onMobilePanelChange={(id) => {
          if (!id) navigate('/chat', { replace: true });
        }}
      />
    </div>
  );
};
