import { useEffect, useState } from 'react';
import type { FeedItem } from './types';
import { formatRON, timeAgo } from './utils';

interface Props {
  items: FeedItem[];
  onItemClick?: (item: FeedItem) => void;
}

export function ActivityStream({ items, onItemClick }: Props) {
  const [collapsed, setCollapsed] = useState(false);
  const [, setTick] = useState(0);

  // Re-render every 30s to refresh "time ago" labels
  useEffect(() => {
    const id = setInterval(() => setTick((t) => t + 1), 30_000);
    return () => clearInterval(id);
  }, []);

  return (
    <div className={`harta-activity ${collapsed ? 'is-collapsed' : ''}`}>
      <button
        onClick={() => setCollapsed((c) => !c)}
        className="harta-activity-header"
        aria-expanded={!collapsed}
      >
        <span className="harta-activity-pulse" />
        <span className="harta-activity-title">Activitate</span>
        <span className="harta-activity-count">{items.length}</span>
        <svg
          className={`ml-auto transition-transform ${collapsed ? 'rotate-180' : ''}`}
          width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"
        >
          <polyline points="6 9 12 15 18 9" />
        </svg>
      </button>

      {!collapsed && (
        <div className="harta-activity-body">
          {items.length === 0 ? (
            <div className="harta-activity-empty">Niciun anunț recent</div>
          ) : (
            items.map((item, idx) => (
              <button
                key={`${item.type}-${item.id}`}
                onClick={() => onItemClick?.(item)}
                className="harta-activity-row"
                style={{ animationDelay: `${Math.min(idx * 40, 800)}ms` }}
              >
                <span className="harta-activity-dot" data-type={item.type} />
                <div className="min-w-0 flex-1 text-left">
                  <div className="harta-activity-row-title">{item.name}</div>
                  <div className="harta-activity-row-meta">
                    <span className="truncate">{item.authority_name}</span>
                    {item.authority_county && <span className="harta-activity-county">{item.authority_county}</span>}
                  </div>
                </div>
                <div className="text-right shrink-0 ml-2">
                  <div className="harta-activity-row-value tabular-nums">{formatRON(Number(item.value))}</div>
                  <div className="harta-activity-row-time">{timeAgo(item.date)}</div>
                </div>
              </button>
            ))
          )}
        </div>
      )}
    </div>
  );
}
