import { useState, useEffect } from 'react';
import { List, Typography, Space, Spin, theme, Empty } from 'antd';
import { PlayCircleOutlined, EyeOutlined } from '@ant-design/icons';
import { mediaPublicApi } from '@/lib/media-public-api';

const { Text } = Typography;

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

interface RelatedVideosListProps {
  currentVideoId: number;
  currentCategory?: string;
  onVideoSelect: (video: Video) => void;
  maxVideos?: number;
}

export default function RelatedVideosList({
  currentVideoId,
  currentCategory,
  onVideoSelect,
  maxVideos = 5,
}: RelatedVideosListProps) {
  const { token } = theme.useToken();
  const [videos, setVideos] = useState<Video[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchRelatedVideos();
  }, [currentVideoId, currentCategory]);

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

      // Fetch videos from same category or recent videos
      const params: any = {
        limit: maxVideos + 1, // Get one extra to exclude current video
        sort: 'recent',
      };

      if (currentCategory) {
        params.category = currentCategory;
      }

      const response = await mediaPublicApi.get('/public', { params });

      // Filter out current video
      const relatedVideos = response.data.videos
        .filter((v: Video) => v.id !== currentVideoId)
        .slice(0, maxVideos);

      setVideos(relatedVideos);
    } catch (error) {
      console.error('Failed to fetch related videos:', error);
    } finally {
      setLoading(false);
    }
  };

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

  const formatCount = (count: number) => {
    if (count >= 1000000) {
      return `${(count / 1000000).toFixed(1)}M`;
    }
    if (count >= 1000) {
      return `${(count / 1000).toFixed(1)}K`;
    }
    return count.toString();
  };

  if (loading) {
    return (
      <div style={{ padding: 24, textAlign: 'center' }}>
        <Spin size="small" tip="Loading related videos..." />
      </div>
    );
  }

  if (videos.length === 0) {
    return (
      <div style={{ padding: 24 }}>
        <Empty
          description="No related videos"
          image={Empty.PRESENTED_IMAGE_SIMPLE}
        />
      </div>
    );
  }

  return (
    <div>
      <div
        style={{
          padding: '12px 16px',
          borderBottom: `1px solid ${token.colorBorder}`,
          background: token.colorBgLayout,
        }}
      >
        <Text strong>Related Videos</Text>
      </div>

      <List
        dataSource={videos}
        renderItem={(video) => {
          const title = video.filename.replace(/\.[^/.]+$/, '');

          return (
            <List.Item
              key={video.id}
              onClick={() => onVideoSelect(video)}
              style={{
                cursor: 'pointer',
                padding: 12,
                transition: 'background 0.2s',
                borderBottom: `1px solid ${token.colorBorderSecondary}`,
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.background = token.colorBgTextHover;
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.background = 'transparent';
              }}
            >
              <Space size={12} style={{ width: '100%' }}>
                {/* Thumbnail */}
                <div
                  style={{
                    position: 'relative',
                    width: 120,
                    height: video.orientation === 'V' ? 160 : 68,
                    borderRadius: 8,
                    overflow: 'hidden',
                    flexShrink: 0,
                    background: '#000',
                  }}
                >
                  {video.thumbnailPath ? (
                    <img
                      src={`/api/media/public/${video.id}/thumbnail`}
                      alt={title}
                      style={{
                        width: '100%',
                        height: '100%',
                        objectFit: 'cover',
                      }}
                    />
                  ) : (
                    <div
                      style={{
                        width: '100%',
                        height: '100%',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        fontSize: 24,
                        color: '#666',
                      }}
                    >
                      {video.orientation === 'V' ? '📱' : '🎬'}
                    </div>
                  )}

                  {/* Play icon overlay */}
                  <div
                    style={{
                      position: 'absolute',
                      inset: 0,
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      background: 'rgba(0, 0, 0, 0.3)',
                    }}
                  >
                    <PlayCircleOutlined style={{ fontSize: 24, color: '#fff' }} />
                  </div>

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

                {/* Info */}
                <div style={{ flex: 1, overflow: 'hidden' }}>
                  <Text
                    strong
                    style={{
                      display: 'block',
                      fontSize: 13,
                      overflow: 'hidden',
                      textOverflow: 'ellipsis',
                      whiteSpace: 'nowrap',
                      marginBottom: 4,
                    }}
                    title={title}
                  >
                    {title}
                  </Text>

                  <Space size={8} style={{ fontSize: 11 }}>
                    {video.quality && (
                      <Text type="secondary">{video.quality}</Text>
                    )}
                    <Space size={4}>
                      <EyeOutlined />
                      <Text type="secondary">{formatCount(video.viewCount)}</Text>
                    </Space>
                  </Space>
                </div>
              </Space>
            </List.Item>
          );
        }}
      />
    </div>
  );
}
