"use client";

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

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

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

const COMMON_EMOJIS = [
  "👍",
  "❤️",
  "😀",
  "🎉",
  "👀",
  "🔥",
  "👏",
  "💯",
  "😅",
  "🙌",
  "✅",
  "❓",
];

function EmojiPicker({
  onPick,
  disabled,
}: {
  onPick: (emoji: string) => void;
  disabled: boolean;
}) {
  return (
    <div className="absolute bottom-full mb-1 left-0 bg-white rounded-lg shadow-lg border border-gray-200 p-2 z-50">
      <div className="grid grid-cols-6 gap-1">
        {COMMON_EMOJIS.map((emoji) => (
          <button
            key={emoji}
            onClick={() => onPick(emoji)}
            disabled={disabled}
            className="w-7 h-7 flex items-center justify-center rounded hover:bg-gray-100 text-lg transition-colors"
          >
            {emoji}
          </button>
        ))}
      </div>
    </div>
  );
}

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

  // 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 = reactions.find((r) => r.emoji === emoji);
    const hasReacted = existing ? hasUserReacted(existing) : false;

    setIsLoading(true);
    try {
      if (hasReacted) {
        await removeReaction(messageId, emoji);
      } else {
        await addReaction(messageId, emoji);
      }
      onReactionsChange?.();
    } catch (err) {
      console.error("Failed to toggle reaction:", err);
    } finally {
      setIsLoading(false);
      setShowPicker(false);
    }
  };

  // No reactions yet: show just the smile button
  if (reactions.length === 0 && !showPicker) {
    return (
      <div ref={pickerRef} className="relative inline-flex items-center">
        <button
          onClick={() => setShowPicker((v) => !v)}
          disabled={isLoading}
          className="p-1 rounded-md hover:bg-gray-200 text-gray-400 transition-colors"
          title="Add reaction"
        >
          <Smile size={16} />
        </button>
      </div>
    );
  }

  return (
    <div ref={pickerRef} className="relative inline-flex items-center gap-1 flex-wrap">
      {reactions.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-1.5 py-0.5 rounded-md text-xs border transition-colors ${
              hasReacted
                ? "bg-slack-purple/10 border-slack-purple/30 text-slack-purple"
                : "bg-gray-50 border-gray-200 text-gray-600 hover:bg-gray-100"
            }`}
            title={hasReacted ? "Remove reaction" : "Add reaction"}
          >
            <span className="text-sm">{reaction.emoji}</span>
            <span className="font-medium">{reaction.count}</span>
          </button>
        );
      })}

      {/* Add reaction button */}
      <button
        onClick={() => setShowPicker((v) => !v)}
        disabled={isLoading}
        className="p-1 rounded-md hover:bg-gray-200 text-gray-400 transition-colors"
        title="Add reaction"
      >
        <Plus size={14} />
      </button>

      {showPicker && (
        <EmojiPicker onPick={handleToggleReaction} disabled={isLoading} />
      )}
    </div>
  );
}