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

interface LogsTabProps {
  logs: ControlLogEntry[];
  providerIds: string[];
}

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

const SOURCE_COLORS: Record<string, string> = {
  proxy: 'text-blue-400',
  upstream: 'text-emerald-400',
  model: 'text-amber-400',
};

export function LogsTab({ logs, providerIds }: LogsTabProps) {
  const [manualPaused, setManualPaused] = useState(false);
  const [hoverPaused, setHoverPaused] = useState(false);
  const paused = manualPaused || hoverPaused;
  const [sourceFilter, setSourceFilter] = useState<string | null>(null);
  const [hostFilter, setHostFilter] = useState<string | null>(null);

  const sources = useMemo(() => {
    const set = new Set<string>();
    for (const l of logs) {
      set.add(l.source);
    }
    return Array.from(set);
  }, [logs]);

  const filtered = useMemo(() => {
    return logs.filter((l) => {
      if (sourceFilter && l.source !== sourceFilter) return false;
      if (hostFilter && l.providerId !== hostFilter) return false;
      return true;
    });
  }, [logs, sourceFilter, hostFilter]);

  const itemContent = useCallback(
    (_index: number, entry: ControlLogEntry) => {
      return (
        <div className="flex items-start gap-2 px-3 py-0.5 text-[11px] font-mono border-b border-border/10">
          <span className="text-muted-foreground shrink-0 w-20">
            {formatTime(entry.ts)}
          </span>
          <span
            className={cn(
              'shrink-0 w-20 font-medium',
              SOURCE_COLORS[entry.source] ?? 'text-muted-foreground',
            )}
          >
            [{entry.source}]
          </span>
          <span className="shrink-0 w-24 text-muted-foreground">
            {entry.providerId}
          </span>
          <span className="text-foreground/80 break-all">{entry.line}</span>
        </div>
      );
    },
    [],
  );

  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">
        <Filter className="size-3 text-muted-foreground" />

        <div className="text-[10px] uppercase tracking-wider text-muted-foreground font-medium">
          Source
        </div>
        <FilterChip
          label="All"
          active={sourceFilter === null}
          onClick={() => setSourceFilter(null)}
        />
        {sources.map((s) => (
          <FilterChip
            key={s}
            label={s}
            active={sourceFilter === s}
            onClick={() => setSourceFilter(sourceFilter === s ? null : s)}
          />
        ))}

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

        <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="flex-1" />

        <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>

      {/* Log feed */}
      <div className="flex-1 min-h-0 bg-muted/10">
        <Virtuoso
          data={filtered}
          itemContent={itemContent}
          followOutput={paused ? undefined : 'bottom' as FollowOutput}
          overscan={400}
          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>
  );
}
