"use client";

import { useState, useRef, useEffect } from "react";
import { addReaction, removeReaction } from "@/lib/api";
import { EmojiPicker } from "@/components/common/EmojiPicker";
import { Plus } from "lucide-react";

interface ReactionBarProps {
  messageId: string;
  reactions: ReactionData[];
  currentUserId?: string;
  onReactionsChange?: () => void;
}

interface ReactionData {
  emoji: string;
  count: number;
  userIds?: string[];
}

// Quick reaction emojis (Slack style)
const QUICK_EMOJIS = ["👍", "❤️", "👏", "😄", "🚀"];

export function ReactionBar({
  messageId,
  reactions,
  currentUserId,
  onReactionsChange,
}: ReactionBarProps) {
  const [showPicker, setShowPicker] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [localReactions, setLocalReactions] = useState<ReactionData[]>(reactions);
  const pickerRef = useRef<HTMLDivElement>(null);

  // Sync when parent reactions change
  useEffect(() => {
    setLocalReactions(reactions);
  }, [reactions]);

  // Close picker on outside click
  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (pickerRef.current && !pickerRef.current.contains(e.target as Node)) {
        setShowPicker(false);
      }
    };
    if (showPicker) {
      document.addEventListener("mousedown", handleClickOutside);
    }
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, [showPicker]);

  const hasUserReacted = (reaction: ReactionData): boolean => {
    if (!currentUserId) return false;
    return reaction.userIds?.includes(currentUserId) ?? false;
  };

  const handleToggleReaction = async (emoji: string) => {
    const existing = localReactions.find((r) => r.emoji === emoji);
    const hasReacted = existing ? hasUserReacted(existing) : false;

    setIsLoading(true);
    try {
      if (hasReacted) {
        await removeReaction(messageId, emoji);
        setLocalReactions((prev) =>
          prev
            .map((r) =>
              r.emoji === emoji
                ? {
                    ...r,
                    count: Math.max(0, r.count - 1),
                    userIds: r.userIds?.filter((u) => u !== currentUserId),
                  }
                : r
            )
            .filter((r) => r.count > 0)
        );
      } else {
        await addReaction(messageId, emoji);
        setLocalReactions((prev) => {
          const found = prev.find((r) => r.emoji === emoji);
          if (found) {
            return prev.map((r) =>
              r.emoji === emoji
                ? {
                    ...r,
                    count: r.count + 1,
                    userIds: [...(r.userIds || []), currentUserId || ""],
                  }
                : r
            );
          }
          return [
            ...prev,
            { emoji, count: 1, userIds: [currentUserId || ""] },
          ];
        });
      }
      onReactionsChange?.();
    } catch (err) {
      console.error("Failed to toggle reaction:", err);
    } finally {
      setIsLoading(false);
      setShowPicker(false);
    }
  };

  return (
    <div className="flex items-center gap-1 flex-wrap">
      {/* Existing reaction pills */}
      {localReactions.map((reaction) => {
        const hasReacted = hasUserReacted(reaction);
        return (
          <button
            key={reaction.emoji}
            onClick={() => handleToggleReaction(reaction.emoji)}
            disabled={isLoading}
            className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs border transition-all ${
              hasReacted
                ? "bg-slack-purple/10 border-slack-purple/40 text-slack-purple"
                : "bg-gray-50 border-gray-200 text-gray-600 hover:bg-gray-100"
            }`}
            title={hasReacted ? "Click to remove reaction" : "Click to react"}
          >
            <span className="text-sm">{reaction.emoji}</span>
            <span className="font-semibold">{reaction.count}</span>
          </button>
        );
      })}

      {/* Quick emoji bar - Slack style pills */}
      <div
        ref={pickerRef}
        className="relative inline-flex items-center gap-0.5 bg-white rounded-lg border border-gray-200 shadow-sm px-1 py-0.5"
      >
        {QUICK_EMOJIS.map((emoji) => (
          <button
            key={emoji}
            onClick={() => handleToggleReaction(emoji)}
            disabled={isLoading}
            className="w-6 h-6 flex items-center justify-center rounded hover:bg-gray-100 text-sm transition-colors"
            title={`React with ${emoji}`}
          >
            {emoji}
          </button>
        ))}

        {/* + button for full emoji picker */}
        <button
          onClick={() => setShowPicker((v) => !v)}
          disabled={isLoading}
          className="w-6 h-6 flex items-center justify-center rounded hover:bg-gray-100 text-gray-400 transition-colors"
          title="More emojis"
        >
          <Plus size={14} />
        </button>

        {/* Full emoji picker popup */}
        {showPicker && (
          <div className="absolute bottom-full mb-2 right-0 z-50">
            <EmojiPicker
              onSelect={(emoji) => handleToggleReaction(emoji)}
              onClose={() => setShowPicker(false)}
            />
          </div>
        )}
      </div>
    </div>
  );
}