import { Card, Checkbox, Tag, Spin } from 'antd';
import { ClockCircleOutlined, CheckCircleOutlined, ThunderboltFilled, LockOutlined, CrownOutlined } from '@ant-design/icons';
import { useState } from 'react';
import type { Video } from '@/types/media';
import { useSignedMediaUrl } from '@/lib/media-url';
import VideoActions from './VideoActions';
import ScheduleBadge from './ScheduleBadge';

interface VideoCardProps {
  video: Video;
  selected: boolean;
  onSelect: (id: number) => void;
  onClick?: (video: Video) => void;
  onEdit?: (video: Video) => void;
  onPreview?: (video: Video) => void;
  onAnalytics?: (video: Video) => void;
  onSchedule?: (video: Video) => void;
  onDelete?: (video: Video) => void;
  onAddToPlaylist?: (video: Video) => void;
  onRefresh?: () => void;
  onTogglePublish?: (video: Video) => void;
  showActions?: boolean;
}

export default function VideoCard({
  video,
  selected,
  onSelect,
  onClick,
  onEdit,
  onPreview,
  onAnalytics,
  onSchedule,
  onDelete,
  onAddToPlaylist,
  onRefresh,
  onTogglePublish,
  showActions = true,
}: VideoCardProps) {
  const [thumbnailLoading, setThumbnailLoading] = useState(true);
  const [thumbnailError, setThumbnailError] = useState(false);
  const signedThumbnailUrl = useSignedMediaUrl(video.thumbnailUrl);

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

  const formatFileSize = (bytes: number) => {
    const mb = bytes / (1024 * 1024);
    if (mb >= 1024) {
      return `${(mb / 1024).toFixed(1)} GB`;
    }
    return `${mb.toFixed(0)} MB`;
  };

  return (
    <Card
      hoverable
      cover={
        <div
          style={{
            position: 'relative',
            paddingTop: video.orientation === 'V' ? '177.78%' : '56.25%',
            background: '#1f1f1f',
            overflow: 'hidden',
          }}
        >
          {/* Thumbnail image or fallback */}
          {video.thumbnailUrl && !thumbnailError && signedThumbnailUrl ? (
            <>
              <img
                src={signedThumbnailUrl}
                alt={video.title}
                style={{
                  position: 'absolute',
                  top: 0,
                  left: 0,
                  width: '100%',
                  height: '100%',
                  objectFit: 'cover',
                  display: thumbnailLoading ? 'none' : 'block',
                }}
                onLoad={() => setThumbnailLoading(false)}
                onError={() => {
                  setThumbnailError(true);
                  setThumbnailLoading(false);
                }}
              />
              {thumbnailLoading && (
                <div
                  style={{
                    position: 'absolute',
                    top: 0,
                    left: 0,
                    width: '100%',
                    height: '100%',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                  }}
                >
                  <Spin />
                </div>
              )}
            </>
          ) : (
            <div
              style={{
                position: 'absolute',
                top: 0,
                left: 0,
                width: '100%',
                height: '100%',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                color: '#666',
                fontSize: 48,
              }}
            >
              {video.orientation === 'V' ? '📱' : '🎬'}
            </div>
          )}

          {/* Schedule badge */}
          <ScheduleBadge
            scheduledPublishAt={video.scheduledPublishAt}
            scheduledUnpublishAt={video.scheduledUnpublishAt}
            isPublished={video.isPublished}
          />

          {/* Publish toggle pill */}
          {onTogglePublish && (
            <div
              onClick={(e) => {
                e.stopPropagation();
                onTogglePublish(video);
              }}
              style={{
                position: 'absolute',
                top: 8,
                right: video.scheduledPublishAt || video.scheduledUnpublishAt ? 120 : 8,
                cursor: 'pointer',
                background: video.isPublished
                  ? 'linear-gradient(135deg, #10b981 0%, #059669 100%)'
                  : 'linear-gradient(135deg, #6b7280 0%, #4b5563 100%)',
                color: '#fff',
                padding: '6px 14px',
                borderRadius: 20,
                fontSize: 12,
                fontWeight: 600,
                display: 'flex',
                alignItems: 'center',
                gap: 6,
                boxShadow: '0 2px 8px rgba(0, 0, 0, 0.15)',
                transition: 'all 0.2s ease',
                zIndex: 11,
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.transform = 'scale(1.05)';
                e.currentTarget.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.25)';
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.transform = 'scale(1)';
                e.currentTarget.style.boxShadow = '0 2px 8px rgba(0, 0, 0, 0.15)';
              }}
              title={video.isPublished ? 'Click to unpublish' : 'Click to publish'}
              role="button"
              aria-label={video.isPublished ? 'Unpublish video' : 'Publish video'}
            >
              {video.isPublished ? (
                <>
                  <CheckCircleOutlined style={{ fontSize: 14 }} />
                  <span>Published</span>
                </>
              ) : (
                <>
                  <ClockCircleOutlined style={{ fontSize: 14 }} />
                  <span>Draft</span>
                </>
              )}
            </div>
          )}

          {/* Action buttons overlay */}
          {showActions && (
            <VideoActions
              video={video}
              onEdit={onEdit}
              onPreview={onPreview}
              onAnalytics={onAnalytics}
              onSchedule={onSchedule}
              onDelete={onDelete}
              onAddToPlaylist={onAddToPlaylist}
              onRefresh={onRefresh}
            />
          )}

          {/* Duration badge */}
          <div
            style={{
              position: 'absolute',
              bottom: 8,
              right: 8,
              background: 'rgba(0, 0, 0, 0.8)',
              color: '#fff',
              padding: '2px 6px',
              borderRadius: 4,
              fontSize: 12,
              display: 'flex',
              alignItems: 'center',
              gap: 4,
            }}
          >
            <ClockCircleOutlined />
            {formatDuration(video.duration)}
          </div>

          {/* Short video badge */}
          {video.isShort && (
            <div
              style={{
                position: 'absolute',
                bottom: 8,
                left: 8,
                background: 'linear-gradient(135deg, #f59e0b 0%, #d97706 100%)',
                color: '#fff',
                padding: '2px 8px',
                borderRadius: 4,
                fontSize: 11,
                fontWeight: 600,
                display: 'flex',
                alignItems: 'center',
                gap: 4,
              }}
            >
              <ThunderboltFilled style={{ fontSize: 12 }} />
              Short
            </div>
          )}

          {/* Select checkbox */}
          <div
            style={{
              position: 'absolute',
              top: 8,
              left: 8,
            }}
          >
            <Checkbox
              checked={selected}
              onChange={(e) => {
                e.stopPropagation();
                onSelect(video.id);
              }}
              onClick={(e) => e.stopPropagation()}
              aria-label={`Select ${video.title || `video ${video.id}`}`}
            />
          </div>
        </div>
      }
      onClick={() => onClick?.(video)}
      style={{ cursor: 'pointer' }}
      role="article"
      aria-label={`Video card: ${video.title || `Video ${video.id}`}`}
    >
      <Card.Meta
        title={
          <div style={{ fontSize: 14, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {video.title}
          </div>
        }
        description={
          <div style={{ fontSize: 12 }}>
            <div>{video.width} × {video.height}</div>
            <div>{formatFileSize(video.fileSize)}</div>
            {video.accessLevel && video.accessLevel !== 'free' && (
              <Tag
                style={{ marginTop: 4 }}
                color={video.accessLevel === 'premium' ? 'gold' : 'purple'}
                icon={video.accessLevel === 'premium' ? <CrownOutlined /> : <LockOutlined />}
              >
                {video.accessLevel === 'premium' ? 'Premium' : 'Member'}
              </Tag>
            )}
            {video.producer && (
              <Tag style={{ marginTop: 4 }} color="blue">
                {video.producer}
              </Tag>
            )}
            {video.creator && (
              <Tag style={{ marginTop: 4 }} color="green">
                {video.creator}
              </Tag>
            )}
          </div>
        }
      />
    </Card>
  );
}
