import { useState } from 'react';
import { Button, Popover, Space, Tooltip, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { api } from '@/lib/api';
import type { SharedViewReactionGroup } from '@/types/api';

const EMOJI_PALETTE = ['👍', '❤️', '🎉', '😄', '🤔', '👀', '🔥', '⭐', '💪', '📅'];

interface CalendarReactionsProps {
  viewId: string;
  itemId: string;
  reactions: SharedViewReactionGroup[];
  currentUserId: string;
  onUpdate: () => void;
}

export default function CalendarReactions({
  viewId,
  itemId,
  reactions,
  currentUserId,
  onUpdate,
}: CalendarReactionsProps) {
  const [paletteOpen, setPaletteOpen] = useState(false);

  const toggleReaction = async (emoji: string) => {
    try {
      await api.post(`/calendar/shared/${viewId}/reactions`, { itemId, emoji });
      onUpdate();
    } catch {
      message.error('Failed to update reaction');
    }
    setPaletteOpen(false);
  };

  return (
    <Space size={4} wrap style={{ marginTop: 4 }}>
      {reactions.map((r) => {
        const hasReacted = r.users.some((u) => u.id === currentUserId);
        const tooltip = r.users.map((u) => u.name || 'Someone').join(', ');
        return (
          <Tooltip key={r.emoji} title={tooltip}>
            <Button
              size="small"
              type={hasReacted ? 'primary' : 'default'}
              style={{
                fontSize: 13,
                padding: '0 6px',
                height: 24,
                borderRadius: 12,
                opacity: hasReacted ? 1 : 0.7,
              }}
              onClick={() => toggleReaction(r.emoji)}
            >
              {r.emoji} {r.count}
            </Button>
          </Tooltip>
        );
      })}

      <Popover
        open={paletteOpen}
        onOpenChange={setPaletteOpen}
        trigger="click"
        placement="bottom"
        content={
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4, maxWidth: 200 }}>
            {EMOJI_PALETTE.map((emoji) => (
              <Button
                key={emoji}
                size="small"
                type="text"
                style={{ fontSize: 18, width: 36, height: 36 }}
                onClick={() => toggleReaction(emoji)}
              >
                {emoji}
              </Button>
            ))}
          </div>
        }
      >
        <Button
          size="small"
          type="text"
          icon={<PlusOutlined />}
          style={{
            fontSize: 12,
            height: 24,
            width: 24,
            borderRadius: 12,
            opacity: 0.5,
          }}
        />
      </Popover>
    </Space>
  );
}
