import { useState, useEffect } from 'react';
import { theme } from 'antd';

interface Reaction {
  id: number;
  reactionType: string;
  emoji: string;
  videoTimestamp: number;
  createdAt: string;
}

interface ProgressBarMarkersProps {
  videoId: number;
  durationSeconds: number;
  playerRef?: React.RefObject<HTMLVideoElement>; // Optional, for future enhancements
}

// Color mapping for reaction types
const REACTION_COLORS: Record<string, string> = {
  like: '#1890ff', // Blue
  love: '#f5222d', // Red
  laugh: '#faad14', // Orange
  wow: '#722ed1', // Purple
  sad: '#13c2c2', // Cyan
  angry: '#ff4d4f', // Dark red
};

export default function ProgressBarMarkers({
  videoId,
  durationSeconds,
}: ProgressBarMarkersProps) {
  const { token } = theme.useToken();
  const [reactions, setReactions] = useState<Reaction[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchReactions();
  }, [videoId]);

  const fetchReactions = async () => {
    try {
      setLoading(true);

      // Use relative URL to go through nginx proxy
      const response = await fetch(`/media/reactions/${videoId}/chat?limit=500`);

      if (!response.ok) {
        throw new Error('Failed to fetch reactions');
      }

      const data = await response.json();
      setReactions(data.reactions || []);
    } catch (error) {
      console.error('Failed to fetch reactions:', error);
    } finally {
      setLoading(false);
    }
  };

  if (loading || reactions.length === 0 || !durationSeconds) {
    return null;
  }

  // Calculate marker positions as percentages
  const markers = reactions.map((reaction) => ({
    ...reaction,
    position: (reaction.videoTimestamp / durationSeconds) * 100,
    color: REACTION_COLORS[reaction.reactionType] || token.colorPrimary,
  }));

  // Group markers that are very close together (within 1% of video duration)
  const groupedMarkers: typeof markers = [];
  const GROUPING_THRESHOLD = 1; // 1% of video duration

  markers.forEach((marker) => {
    const existingGroup = groupedMarkers.find(
      (m) => Math.abs(m.position - marker.position) < GROUPING_THRESHOLD
    );

    if (existingGroup) {
      // Use the most recent reaction color
      if (new Date(marker.createdAt) > new Date(existingGroup.createdAt)) {
        existingGroup.color = marker.color;
      }
    } else {
      groupedMarkers.push({ ...marker });
    }
  });

  return (
    <div
      style={{
        position: 'absolute',
        bottom: 45, // Position above video controls
        left: 0,
        right: 0,
        height: 8,
        pointerEvents: 'none',
        zIndex: 5,
      }}
    >
      {groupedMarkers.map((marker, index) => (
        <div
          key={`${marker.id}-${index}`}
          style={{
            position: 'absolute',
            left: `${marker.position}%`,
            top: 0,
            width: 4,
            height: 8,
            background: marker.color,
            borderRadius: 2,
            boxShadow: '0 1px 3px rgba(0, 0, 0, 0.5)',
            transform: 'translateX(-50%)',
            transition: 'transform 0.2s',
          }}
          title={`${marker.emoji} at ${Math.floor(marker.videoTimestamp / 60)}:${String(
            marker.videoTimestamp % 60
          ).padStart(2, '0')}`}
          onMouseEnter={(e) => {
            e.currentTarget.style.transform = 'translateX(-50%) scale(1.5)';
          }}
          onMouseLeave={(e) => {
            e.currentTarget.style.transform = 'translateX(-50%) scale(1)';
          }}
        />
      ))}
    </div>
  );
}
