// Event card component displaying a single event

import React from 'react';
import type { Event } from '../types';

interface EventCardProps {
  event: Event;
}

const formatTimestamp = (timestamp: number): string => {
  const date = new Date(timestamp * 1000);
  return date.toLocaleTimeString('en-US', {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    fractionalSecondDigits: 3,
    hour12: false,
  });
};

const getEventColor = (eventType: string): string => {
  switch (eventType) {
    case 'PreToolUse':
      return 'cyan';
    case 'PostToolUse':
      return 'green';
    case 'SessionStart':
      return 'blue';
    case 'SessionEnd':
      return 'blue';
    case 'SubagentStop':
      return 'magenta';
    case 'UserPromptSubmit':
      return 'yellow';
    default:
      return 'gray';
  }
};

const getSuccessIcon = (success?: boolean | null): string => {
  if (success === null || success === undefined) return '▶';
  return success ? '✓' : '✗';
};

const formatToolInput = (toolInput: any): string => {
  if (!toolInput) return '';
  if (typeof toolInput === 'string') return toolInput;
  if (typeof toolInput === 'object') {
    // For Bash commands, show the command
    if (toolInput.command) return `$ ${toolInput.command}`;
    return JSON.stringify(toolInput, null, 2);
  }
  return String(toolInput);
};

export const EventCard: React.FC<EventCardProps> = ({ event }) => {
  const color = getEventColor(event.event_type);
  const successIcon = getSuccessIcon(event.success);
  const formattedInput = formatToolInput(event.tool_input);

  return (
    <div className={`event-card ${color}-border`}>
      <div className="event-header">
        <span className={`event-type ${color}`}>{event.event_type}</span>
        {event.tool_name && <span className="event-tool">{event.tool_name}</span>}
        <span className="event-timestamp">{formatTimestamp(event.timestamp)}</span>
      </div>

      <div className="event-body">
        <div className="event-status">
          <span className={`status-icon ${event.success ? 'success' : event.success === false ? 'error' : 'pending'}`}>
            {successIcon}
          </span>
        </div>

        {formattedInput && (
          <div className="event-command">
            <code>{formattedInput}</code>
          </div>
        )}

        {event.description && (
          <div className="event-description">
            {event.description}
          </div>
        )}
      </div>
    </div>
  );
};

export default EventCard;
