import { useState, useMemo, useCallback } from 'react';
import { useParams } from 'react-router';
import { useGlobalFilters } from '@cameleer/design-system';
import { useExecutionDetail } from '../../api/queries/executions';
import { useDiagramByRoute } from '../../api/queries/diagrams';
import { useRouteCatalog } from '../../api/queries/catalog';
import { ExchangeHeader } from './ExchangeHeader';
import { ExecutionDiagram } from '../../components/ExecutionDiagram/ExecutionDiagram';
import { ProcessDiagram } from '../../components/ProcessDiagram';
import styles from './ExchangesPage.module.css';

// The full-width Dashboard table — used at every scope level
import Dashboard from '../Dashboard/Dashboard';

export default function ExchangesPage() {
  const { appId, routeId, exchangeId } = useParams<{
    appId?: string; routeId?: string; exchangeId?: string;
  }>();

  // No route scoped: full-width Dashboard
  if (!routeId) {
    return <Dashboard />;
  }

  // Route scoped: 50:50 split — Dashboard table on left, diagram on right
  return (
    <div className={styles.splitView}>
      <div className={styles.leftPanel}>
        <Dashboard />
      </div>
      <div className={styles.rightPanel}>
        <DiagramPanel appId={appId!} routeId={routeId} exchangeId={exchangeId} />
      </div>
    </div>
  );
}

// ─── Right panel: diagram + optional execution overlay ──────────────────────

interface DiagramPanelProps {
  appId: string;
  routeId: string;
  exchangeId?: string;
}

function DiagramPanel({ appId, routeId, exchangeId }: DiagramPanelProps) {
  const { timeRange } = useGlobalFilters();
  const timeFrom = timeRange.start.toISOString();
  const timeTo = timeRange.end.toISOString();

  // Fetch execution detail if an exchange is selected
  const { data: detail } = useExecutionDetail(exchangeId ?? null);

  // Fetch diagram for topology-only view
  const diagramQuery = useDiagramByRoute(appId, routeId);

  // Known route IDs for drill-down
  const { data: catalog } = useRouteCatalog(timeFrom, timeTo);
  const knownRouteIds = useMemo(() => {
    const ids = new Set<string>();
    if (catalog) {
      for (const app of catalog as any[]) {
        for (const r of app.routes || []) {
          ids.add(r.routeId);
        }
      }
    }
    return ids;
  }, [catalog]);

  // If exchange selected: show header + ExecutionDiagram
  if (exchangeId && detail) {
    return (
      <>
        <ExchangeHeader detail={detail} />
        <ExecutionDiagram
          executionId={exchangeId}
          executionDetail={detail}
          knownRouteIds={knownRouteIds}
        />
      </>
    );
  }

  // No exchange: show topology-only ProcessDiagram
  if (diagramQuery.data) {
    return (
      <ProcessDiagram
        application={appId}
        routeId={routeId}
        diagramLayout={diagramQuery.data}
        knownRouteIds={knownRouteIds}
      />
    );
  }

  return (
    <div className={styles.emptyRight}>
      Loading diagram...
    </div>
  );
}
