import React from 'react';
import { useShadeEvents, type ShadeEventEnvelope } from '../useShadeEvents.js';
import { useShadeContext } from '../ShadeProvider.js';
import { WidgetShell, ConnectionStatus, formatRelative } from './shared.js';

/**
 * RecentActivity — live feed of all events flowing through the system.
 */
export function RecentActivity({ limit = 50 }: { limit?: number }): React.ReactElement {
  const { events, connected } = useShadeEvents(limit);
  const { theme } = useShadeContext();

  // Show newest first
  const sorted = [...events].reverse();

  return (
    <WidgetShell title="Recent activity" status={<ConnectionStatus connected={connected} />}>
      {sorted.length === 0 ? (
        <div style={{ color: theme.textMuted, fontSize: 13, padding: '16px 0', textAlign: 'center' }}>
          {connected ? 'Waiting for events…' : 'Not connected'}
        </div>
      ) : (
        <div
          style={{
            display: 'flex',
            flexDirection: 'column',
            gap: 4,
            maxHeight: 320,
            overflowY: 'auto',
          }}
        >
          {sorted.map((e) => (
            <EventRow key={`${e.source}-${e.seq}`} event={e} />
          ))}
        </div>
      )}
    </WidgetShell>
  );
}

function EventRow({ event }: { event: ShadeEventEnvelope }): React.ReactElement {
  const { theme } = useShadeContext();
  const color = colorForEvent(event.name, theme);
  const summary = summaryForEvent(event);

  return (
    <div
      style={{
        display: 'grid',
        gridTemplateColumns: '60px 1fr auto',
        gap: 8,
        alignItems: 'center',
        padding: '6px 8px',
        background: theme.bg,
        borderRadius: 4,
        fontSize: 11,
      }}
    >
      <span style={{ color: theme.textDim, fontFamily: theme.fontMono, fontSize: 10 }}>
        {formatRelative(event.timestamp)}
      </span>
      <span style={{ color, fontFamily: theme.fontMono, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
        <strong>{event.name}</strong> <span style={{ color: theme.textMuted }}>{summary}</span>
      </span>
      <span
        style={{
          fontSize: 9,
          color: theme.textDim,
          textTransform: 'uppercase',
          letterSpacing: '0.05em',
          padding: '1px 4px',
          background: theme.bgElevated,
          borderRadius: 2,
        }}
      >
        {event.source}
      </span>
    </div>
  );
}

function colorForEvent(name: string, theme: any): string {
  if (name.startsWith('message.encrypted')) return theme.accent;
  if (name.startsWith('message.decrypted')) return theme.success;
  if (name.startsWith('ratchet')) return theme.accent;
  if (name.startsWith('identity')) return theme.warning;
  if (name.startsWith('trust')) return theme.warning;
  if (name.startsWith('server.rate_limited')) return theme.danger;
  return theme.textMuted;
}

function summaryForEvent(e: ShadeEventEnvelope): string {
  const d = e.data;
  switch (e.name) {
    case 'identity.initialized':
      return `reg ${d.registrationId}`;
    case 'identity.rotated':
      return 'new identity';
    case 'session.created':
      return `${d.address} (${d.remoteIdentityKeyHash})`;
    case 'session.removed':
      return `${d.address}`;
    case 'message.encrypted':
      return `${d.address} #${d.counter} (${d.ciphertextSize}b)`;
    case 'message.decrypted':
      return `${d.address} #${d.counter} (${d.plaintextSize}b)`;
    case 'ratchet.dh_step':
      return `${d.address}`;
    case 'prekey.generated':
      return `+${d.count} (now ${d.totalAfter})`;
    case 'prekey.consumed':
      return `id ${d.keyId}`;
    case 'signed_prekey.rotated':
      return `${d.oldKeyId} → ${d.newKeyId}`;
    case 'trust.pinned':
      return `${d.address} (${d.identityKeyHash})`;
    case 'trust.changed':
      return `${d.address}`;
    case 'server.identity_registered':
      return `${d.address}`;
    case 'server.bundle_fetched':
      return `${d.address}${d.hadOneTimePreKey ? ' (with OTPK)' : ''}`;
    case 'server.prekeys_replenished':
      return `${d.address} +${d.count} (now ${d.totalAfter})`;
    case 'server.identity_deleted':
      return `${d.address}`;
    case 'server.rate_limited':
      return `${d.route}`;
    default:
      return '';
  }
}
