import { useCallback } from 'react';
import { api, type FeedMessage } from '../api';
import { usePolling } from '../hooks/usePolling';
import { SourceBadge, TypeBadge } from './Badges';

interface Props {
  org?: string;
}

export function LiveFeed({ org }: Props) {
  const fetcher = useCallback(() => api.feed({ org, limit: 30 }), [org]);
  const { data, error, loading } = usePolling<FeedMessage[]>(fetcher, 2000);

  return (
    <div className="bg-surface-raised border border-border rounded-lg overflow-hidden">
      <div className="px-4 py-3 border-b border-border flex items-center justify-between">
        <h2 className="text-sm font-semibold text-text-primary">Live Feed</h2>
        <span className="text-xs text-text-muted">
          {loading ? 'loading...' : error ? 'error' : `${data?.length ?? 0} messages`}
        </span>
      </div>
      <div className="max-h-[500px] overflow-y-auto divide-y divide-border-subtle">
        {data?.map((m) => (
          <div key={m.id} className="px-4 py-2.5 hover:bg-surface-overlay transition-colors">
            <div className="flex items-start gap-3">
              <div className="flex items-center gap-2 shrink-0 w-44">
                <SourceBadge source={m.source} />
                <TypeBadge type={m.msg_type} />
              </div>
              <p className="text-sm text-text-secondary truncate flex-1">
                {m.content_preview || <span className="text-text-muted italic">no content</span>}
              </p>
              <span className="text-xs text-text-muted shrink-0 tabular-nums">
                {m.timestamp ? new Date(m.timestamp).toLocaleTimeString() : ''}
              </span>
            </div>
            <div className="mt-0.5 ml-44 pl-3 flex items-center gap-3 text-[10px] text-text-muted">
              {m.device_name && <span title={m.device_name}>{m.device_name.length > 20 ? m.device_name.slice(0, 20) + '…' : m.device_name}</span>}
              <span className="font-mono">{m.session_id.slice(0, 8)}</span>
            </div>
          </div>
        ))}
        {data?.length === 0 && (
          <div className="px-4 py-8 text-center text-text-muted text-sm">
            No messages yet. Start the daemon or POST to /ingest.
          </div>
        )}
      </div>
    </div>
  );
}
