'use client';

import type { Doc } from '@spoon/backend/convex/_generated/dataModel.js';

const formatTime = (value: number) =>
  new Intl.DateTimeFormat(undefined, {
    month: 'short',
    day: 'numeric',
    hour: 'numeric',
    minute: '2-digit',
  }).format(value);

export const AgentEventLog = ({
  events,
}: {
  events: Doc<'agentJobEvents'>[];
}) => {
  if (!events.length) {
    return (
      <p className='text-muted-foreground text-sm'>No worker events yet.</p>
    );
  }

  return (
    <div className='divide-border overflow-hidden rounded-md border'>
      {events.map((event) => (
        <div key={event._id} className='grid gap-1 border-b p-3 text-sm'>
          <div className='flex flex-wrap items-center gap-2'>
            <span className='font-mono text-xs uppercase'>{event.phase}</span>
            <span className='text-muted-foreground text-xs'>
              {formatTime(event.createdAt)}
            </span>
            <span className='text-muted-foreground text-xs capitalize'>
              {event.level}
            </span>
          </div>
          <p className='whitespace-pre-wrap'>{event.message}</p>
          {event.metadata ? (
            <pre className='bg-muted overflow-auto rounded p-2 text-xs'>
              {event.metadata}
            </pre>
          ) : null}
        </div>
      ))}
    </div>
  );
};
