import { useState, useEffect, useCallback } from 'react';
import { Card, Typography, Spin, Flex, Button, Tag, Tooltip } from 'antd';
import {
  VideoCameraOutlined,
  ReloadOutlined,
  EyeOutlined,
  MessageOutlined,
  LikeOutlined,
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { api } from '@/lib/api';
import type { DashboardTopVideosResult, DashboardTopVideo } from '@/types/api';

const { Text } = Typography;

function formatDuration(seconds: number | null): string {
  if (!seconds) return '--:--';
  const m = Math.floor(seconds / 60);
  const s = seconds % 60;
  return `${m}:${s.toString().padStart(2, '0')}`;
}

function VideoRow({ video, rank }: { video: DashboardTopVideo; rank: number }) {
  const navigate = useNavigate();
  const displayTitle = video.title || video.filename;

  return (
    <Flex
      align="center"
      gap={8}
      onClick={() => navigate(`/gallery/watch/${video.id}`)}
      style={{
        padding: '5px 0',
        borderBottom: '1px solid rgba(255,255,255,0.04)',
        lineHeight: 1.4,
        cursor: 'pointer',
      }}
    >
      <Text type="secondary" style={{ fontSize: 13, flexShrink: 0, width: 18, textAlign: 'center' }}>
        {rank}
      </Text>
      <Tooltip title={displayTitle}>
        <Text
          strong
          style={{
            fontSize: 13,
            flex: 1,
            minWidth: 0,
            overflow: 'hidden',
            textOverflow: 'ellipsis',
            whiteSpace: 'nowrap',
          }}
        >
          {displayTitle}
        </Text>
      </Tooltip>
      {!video.isPublished && (
        <Tag style={{ fontSize: 10, margin: 0, padding: '0 4px', lineHeight: '18px' }}>Draft</Tag>
      )}
      <Text type="secondary" style={{ fontSize: 11, flexShrink: 0 }}>
        {formatDuration(video.durationSeconds)}
      </Text>
      <Flex gap={6} style={{ flexShrink: 0 }}>
        <Tooltip title="Views">
          <Text type="secondary" style={{ fontSize: 11 }}>
            <EyeOutlined style={{ marginRight: 2, fontSize: 10 }} />
            {video.viewCount}
          </Text>
        </Tooltip>
        {video.commentCount > 0 && (
          <Tooltip title="Comments">
            <Text type="secondary" style={{ fontSize: 11 }}>
              <MessageOutlined style={{ marginRight: 2, fontSize: 10 }} />
              {video.commentCount}
            </Text>
          </Tooltip>
        )}
        {video.upvoteCount > 0 && (
          <Tooltip title="Upvotes">
            <Text type="secondary" style={{ fontSize: 11 }}>
              <LikeOutlined style={{ marginRight: 2, fontSize: 10 }} />
              {video.upvoteCount}
            </Text>
          </Tooltip>
        )}
      </Flex>
    </Flex>
  );
}

export default function TopVideosCard() {
  const [result, setResult] = useState<DashboardTopVideosResult | null>(null);
  const [loading, setLoading] = useState(true);

  const fetchVideos = useCallback(async () => {
    setLoading(true);
    try {
      const res = await api.get<DashboardTopVideosResult>('/dashboard/top-videos');
      setResult(res.data);
    } catch {
      // non-critical widget
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchVideos();
    const interval = setInterval(fetchVideos, 5 * 60_000);
    return () => clearInterval(interval);
  }, [fetchVideos]);

  if (result && !result.enabled) return null;

  return (
    <Card
      title={<span style={{ fontSize: 14 }}><VideoCameraOutlined style={{ marginRight: 6, fontSize: 15 }} />Top Videos</span>}
      size="small"
      extra={
        <Button type="text" size="small" icon={<ReloadOutlined spin={loading} style={{ fontSize: 13 }} />} onClick={fetchVideos} />
      }
      styles={{ body: { padding: '6px 14px 8px' } }}
    >
      {loading && !result ? (
        <div style={{ textAlign: 'center', padding: 12 }}><Spin size="small" /></div>
      ) : result && result.videos.length > 0 ? (
        <div>
          {result.videos.map((video, i) => (
            <VideoRow key={video.id} video={video} rank={i + 1} />
          ))}
        </div>
      ) : (
        <Text type="secondary" style={{ fontSize: 13, display: 'block', padding: '8px 0' }}>No videos yet</Text>
      )}
    </Card>
  );
}
