'use client';

import { useMemo, useState } from 'react';
import { Search, Play, ShieldCheck } from 'lucide-react';
import { formatRelativeTime, humanizeRunStatus } from './format-helpers';

type ActivityItem = {
  id: string;
  kind: 'execution' | 'approval';
  status: string;
  title: string;
  risk?: string | null;
  at: string | null;
};

function statusTone(status: string): 'ok' | 'warn' | 'bad' | 'neutral' {
  const s = String(status || '').toLowerCase();
  if (s.includes('complete') || s.includes('ok') || s === 'approved') return 'ok';
  if (s.includes('wait') || s.includes('approval') || s === 'pending' || s.includes('queue')) return 'warn';
  if (s.includes('fail') || s.includes('error') || s.includes('denied') || s.includes('block')) return 'bad';
  return 'neutral';
}

function statusLabel(item: ActivityItem): string {
  if (item.kind === 'approval') {
    const s = item.status.toLowerCase();
    if (s === 'used') return 'Approved';
    return item.status ? item.status.charAt(0).toUpperCase() + item.status.slice(1) : 'Pending';
  }
  return humanizeRunStatus(item.status);
}

export function AgentActivityFeed({ items }: { items: ActivityItem[] }) {
  const [query, setQuery] = useState('');

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return items;
    return items.filter((item) =>
      item.title.toLowerCase().includes(q)
      || item.status.toLowerCase().includes(q)
      || item.kind.includes(q)
    );
  }, [items, query]);

  return (
    <section className="ad-activity">
      <div className="ad-activity-head">
        <span className="ad-activity-title">Recent activity</span>
        {items.length ? (
          <label className="ad-activity-search">
            <Search size={13} aria-hidden />
            <input
              type="text"
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              placeholder="Search runs & approvals"
              aria-label="Search activity"
            />
          </label>
        ) : null}
      </div>

      {filtered.length ? (
        <ul className="ad-feed">
          {filtered.map((item) => {
            const tone = statusTone(item.status);
            return (
              <li key={item.id} className="ad-feed-row">
                <span className={`ad-feed-icon kind-${item.kind}`} aria-hidden>
                  {item.kind === 'approval' ? <ShieldCheck size={14} /> : <Play size={13} />}
                </span>
                <span className="ad-feed-main">
                  <span className="ad-feed-title">{item.title}</span>
                  <span className="ad-feed-meta">
                    {item.kind === 'approval' ? 'Approval' : 'Run'}
                    {item.risk && item.risk !== 'low' ? ` · ${item.risk} risk` : ''}
                  </span>
                </span>
                <span className={`ad-feed-status tone-${tone}`}>{statusLabel(item)}</span>
                <span className="ad-feed-when">{formatRelativeTime(item.at) || '—'}</span>
              </li>
            );
          })}
        </ul>
      ) : items.length ? (
        <div className="ad-feed-empty">No activity matches “{query}”.</div>
      ) : (
        <div className="ad-feed-empty">
          <strong>Nothing has happened yet.</strong>
          <span>When this agent runs or asks for approval, you’ll see it here.</span>
        </div>
      )}
    </section>
  );
}
