import { useState, useRef, useEffect } from 'react';
import { Card, Tag, Space, Typography, theme, Modal, Grid } from 'antd';
import { PlayCircleOutlined, LikeOutlined, EyeOutlined, CommentOutlined, LockOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useExpandedVideo } from '@/contexts/ExpandedVideoContext';
import { hexToRgba } from '@/utils/color';

interface PublicVideoCardProps {
  video: {
    id: number;
    filename: string;
    title: string | null;
    category: string | null;
    durationSeconds: number | null;
    quality: string | null;
    orientation: string | null;
    thumbnailPath: string | null;
    viewCount: number;
    upvoteCount: number;
    commentCount: number;
    isLocked: boolean;
    createdAt: string;
  };
}

export default function PublicVideoCard({ video }: PublicVideoCardProps) {
  const { token } = theme.useToken();
  const navigate = useNavigate();
  const { expandVideo } = useExpandedVideo();
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;

  // Hover video preview state
  const [hovering, setHovering] = useState(false);
  const [thumbnailError, setThumbnailError] = useState(false);
  const hoverTimeout = useRef<number | null>(null);
  const videoRef = useRef<HTMLVideoElement | null>(null);

  const formatDuration = (seconds: number | null) => {
    if (!seconds) return '\u2014';
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins}:${secs.toString().padStart(2, '0')}`;
  };

  const formatCount = (count: number | undefined | null) => {
    if (!count && count !== 0) return '0';
    if (count >= 1000000) {
      return `${(count / 1000000).toFixed(1)}M`;
    }
    if (count >= 1000) {
      return `${(count / 1000).toFixed(1)}K`;
    }
    return count.toString();
  };

  // Use video title if available, fall back to filename without extension
  const title = video.title || video.filename.replace(/\.[^/.]+$/, '');

  // Cleanup hover timeout on unmount
  useEffect(() => {
    return () => {
      if (hoverTimeout.current) {
        clearTimeout(hoverTimeout.current);
      }
    };
  }, []);

  // Handle mouse enter with debounce to prevent connection saturation
  const handleMouseEnter = (e: React.MouseEvent<HTMLDivElement>) => {
    // Apply card hover effects
    const card = e.currentTarget;
    card.style.boxShadow = `0 0 0 2px ${token.colorPrimary}`;
    card.style.transform = 'translateY(-2px)';

    // Debounce: only load video if user hovers for 200ms
    // Prevents connection saturation when quickly scanning the grid
    hoverTimeout.current = setTimeout(() => {
      setHovering(true);
    }, 200);
  };

  // Handle mouse leave - cancel pending video load
  const handleMouseLeave = (e: React.MouseEvent<HTMLDivElement>) => {
    // Remove card hover effects
    const card = e.currentTarget;
    card.style.boxShadow = 'none';
    card.style.transform = 'translateY(0)';

    // Cancel pending hover timer
    if (hoverTimeout.current) {
      clearTimeout(hoverTimeout.current);
      hoverTimeout.current = null;
    }

    // Abort any in-flight video load to free the connection slot
    const video = videoRef.current;
    if (video) {
      video.pause();
      video.removeAttribute('src');
      video.load();
    }

    setHovering(false);
  };

  const handleCardClick = () => {
    if (video.isLocked) {
      // Show login modal for locked content
      Modal.confirm({
        title: 'Login Required',
        content: 'This video is locked. Please log in to watch.',
        okText: 'Go to Login',
        cancelText: 'Cancel',
        onOk: () => {
          navigate('/login', { state: { from: `/gallery/watch/${video.id}` } });
        },
      });
    } else {
      expandVideo(video.id, video);
    }
  };

  return (
    <Card
      hoverable
      style={{
        borderRadius: 12,
        overflow: 'hidden',
        border: `1px solid ${token.colorBorderSecondary}`,
        transition: 'all 0.2s ease',
        cursor: 'pointer',
      }}
      styles={{ body: { padding: 12 } }}
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}
      onClick={handleCardClick}
      cover={
        <div
          style={{
            position: 'relative',
            paddingTop: video.orientation === 'V' ? '177.78%' : '56.25%', // 9:16 or 16:9
            background: '#000',
            overflow: 'hidden',
          }}
        >
          {/* Thumbnail or Video Preview */}
          {hovering && !video.isLocked ? (
            <video
              ref={videoRef}
              src={`/media/public/${video.id}/stream`}
              autoPlay
              loop
              muted
              playsInline
              style={{
                position: 'absolute',
                top: 0,
                left: 0,
                width: '100%',
                height: '100%',
                objectFit: 'cover',
              }}
            />
          ) : video.thumbnailPath && !thumbnailError ? (
            <img
              src={`/media/public/${video.id}/thumbnail`}
              alt={title}
              onError={() => setThumbnailError(true)}
              style={{
                position: 'absolute',
                top: 0,
                left: 0,
                width: '100%',
                height: '100%',
                objectFit: 'cover',
              }}
            />
          ) : (
            <div
              style={{
                position: 'absolute',
                top: 0,
                left: 0,
                width: '100%',
                height: '100%',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                fontSize: 48,
                color: '#666',
              }}
            >
              {video.orientation === 'V' ? '\uD83D\uDCF1' : '\uD83C\uDFAC'}
            </div>
          )}

          {/* Lock overlay */}
          {video.isLocked && (
            <div
              style={{
                position: 'absolute',
                inset: 0,
                background: 'rgba(0, 0, 0, 0.7)',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                backdropFilter: 'blur(2px)',
              }}
            >
              <LockOutlined style={{ fontSize: 48, color: token.colorPrimary }} />
            </div>
          )}

          {/* Play button overlay — always visible on mobile, hover-only on desktop */}
          {!video.isLocked && (
            <div
              style={{
                position: 'absolute',
                inset: 0,
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                background: isMobile ? 'rgba(0, 0, 0, 0.2)' : 'rgba(0, 0, 0, 0.3)',
                opacity: isMobile ? 1 : 0,
                transition: 'opacity 0.2s ease',
              }}
              onMouseEnter={(e) => {
                if (!isMobile) e.currentTarget.style.opacity = '1';
              }}
              onMouseLeave={(e) => {
                if (!isMobile) e.currentTarget.style.opacity = '0';
              }}
            >
              <div
                style={{
                  width: isMobile ? 48 : 64,
                  height: isMobile ? 48 : 64,
                  borderRadius: '50%',
                  background: hexToRgba(token.colorPrimary, 0.9),
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  transition: 'transform 0.2s ease',
                }}
                onMouseEnter={(e) => {
                  if (!isMobile) e.currentTarget.style.transform = 'scale(1.1)';
                }}
                onMouseLeave={(e) => {
                  if (!isMobile) e.currentTarget.style.transform = 'scale(1)';
                }}
              >
                <PlayCircleOutlined style={{ fontSize: isMobile ? 24 : 32, color: '#fff' }} />
              </div>
            </div>
          )}

          {/* Duration badge */}
          {video.durationSeconds && (
            <div
              style={{
                position: 'absolute',
                bottom: 8,
                right: 8,
                background: 'rgba(0, 0, 0, 0.8)',
                color: '#fff',
                padding: '2px 8px',
                borderRadius: 4,
                fontSize: 12,
                fontWeight: 500,
              }}
            >
              {formatDuration(video.durationSeconds)}
            </div>
          )}

          {/* Quality badge */}
          {video.quality && (
            <Tag
              style={{
                position: 'absolute',
                top: 8,
                left: 8,
                margin: 0,
                background: token.colorPrimary,
                border: 'none',
                color: '#fff',
                fontWeight: 600,
              }}
            >
              {video.quality}
            </Tag>
          )}

          {/* Category badge */}
          {video.category && (
            <Tag
              style={{
                position: 'absolute',
                top: 8,
                right: 8,
                margin: 0,
                background: 'rgba(255, 255, 255, 0.15)',
                backdropFilter: 'blur(4px)',
                border: '1px solid rgba(255, 255, 255, 0.2)',
                color: '#fff',
              }}
            >
              {video.category}
            </Tag>
          )}
        </div>
      }
    >
      {/* Card content */}
      <Space direction="vertical" size={8} style={{ width: '100%' }}>
        {/* Title */}
        <Typography.Text
          strong
          style={{
            fontSize: 14,
            display: 'block',
            overflow: 'hidden',
            textOverflow: 'ellipsis',
            whiteSpace: 'nowrap',
            color: token.colorText,
          }}
          title={title}
        >
          {title}
        </Typography.Text>

        {/* Engagement metrics */}
        <Space size={16} style={{ fontSize: 12, color: token.colorTextSecondary }}>
          <Space size={4}>
            <LikeOutlined />
            <span>{formatCount(video.upvoteCount)}</span>
          </Space>
          <Space size={4}>
            <EyeOutlined />
            <span>{formatCount(video.viewCount)}</span>
          </Space>
          <Space size={4}>
            <CommentOutlined />
            <span>{formatCount(video.commentCount)}</span>
          </Space>
        </Space>
      </Space>
    </Card>
  );
}
