import { Activity } from 'lucide-react';
import { useGetXmemTeamActivityQuery } from '../../store';
import type { TeamMemoryEvent } from './types';

const EVENT_TYPE_COLOR: Record<string, string> = {
  task_created: 'text-blue-400',
  task_selected: 'text-yellow-400',
  task_updated: 'text-purple-400',
  task_completed: 'text-green-400',
  context_switch: 'text-orange-400',
  project_created: 'text-cyan-400',
  derived_blocker: 'text-red-400',
};

function formatRelative(ts: string): string {
  const diffMs = Date.now() - new Date(ts).getTime();
  const sec = Math.floor(diffMs / 1000);
  if (sec < 60) return `${sec}s ago`;
  const min = Math.floor(sec / 60);
  if (min < 60) return `${min}m ago`;
  const hr = Math.floor(min / 60);
  if (hr < 24) return `${hr}h ago`;
  return new Date(ts).toLocaleDateString();
}

export function ActivityFeed({ pollInterval = 15000 }: { pollInterval?: number }) {
  const { data, isLoading, isError } = useGetXmemTeamActivityQuery(
    { limit: 25 },
    { pollingInterval: pollInterval, refetchOnFocus: true },
  );

  return (
    <div className="glass-light rounded-xl p-4">
      <h3 className="text-xs font-medium text-surface-400 uppercase tracking-wider mb-3 flex items-center gap-2">
        <Activity className="w-4 h-4 text-blue-400" />
        Team Activity
        {data && (
          <span className="ml-auto px-2 py-0.5 rounded bg-blue-500/20 text-blue-400 text-xs">
            {data.count}
          </span>
        )}
      </h3>

      {isLoading && (
        <p className="text-sm text-surface-500 text-center py-4">Loading…</p>
      )}
      {isError && (
        <p className="text-sm text-red-400 text-center py-4">Failed to load activity</p>
      )}
      {data && data.events.length === 0 && (
        <p className="text-sm text-surface-500 text-center py-4">No team activity yet</p>
      )}

      {data && data.events.length > 0 && (
        <div className="space-y-2 max-h-[400px] overflow-y-auto">
          {data.events.map((event: TeamMemoryEvent, index) => (
            <div
              key={event.eventId}
              className="p-2 rounded-lg bg-surface-800/50 border border-surface-700 animate-slide-up"
              style={{ animationDelay: `${index * 0.02}s`, animationFillMode: 'forwards' }}
            >
              <div className="flex items-center gap-2 mb-1">
                <span
                  className={`text-xs font-mono uppercase tracking-wide ${
                    EVENT_TYPE_COLOR[event.eventType] ?? 'text-surface-400'
                  }`}
                >
                  {event.eventType.replace('_', ' ')}
                </span>
                <span className="text-xs text-surface-500 ml-auto font-mono">
                  {formatRelative(event.timestamp)}
                </span>
              </div>
              <p className="text-sm text-surface-200">{event.summary}</p>
              <p className="text-xs text-surface-500 mt-1">
                <span className="font-mono">{event.agentId}</span>
              </p>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
