import React, { useState, useEffect } from 'react';
import { Button, message, Tooltip } from 'antd';
import {
  LikeOutlined,
  HeartOutlined,
  SmileOutlined,
  FrownOutlined,
  ThunderboltOutlined,
  FireOutlined,
  LikeFilled,
  HeartFilled,
  SmileFilled,
  FrownFilled,
  ThunderboltFilled,
  FireFilled,
} from '@ant-design/icons';
import { VideoPlayer, VideoPlayerProps, VideoMetadata } from './VideoPlayer';
import { mediaApi } from '../../lib/media-api';

export interface AdvancedVideoPlayerProps extends VideoPlayerProps {
  showReactions?: boolean;
  showComments?: boolean;
  userId?: string | number;
  onReactionChange?: (reactionType: string, isActive: boolean) => void;
}

interface ReactionType {
  type: string;
  icon: React.ReactNode;
  iconFilled: React.ReactNode;
  color: string;
  label: string;
}

const REACTIONS: ReactionType[] = [
  {
    type: 'like',
    icon: <LikeOutlined />,
    iconFilled: <LikeFilled />,
    color: '#1890ff',
    label: 'Like',
  },
  {
    type: 'love',
    icon: <HeartOutlined />,
    iconFilled: <HeartFilled />,
    color: '#eb2f96',
    label: 'Love',
  },
  {
    type: 'laugh',
    icon: <SmileOutlined />,
    iconFilled: <SmileFilled />,
    color: '#faad14',
    label: 'Laugh',
  },
  {
    type: 'wow',
    icon: <ThunderboltOutlined />,
    iconFilled: <ThunderboltFilled />,
    color: '#52c41a',
    label: 'Wow',
  },
  {
    type: 'sad',
    icon: <FrownOutlined />,
    iconFilled: <FrownFilled />,
    color: '#8c8c8c',
    label: 'Sad',
  },
  {
    type: 'angry',
    icon: <FireOutlined />,
    iconFilled: <FireFilled />,
    color: '#ff4d4f',
    label: 'Angry',
  },
];

interface ReactionCounts {
  [key: string]: number;
}

interface UserReactions {
  [key: string]: boolean;
}

/**
 * Advanced video player with reaction system
 * Includes all standard player features plus reaction buttons and counts
 */
export const AdvancedVideoPlayer: React.FC<AdvancedVideoPlayerProps> = ({
  videoId,
  showReactions = true,
  showComments = false,
  userId,
  onReactionChange,
  ...playerProps
}) => {
  const [reactionCounts, setReactionCounts] = useState<ReactionCounts>({});
  const [userReactions, setUserReactions] = useState<UserReactions>({});
  const [loadingReaction, setLoadingReaction] = useState<string | null>(null);
  const [metadata, setMetadata] = useState<VideoMetadata | null>(null);

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

  const fetchReactions = async () => {
    try {
      // Fetch reaction counts
      const response = await mediaApi.get(`/api/reactions/${videoId}/counts`);
      setReactionCounts(response.data || {});

      // Fetch user's reactions if userId provided
      if (userId) {
        const userResponse = await mediaApi.get(`/api/reactions/${videoId}/user/${userId}`);
        const userReactionData = userResponse.data || [];

        // Convert array to object for easier lookup
        const reactions: UserReactions = {};
        userReactionData.forEach((reaction: { reactionType: string }) => {
          reactions[reaction.reactionType] = true;
        });
        setUserReactions(reactions);
      }
    } catch (error) {
      console.error('Failed to fetch reactions:', error);
    }
  };

  const handleReaction = async (reactionType: string) => {
    if (!userId) {
      message.warning('Please log in to react to videos');
      return;
    }

    setLoadingReaction(reactionType);

    try {
      const isCurrentlyActive = userReactions[reactionType] || false;

      if (isCurrentlyActive) {
        // Remove reaction
        await mediaApi.delete(`/api/reactions/${videoId}`, {
          data: { userId, reactionType },
        });

        setUserReactions((prev) => ({
          ...prev,
          [reactionType]: false,
        }));

        setReactionCounts((prev) => ({
          ...prev,
          [reactionType]: Math.max(0, (prev[reactionType] || 0) - 1),
        }));

        if (onReactionChange) {
          onReactionChange(reactionType, false);
        }
      } else {
        // Add reaction
        await mediaApi.post(`/api/reactions`, {
          videoId,
          userId,
          reactionType,
        });

        setUserReactions((prev) => ({
          ...prev,
          [reactionType]: true,
        }));

        setReactionCounts((prev) => ({
          ...prev,
          [reactionType]: (prev[reactionType] || 0) + 1,
        }));

        if (onReactionChange) {
          onReactionChange(reactionType, true);
        }
      }
    } catch (error) {
      console.error('Failed to update reaction:', error);
      message.error('Failed to update reaction. Please try again.');
    } finally {
      setLoadingReaction(null);
    }
  };

  const handleMetadataLoaded = (meta: VideoMetadata) => {
    setMetadata(meta);
    if (playerProps.onLoadedMetadata) {
      playerProps.onLoadedMetadata(meta);
    }
  };

  return (
    <div style={{ width: playerProps.width || '100%' }}>
      {/* Video Player */}
      <VideoPlayer
        {...playerProps}
        videoId={videoId}
        onLoadedMetadata={handleMetadataLoaded}
      />

      {/* Reactions Bar */}
      {showReactions && (
        <div
          style={{
            marginTop: 12,
            padding: '8px 12px',
            background: '#fafafa',
            borderRadius: 8,
            display: 'flex',
            gap: 8,
            flexWrap: 'wrap',
            alignItems: 'center',
          }}
        >
          {REACTIONS.map((reaction) => {
            const count = reactionCounts[reaction.type] || 0;
            const isActive = userReactions[reaction.type] || false;
            const isLoading = loadingReaction === reaction.type;

            return (
              <Tooltip key={reaction.type} title={reaction.label}>
                <Button
                  type={isActive ? 'primary' : 'default'}
                  icon={isActive ? reaction.iconFilled : reaction.icon}
                  loading={isLoading}
                  disabled={!userId}
                  onClick={() => handleReaction(reaction.type)}
                  style={{
                    borderColor: isActive ? reaction.color : undefined,
                    background: isActive ? reaction.color : undefined,
                    color: isActive ? '#fff' : reaction.color,
                  }}
                >
                  {count > 0 && <span style={{ marginLeft: 4 }}>{count}</span>}
                </Button>
              </Tooltip>
            );
          })}

          {/* Video Info */}
          {metadata && (
            <div
              style={{
                marginLeft: 'auto',
                fontSize: 12,
                color: '#999',
                display: 'flex',
                gap: 12,
              }}
            >
              {metadata.orientation && (
                <span>
                  {metadata.width}×{metadata.height}
                </span>
              )}
              {metadata.durationSeconds && (
                <span>
                  {Math.floor(metadata.durationSeconds / 60)}:
                  {String(metadata.durationSeconds % 60).padStart(2, '0')}
                </span>
              )}
            </div>
          )}
        </div>
      )}

      {/* Comments Section (Future) */}
      {showComments && (
        <div style={{ marginTop: 16, padding: 12, background: '#f5f5f5', borderRadius: 8 }}>
          <p style={{ margin: 0, color: '#999', textAlign: 'center' }}>
            Comments coming soon...
          </p>
        </div>
      )}
    </div>
  );
};

export default AdvancedVideoPlayer;
