import { useState } from 'react';
import { Space, Button, message, theme } from 'antd';
import { mediaPublicApi } from '@/lib/media-public-api';
import { useAuthStore } from '@/stores/auth.store';
import { hexToRgba } from '@/utils/color';
import axios from 'axios';

interface ReactionButtonsProps {
  videoId: number;
  currentTime: number;
}

// Standard emoji reactions
const REACTIONS = [
  { emoji: '👍', name: 'like', label: 'Like' },
  { emoji: '❤️', name: 'love', label: 'Love' },
  { emoji: '😂', name: 'laugh', label: 'Laugh' },
  { emoji: '😮', name: 'wow', label: 'Wow' },
  { emoji: '😢', name: 'sad', label: 'Sad' },
  { emoji: '😡', name: 'angry', label: 'Angry' },
];

interface FloatingEmoji {
  id: number;
  emoji: string;
  x: number;
}

export default function ReactionButtons({ videoId, currentTime }: ReactionButtonsProps) {
  const { token } = theme.useToken();
  const isAuthenticated = useAuthStore((s) => s.isAuthenticated);
  const [floatingEmojis, setFloatingEmojis] = useState<FloatingEmoji[]>([]);
  const [loading, setLoading] = useState(false);
  const hoverBg = hexToRgba(token.colorPrimary, 0.1);

  const handleReaction = async (reactionType: string, emoji: string) => {
    // Check if user is logged in
    if (!isAuthenticated) {
      message.warning('Please log in to add reactions');
      return;
    }

    try {
      setLoading(true);

      await mediaPublicApi.post('/reactions', {
        mediaId: videoId,
        reactionType,
        videoTimestamp: Math.floor(currentTime),
      });

      // Add floating emoji animation
      const newEmoji: FloatingEmoji = {
        id: Date.now(),
        emoji,
        x: Math.random() * 80 + 10, // Random x position (10-90%)
      };

      setFloatingEmojis((prev) => [...prev, newEmoji]);

      // Remove emoji after animation completes (2 seconds)
      setTimeout(() => {
        setFloatingEmojis((prev) => prev.filter((e) => e.id !== newEmoji.id));
      }, 2000);

      message.success(`${emoji} reaction added!`);
    } catch (error: unknown) {
      if (axios.isAxiosError(error) && error.response?.status === 401) {
        message.error('Please log in to add reactions');
      } else {
        message.error('Failed to add reaction');
      }
      console.error('Failed to add reaction:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ position: 'relative' }}>
      {/* Reaction buttons */}
      <Space size={12} wrap>
        {REACTIONS.map((reaction) => (
          <Button
            key={reaction.name}
            type="text"
            size="large"
            disabled={loading}
            onClick={() => handleReaction(reaction.name, reaction.emoji)}
            style={{
              fontSize: 24,
              padding: '4px 12px',
              height: 'auto',
              borderRadius: 8,
              transition: 'all 0.2s ease',
            }}
            onMouseEnter={(e) => {
              e.currentTarget.style.transform = 'scale(1.2)';
              e.currentTarget.style.background = hoverBg;
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.transform = 'scale(1)';
              e.currentTarget.style.background = 'transparent';
            }}
            title={reaction.label}
          >
            {reaction.emoji}
          </Button>
        ))}
      </Space>

      {/* Floating emojis */}
      {floatingEmojis.map((floatingEmoji) => (
        <div
          key={floatingEmoji.id}
          style={{
            position: 'fixed',
            left: `${floatingEmoji.x}%`,
            bottom: '20%',
            fontSize: 48,
            pointerEvents: 'none',
            animation: 'float-up 2s ease-out forwards',
            zIndex: 1000,
          }}
        >
          {floatingEmoji.emoji}
        </div>
      ))}

      {/* CSS Animation */}
      <style>{`
        @keyframes float-up {
          0% {
            transform: translateY(0) scale(1);
            opacity: 1;
          }
          50% {
            transform: translateY(-100px) scale(1.2);
            opacity: 1;
          }
          100% {
            transform: translateY(-200px) scale(0.8);
            opacity: 0;
          }
        }
      `}</style>
    </div>
  );
}
