import { useState } from 'react';
import { api } from '../lib/api.ts';

interface Reaction {
  emoji: string;
  count: number;
  users: string[];
  reacted: boolean;
}

interface ReactionBarProps {
  messageId: string;
  reactions: Reaction[];
  onRefresh: () => void;
}

export function ReactionBar({ messageId, reactions, onRefresh }: ReactionBarProps) {
  const [loading, setLoading] = useState(false);

  const toggleReaction = async (emoji: string) => {
    if (loading) return;
    setLoading(true);
    try {
      const existing = reactions.find(r => r.emoji === emoji);
      if (existing?.reacted) {
        await api.delete(`/messages/${messageId}/reactions/${encodeURIComponent(emoji)}`);
      } else {
        await api.post(`/messages/${messageId}/reactions`, { emoji });
      }
      onRefresh();
    } catch (error) {
      console.error('Failed to toggle reaction:', error);
    } finally {
      setLoading(false);
    }
  };

  if (reactions.length === 0) return null;

  return (
    <div className="flex flex-wrap gap-1 mt-1">
      {reactions.map((reaction) => (
        <button
          key={reaction.emoji}
          onClick={() => toggleReaction(reaction.emoji)}
          disabled={loading}
          className={`
            px-1.5 py-0.5 text-xs font-mono border rounded-sm
            transition-colors duration-100
            ${reaction.reacted
              ? 'border-gb-orange bg-gb-bg-t text-gb-orange'
              : 'border-gb-bg-t bg-gb-bg-s text-gb-fg-f hover:border-gb-fg-f'
            }
          `}
          title={reaction.users.join(', ')}
        >
          {reaction.emoji} {reaction.count}
        </button>
      ))}
    </div>
  );
}
