import { useState } from 'react';
import { Card, Tag, Space, Typography, theme } from 'antd';
import { CameraOutlined, LikeOutlined, EyeOutlined, CommentOutlined, PictureOutlined } from '@ant-design/icons';
import { useExpandedVideo } from '@/contexts/ExpandedVideoContext';
import { hexToRgba } from '@/utils/color';
import type { PublicPhoto } from '@/types/media';

interface PublicPhotoCardProps {
  photo: PublicPhoto;
}

export default function PublicPhotoCard({ photo }: PublicPhotoCardProps) {
  const { token } = theme.useToken();
  const { expandMedia } = useExpandedVideo();
  const [thumbnailError, setThumbnailError] = useState(false);

  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();
  };

  const title = photo.title || 'Untitled Photo';

  const handleCardClick = () => {
    expandMedia(photo.id, 'photo', photo);
  };

  const handleMouseEnter = (e: React.MouseEvent<HTMLDivElement>) => {
    const card = e.currentTarget;
    card.style.boxShadow = `0 0 0 2px ${token.colorPrimary}`;
    card.style.transform = 'translateY(-2px)';
  };

  const handleMouseLeave = (e: React.MouseEvent<HTMLDivElement>) => {
    const card = e.currentTarget;
    card.style.boxShadow = 'none';
    card.style.transform = 'translateY(0)';
  };

  // Choose aspect ratio based on orientation
  const aspectPadding = photo.orientation === 'V' ? '133.33%' : photo.orientation === 'S' ? '100%' : '75%'; // 3:4, 1:1, or 4:3

  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: aspectPadding,
            background: '#000',
            overflow: 'hidden',
          }}
        >
          {/* Thumbnail */}
          {photo.thumbnailUrl && !thumbnailError ? (
            <img
              src={photo.thumbnailUrl}
              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',
              }}
            >
              <PictureOutlined />
            </div>
          )}

          {/* Camera icon overlay on hover */}
          <div
            style={{
              position: 'absolute',
              inset: 0,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              background: 'rgba(0, 0, 0, 0.3)',
              opacity: 0,
              transition: 'opacity 0.2s ease',
            }}
            onMouseEnter={(e) => { e.currentTarget.style.opacity = '1'; }}
            onMouseLeave={(e) => { e.currentTarget.style.opacity = '0'; }}
          >
            <div
              style={{
                width: 64,
                height: 64,
                borderRadius: '50%',
                background: hexToRgba(token.colorPrimary, 0.9),
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                transition: 'transform 0.2s ease',
              }}
              onMouseEnter={(e) => { e.currentTarget.style.transform = 'scale(1.1)'; }}
              onMouseLeave={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
            >
              <CameraOutlined style={{ fontSize: 32, color: '#fff' }} />
            </div>
          </div>

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

          {/* Category badge */}
          {photo.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',
              }}
            >
              {photo.category}
            </Tag>
          )}

          {/* Dimensions badge */}
          {photo.width && photo.height && (
            <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,
              }}
            >
              {photo.width}&times;{photo.height}
            </div>
          )}
        </div>
      }
    >
      <Space direction="vertical" size={8} style={{ width: '100%' }}>
        <Typography.Text
          strong
          style={{
            fontSize: 14,
            display: 'block',
            overflow: 'hidden',
            textOverflow: 'ellipsis',
            whiteSpace: 'nowrap',
            color: token.colorText,
          }}
          title={title}
        >
          {title}
        </Typography.Text>

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