'use client';

import { useEffect, useRef } from 'react';
import { cn } from '@/lib/utils';

export type StreamEventType = 'text' | 'tool_use' | 'tool_result' | 'error';

export interface StreamEvent {
  id: string;
  timestamp: string;
  type: StreamEventType;
  content: string;
}

const EVENT_TYPE_STYLES: Record<StreamEventType, { badge: string; border: string }> = {
  text: {
    badge: 'bg-gray-100 text-gray-700',
    border: 'border-l-gray-300',
  },
  tool_use: {
    badge: 'bg-blue-100 text-blue-700',
    border: 'border-l-blue-400',
  },
  tool_result: {
    badge: 'bg-green-100 text-green-700',
    border: 'border-l-green-400',
  },
  error: {
    badge: 'bg-red-100 text-red-700',
    border: 'border-l-red-400',
  },
};

const EVENT_TYPE_LABELS: Record<StreamEventType, string> = {
  text: 'Text',
  tool_use: 'Tool Use',
  tool_result: 'Tool Result',
  error: 'Error',
};

interface StreamEventViewerProps {
  events: StreamEvent[];
  autoScroll?: boolean;
  className?: string;
}

function formatTimestamp(iso: string): string {
  try {
    const date = new Date(iso);
    return date.toLocaleTimeString('en-US', {
      hour12: false,
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
    });
  } catch {
    return iso;
  }
}

export function StreamEventViewer({
  events,
  autoScroll = true,
  className,
}: StreamEventViewerProps) {
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (autoScroll && containerRef.current) {
      containerRef.current.scrollTop = containerRef.current.scrollHeight;
    }
  }, [events, autoScroll]);

  return (
    <div
      ref={containerRef}
      className={cn(
        'overflow-y-auto rounded-lg border bg-card',
        className,
      )}
    >
      {events.length === 0 ? (
        <div className="flex items-center justify-center p-8 text-sm text-muted-foreground">
          No events yet
        </div>
      ) : (
        <div className="divide-y">
          {events.map((event) => {
            const styles = EVENT_TYPE_STYLES[event.type];

            return (
              <div
                key={event.id}
                className={cn('flex gap-3 p-3 border-l-2', styles.border)}
              >
                <div className="flex flex-col items-start gap-1 shrink-0">
                  <span className="text-xs text-muted-foreground font-mono">
                    {formatTimestamp(event.timestamp)}
                  </span>
                  <span
                    className={cn(
                      'inline-flex rounded px-1.5 py-0.5 text-[10px] font-semibold',
                      styles.badge,
                    )}
                  >
                    {EVENT_TYPE_LABELS[event.type]}
                  </span>
                </div>
                <pre
                  className={cn(
                    'flex-1 whitespace-pre-wrap break-all text-sm font-mono',
                    event.type === 'error' && 'text-red-600',
                  )}
                >
                  {event.content}
                </pre>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
