import { useState, useMemo } from 'react';
import { useControlStream } from '@/hooks/useControlStream';
import { FleetTab } from '@/components/control/FleetTab';
import { ActivityTab } from '@/components/control/ActivityTab';
import { LogsTab } from '@/components/control/LogsTab';
import { CaptureDrawer } from '@/components/control/CaptureDrawer';
import { PlaygroundTab } from '@/components/control/PlaygroundTab';
import { BenchTab } from '@/components/control/BenchTab';
import { EvalsTab } from '@/components/control/EvalsTab';
import { ReportsTab } from '@/components/control/ReportsTab';
import { JobsTab } from '@/components/control/JobsTab';
import { cn } from '@/lib/utils';
import { Radio, Activity, ScrollText, Gamepad2, Gauge, Brain, FileText, ListChecks, Route } from 'lucide-react';

type Tab = 'fleet' | 'activity' | 'logs' | 'playground' | 'bench' | 'evals' | 'jobs' | 'routing' | 'reports';

const CONNECTION_STYLE: Record<'live' | 'connecting' | 'reconnecting' | 'down', { dot: string; label: string }> = {
  live: { dot: 'bg-green-500', label: 'live' },
  connecting: { dot: 'bg-amber-500 animate-pulse', label: 'connecting' },
  reconnecting: { dot: 'bg-amber-500 animate-pulse', label: 'reconnecting' },
  down: { dot: 'bg-red-500', label: 'disconnected' },
};

export function Control() {
  const [activeTab, setActiveTab] = useState<Tab>('fleet');
  const fleet = useControlStream();
  const providerIds = fleet.hosts.map((h) => h.providerId);
  const conn = CONNECTION_STYLE[fleet.connection] ?? CONNECTION_STYLE.connecting;
  const activeJobs = fleet.jobs.filter((j) => j.status === 'running' || j.status === 'queued').length;

  // P2.4: Capture drawer state
  const [captureDrawer, setCaptureDrawer] = useState<{ requestId: number; providerId: string } | null>(null);

  // Compute the latest GPU data per provider from perf samples.
  const gpuMap = useMemo(() => {
    const map = new Map<string, { vram_used: number; vram_total: number; temperature: number; power: number }>();
    for (const sample of fleet.perfSamples) {
      const gpu = sample.gpu as { vram_used?: number; vram_total?: number; temperature?: number; power?: number } | undefined;
      if (gpu) {
        map.set(sample.providerId, {
          vram_used: gpu.vram_used ?? 0,
          vram_total: gpu.vram_total ?? 0,
          temperature: gpu.temperature ?? 0,
          power: gpu.power ?? 0,
        });
      }
    }
    return map;
  }, [fleet.perfSamples]);

  const tabs: Array<{ id: Tab; label: string; icon: typeof Radio; badge?: number }> = [
    { id: 'fleet', label: 'Fleet', icon: Radio },
    { id: 'activity', label: 'Activity', icon: Activity },
    { id: 'logs', label: 'Logs', icon: ScrollText },
    { id: 'playground', label: 'Playground', icon: Gamepad2 },
    { id: 'bench', label: 'Bench', icon: Gauge },
    { id: 'evals', label: 'Evals', icon: Brain },
    { id: 'jobs', label: 'Jobs', icon: ListChecks, badge: activeJobs },
    { id: 'routing', label: 'Routing', icon: Route },
    { id: 'reports', label: 'Reports', icon: FileText },
  ];

  return (
    <div className="flex-1 flex flex-col bg-background text-foreground">
      {/* Tab bar */}
      <div className="flex items-center gap-1 border-b border-border/40 px-4 shrink-0">
        {tabs.map((tab) => (
          <button
            key={tab.id}
            type="button"
            onClick={() => setActiveTab(tab.id)}
            className={cn(
              'flex items-center gap-1.5 px-3 py-2 text-sm rounded-t-md border border-b-0 -mb-px transition-colors',
              activeTab === tab.id
                ? 'bg-background border-border text-foreground'
                : 'border-transparent text-muted-foreground hover:text-foreground hover:bg-muted/30',
            )}
          >
            <tab.icon className="size-3.5" />
            <span>{tab.label}</span>
            {tab.badge != null && tab.badge > 0 && (
              <span className="ml-0.5 px-1.5 py-px text-[10px] leading-none rounded-full bg-primary/20 text-primary">{tab.badge}</span>
            )}
          </button>
        ))}

        {/* B3: live connection status pill */}
        <div
          className="ml-auto inline-flex items-center gap-1.5 px-2 py-0.5 text-[11px] text-muted-foreground"
          title={`control stream: ${conn.label}`}
        >
          <span className={cn('w-1.5 h-1.5 rounded-full', conn.dot)} />
          <span>{conn.label}</span>
        </div>
      </div>

      {/* Tab content */}
      <div className="flex-1 flex flex-col min-h-0">
        {activeTab === 'fleet' && (
          <FleetTab hosts={fleet.hosts} gpuMap={gpuMap} perfSamples={fleet.perfSamples} connection={fleet.connection} />
        )}
        {activeTab === 'activity' && (
          <ActivityTab
            requests={fleet.requests}
            providerIds={providerIds}
            onOpenCapture={(entry) => setCaptureDrawer({ requestId: entry.id, providerId: entry.providerId })}
          />
        )}
        {activeTab === 'logs' && (
          <LogsTab logs={fleet.logs} providerIds={providerIds} />
        )}
        {activeTab === 'playground' && (
          <PlaygroundTab providerIds={providerIds} />
        )}
        {activeTab === 'bench' && (
          <BenchTab providerIds={providerIds} />
        )}
        {activeTab === 'evals' && (
          <EvalsTab providerIds={providerIds} />
        )}
        {activeTab === 'jobs' && (
          <JobsTab jobs={fleet.jobs} />
        )}
        {activeTab === 'routing' && (
          <ReportsTab mode="routing" />
        )}
        {activeTab === 'reports' && (
          <ReportsTab mode="reports" />
        )}
      </div>

      {/* P2.4: Capture drawer overlay */}
      {captureDrawer && (
        <CaptureDrawer
          requestId={captureDrawer.requestId}
          providerId={captureDrawer.providerId}
          onClose={() => setCaptureDrawer(null)}
        />
      )}
    </div>
  );
}
