import { useState, useCallback } from 'react';
import { Badge } from '@/components/ui/Badge';
import { McpRequestBuilder, type McpResponse, type McpServer, type HistoryEntry } from '@/components/mcp/McpRequestBuilder';
import { McpResponseViewer } from '@/components/mcp/McpResponseViewer';
import { McpHistory } from '@/components/mcp/McpHistory';

// ---------------------------------------------------------------------------
// Server status indicators
// ---------------------------------------------------------------------------

const SERVERS: { key: string; label: string }[] = [
  { key: 'code', label: 'Code' },
  { key: 'docs', label: 'Docs' },
  { key: 'otel', label: 'OTel' },
  { key: 'unified', label: 'Unified' },
];

// ---------------------------------------------------------------------------
// Page
// ---------------------------------------------------------------------------

export default function McpPage() {
  const [response, setResponse] = useState<McpResponse | null>(null);
  const [historyRevision, setHistoryRevision] = useState(0);

  // Replay state — using a key to remount the request builder
  const [replayKey, setReplayKey] = useState(0);
  const [replayServer, setReplayServer] = useState<McpServer | undefined>(undefined);
  const [replayTool, setReplayTool] = useState<string | undefined>(undefined);
  const [replayParams, setReplayParams] = useState<string | undefined>(undefined);

  const handleResponse = useCallback((res: McpResponse) => {
    setResponse(res);
  }, []);

  const handleHistoryChange = useCallback(() => {
    setHistoryRevision((r) => r + 1);
  }, []);

  const handleReplay = useCallback((entry: HistoryEntry) => {
    setReplayServer(entry.server);
    setReplayTool(entry.tool);
    setReplayParams(entry.params);
    setReplayKey((k) => k + 1);
  }, []);

  return (
    <div className="space-y-6">
      {/* Header — Server Status Indicators */}
      <div className="flex items-center gap-6">
        <h1 className="text-lg font-semibold text-text-primary">MCP Console</h1>
        <div className="flex items-center gap-4">
          {SERVERS.map((s) => (
            <Badge key={s.key} status="info">
              {s.label}
            </Badge>
          ))}
        </div>
      </div>

      {/* Main — Split Pane */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Left: Request Builder */}
        <McpRequestBuilder
          key={replayKey}
          onResponse={handleResponse}
          onHistoryChange={handleHistoryChange}
          initialServer={replayServer}
          initialTool={replayTool}
          initialParams={replayParams}
        />

        {/* Right: Response Viewer */}
        <McpResponseViewer response={response} />
      </div>

      {/* Bottom — History Table */}
      <McpHistory
        onReplay={handleReplay}
        revision={historyRevision}
      />
    </div>
  );
}
