import { useCallback, useMemo, useState } from 'react';
import { Virtuoso, type FollowOutput } from 'react-virtuoso';
import { ControlRequestEntry } from '@/hooks/useControlStream';
import { cn } from '@/lib/utils';
import { Pause, Play, Search } from 'lucide-react';

interface ActivityTabProps {
  requests: ControlRequestEntry[];
  providerIds: string[];
  onOpenCapture?: (entry: ControlRequestEntry) => void;
}

function formatDuration(ms: number | null): string {
  if (ms == null) return '-';
  if (ms < 1000) return `${ms}ms`;
  return `${(ms / 1000).toFixed(1)}s`;
}

function formatStatus(code: number | null): string {
  if (code == null) return '-';
  return String(code);
}

function formatTime(iso: string): string {
  const d = new Date(iso);
  return d.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit', second: '2-digit' });
}

export function ActivityTab({ requests, providerIds, onOpenCapture }: ActivityTabProps) {
  const [manualPaused, setManualPaused] = useState(false);
  const [hoverPaused, setHoverPaused] = useState(false);
  const [scrollPaused, setScrollPaused] = useState(false);
  const paused = manualPaused || hoverPaused || scrollPaused;
  const [modelFilter, setModelFilter] = useState<string | null>(null);
  const [hostFilter, setHostFilter] = useState<string | null>(null);

  const models = useMemo(() => {
    const set = new Set<string>();
    for (const r of requests) {
      if (r.model) set.add(r.model);
    }
    return Array.from(set).sort();
  }, [requests]);

  const filtered = useMemo(() => {
    return requests.filter((r) => {
      if (modelFilter && r.model !== modelFilter) return false;
      if (hostFilter && r.providerId !== hostFilter) return false;
      return true;
    });
  }, [requests, modelFilter, hostFilter]);

  const handleScroll = useCallback((isAtBottom: boolean) => {
    setScrollPaused(!isAtBottom);
  }, []);

  const itemContent = useCallback(
    (_index: number, entry: ControlRequestEntry) => {
      const isError = entry.statusCode != null && entry.statusCode >= 400;
      return (
        <div
          className={cn(
            'flex items-center gap-2 px-3 py-1.5 text-xs border-b border-border/20',
            isError && 'bg-red-500/5',
          )}
        >
          {/* Time */}
          <span className="text-muted-foreground font-mono shrink-0 w-20">
            {formatTime(entry.ts)}
          </span>

          {/* Provider */}
          <span className="shrink-0 text-muted-foreground w-24 truncate">
            {entry.providerId}
          </span>

          {/* Model */}
          <span className="shrink-0 w-48 truncate">
            {entry.model || '-'}
          </span>

          {/* Status */}
          <span
            className={cn(
              'shrink-0 w-10 text-right font-mono',
              isError && 'text-red-400 font-bold',
            )}
          >
            {formatStatus(entry.statusCode)}
          </span>

          {/* Duration */}
          <span className="shrink-0 w-16 text-right font-mono text-muted-foreground">
            {formatDuration(entry.durationMs)}
          </span>

          {/* P2.4: Capture inspector button */}
          {onOpenCapture && (
            <button
              type="button"
              onClick={() => onOpenCapture(entry)}
              className="ml-auto p-0.5 rounded hover:bg-muted/50 text-muted-foreground hover:text-foreground transition-colors shrink-0"
              title="Inspect capture"
            >
              <Search className="size-3" />
            </button>
          )}
        </div>
      );
    },
    [onOpenCapture],
  );

  return (
    <div className="flex-1 flex flex-col min-h-0">
      {/* Filter bar */}
      <div className="flex items-center gap-2 px-3 py-2 border-b border-border/40 shrink-0 flex-wrap">
        <div className="text-[10px] uppercase tracking-wider text-muted-foreground font-medium">
          Host
        </div>
        <FilterChip
          label="All"
          active={hostFilter === null}
          onClick={() => setHostFilter(null)}
        />
        {providerIds.map((pid) => (
          <FilterChip
            key={pid}
            label={pid}
            active={hostFilter === pid}
            onClick={() => setHostFilter(hostFilter === pid ? null : pid)}
          />
        ))}

        <div className="w-px h-4 bg-border mx-1" />

        <div className="text-[10px] uppercase tracking-wider text-muted-foreground font-medium">
          Model
        </div>
        <FilterChip
          label="All"
          active={modelFilter === null}
          onClick={() => setModelFilter(null)}
        />
        {models.slice(0, 12).map((m) => (
          <FilterChip
            key={m}
            label={m}
            active={modelFilter === m}
            onClick={() => setModelFilter(modelFilter === m ? null : m)}
          />
        ))}

        <div className="flex-1" />

        {/* Pause toggle */}
        <button
          type="button"
          onClick={() => setManualPaused((p) => !p)}
          className={cn(
            'inline-flex items-center gap-1 px-2 py-1 rounded text-[11px] font-medium',
            'border border-border/40 transition-colors',
            paused
              ? 'bg-amber-500/10 text-amber-400 border-amber-500/20'
              : 'bg-muted/30 text-muted-foreground hover:text-foreground',
          )}
          aria-label={manualPaused ? 'Resume follow' : 'Pause follow'}
          title={manualPaused ? 'Resume follow' : 'Pause follow'}
        >
          {manualPaused ? <Play className="size-3" /> : <Pause className="size-3" />}
          {paused ? 'Paused' : 'Follow'}
        </button>
      </div>

      {/* Feed */}
      <div className="flex-1 min-h-0">
        <Virtuoso
          data={filtered}
          itemContent={itemContent}
          followOutput={paused ? undefined : 'bottom' as FollowOutput}
          overscan={400}
          atBottomStateChange={handleScroll}
          components={{
            Footer: () => (
              <div className="h-2" />
            ),
          }}
          className="h-full"
          onMouseEnter={() => setHoverPaused(true)}
          onMouseLeave={() => setHoverPaused(false)}
        />
      </div>
    </div>
  );
}

function FilterChip({
  label,
  active,
  onClick,
}: {
  label: string;
  active: boolean;
  onClick: () => void;
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      className={cn(
        'px-2 py-0.5 rounded text-[11px] font-medium transition-colors border',
        active
          ? 'bg-primary/10 text-foreground border-primary/30'
          : 'bg-muted/20 text-muted-foreground border-border/30 hover:text-foreground hover:border-border/60',
      )}
    >
      {label}
    </button>
  );
}
