import { useState } from 'react';
import { Activity, ChevronDown, ChevronUp, Zap } from 'lucide-react';
import { useWidgetContext } from '@/contexts/WidgetContext';
import { cn } from '@/lib/utils';

const EventLog = () => {
  const { recentEvents } = useWidgetContext();
  const [expanded, setExpanded] = useState(false);

  const displayEvents = expanded ? recentEvents.slice(0, 20) : recentEvents.slice(0, 3);

  return (
    <div className="bg-card/60 backdrop-blur-sm border border-border/50 rounded p-3 mb-4">
      <button 
        onClick={() => setExpanded(!expanded)}
        className="flex items-center gap-2 w-full text-left"
      >
        <Activity className="w-4 h-4 text-accent" />
        <span className="font-display text-xs uppercase text-accent">Widget Events</span>
        <span className="text-xs text-muted-foreground ml-1">({recentEvents.length})</span>
        <div className="flex-1" />
        {expanded ? (
          <ChevronUp className="w-4 h-4 text-muted-foreground" />
        ) : (
          <ChevronDown className="w-4 h-4 text-muted-foreground" />
        )}
      </button>

      {displayEvents.length > 0 && (
        <div className={cn("mt-2 space-y-1", expanded && "max-h-64 overflow-y-auto")}>
          {displayEvents.map((event, i) => (
            <div 
              key={`${event.timestamp}-${i}`}
              className="flex items-start gap-2 p-1.5 bg-secondary/20 rounded text-xs font-mono"
            >
              <Zap className="w-3 h-3 text-primary mt-0.5 shrink-0" />
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2">
                  <span className="text-primary">{event.type}</span>
                  <span className="text-muted-foreground">from</span>
                  <span className="text-foreground">{event.sourceWidgetId}</span>
                </div>
                <div className="text-muted-foreground truncate">
                  {JSON.stringify(event.payload)}
                </div>
              </div>
              <span className="text-muted-foreground shrink-0">
                {new Date(event.timestamp).toLocaleTimeString('da-DK', { 
                  hour: '2-digit', 
                  minute: '2-digit', 
                  second: '2-digit' 
                })}
              </span>
            </div>
          ))}
        </div>
      )}

      {recentEvents.length === 0 && (
        <p className="text-xs text-muted-foreground mt-2">
          Ingen events endnu. Interager med widgets for at se kommunikation.
        </p>
      )}
    </div>
  );
};

export default EventLog;
