/**
 * MessageReactions Component
 * Displays and manages emoji reactions on messages
 */

import React, { useState } from 'react';
import ReactionPicker from './ReactionPicker';
import './MessageReactions.css';

export default function MessageReactions({
  reactions = [],
  onAddReaction,
  onRemoveReaction,
  currentUserId,
  messageId,
}) {
  const [showPicker, setShowPicker] = useState(false);

  const handleReactionClick = (emoji) => {
    // Check if user already reacted with this emoji
    const existingReaction = reactions.find((r) => r.emoji === emoji);

    if (existingReaction?.users?.includes(currentUserId)) {
      // Remove reaction
      onRemoveReaction?.(messageId, emoji, currentUserId);
    } else {
      // Add reaction
      onAddReaction?.(messageId, emoji, currentUserId);
    }
  };

  const handleAddReaction = (emoji) => {
    onAddReaction?.(messageId, emoji, currentUserId);
  };

  return (
    <div className="message-reactions-container">
      <div className="reactions-list">
        {reactions.map((reaction, idx) => {
          const userReacted = reaction.users?.includes(currentUserId);
          return (
            <button
              key={idx}
              className={`reaction-button ${userReacted ? 'user-reacted' : ''}`}
              onClick={() => handleReactionClick(reaction.emoji)}
              title={reaction.users?.join(', ') || 'Add reaction'}
            >
              <span className="reaction-emoji">{reaction.emoji}</span>
              {reaction.users?.length > 0 && (
                <span className="reaction-count">{reaction.users.length}</span>
              )}
            </button>
          );
        })}
      </div>

      <div className="add-reaction-container">
        {showPicker && (
          <ReactionPicker
            onReactionSelect={handleAddReaction}
            onClose={() => setShowPicker(false)}
          />
        )}
        <button
          className="btn-add-reaction"
          onClick={() => setShowPicker(!showPicker)}
          title="Add reaction"
        >
          ➕
        </button>
      </div>
    </div>
  );
}
