import { Card, Checkbox, Tag, Tooltip } from 'antd';
import {
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  FolderOutlined,
  PictureOutlined,
} from '@ant-design/icons';
import { useSignedMediaUrl } from '@/lib/media-url';
import type { Photo } from '@/types/media';

interface PhotoCardProps {
  photo: Photo;
  selected?: boolean;
  onSelect?: (id: number) => void;
  onClick?: (photo: Photo) => void;
  onEdit?: (photo: Photo) => void;
  onPreview?: (photo: Photo) => void;
  onDelete?: (photo: Photo) => void;
  onTogglePublish?: (photo: Photo) => void;
}

function formatFileSize(sizeStr: string | null): string {
  if (!sizeStr) return '';
  const bytes = parseInt(sizeStr);
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}

export default function PhotoCard({
  photo,
  selected,
  onSelect,
  onClick,
  onEdit,
  onPreview,
  onDelete,
  onTogglePublish,
}: PhotoCardProps) {
  const thumbnailUrl = photo.thumbnailUrl;
  const signedThumbnailUrl = useSignedMediaUrl(thumbnailUrl);

  const hoverActions = (
    <div
      style={{
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        background: 'rgba(0,0,0,0.55)',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        gap: 8,
        opacity: 0,
        transition: 'opacity 0.2s',
      }}
      className="photo-card-hover"
    >
      {onEdit && (
        <Tooltip title="Edit">
          <EditOutlined
            style={{ color: '#fff', fontSize: 18, cursor: 'pointer' }}
            onClick={(e) => { e.stopPropagation(); onEdit(photo); }}
          />
        </Tooltip>
      )}
      {onPreview && (
        <Tooltip title="Preview">
          <EyeOutlined
            style={{ color: '#fff', fontSize: 18, cursor: 'pointer' }}
            onClick={(e) => { e.stopPropagation(); onPreview(photo); }}
          />
        </Tooltip>
      )}
      {onDelete && (
        <Tooltip title="Delete">
          <DeleteOutlined
            style={{ color: '#ff4d4f', fontSize: 18, cursor: 'pointer' }}
            onClick={(e) => { e.stopPropagation(); onDelete(photo); }}
          />
        </Tooltip>
      )}
    </div>
  );

  return (
    <Card
      hoverable
      size="small"
      style={{ position: 'relative', overflow: 'hidden' }}
      styles={{ body: { padding: 8 } }}
      onClick={() => onClick?.(photo)}
      cover={
        <div
          style={{
            position: 'relative',
            paddingTop: '75%', // 4:3 aspect ratio
            backgroundColor: '#1a1a1a',
            overflow: 'hidden',
          }}
        >
          {thumbnailUrl && signedThumbnailUrl ? (
            <img
              src={signedThumbnailUrl}
              alt={photo.title || photo.filename}
              style={{
                position: 'absolute',
                top: 0,
                left: 0,
                width: '100%',
                height: '100%',
                objectFit: 'cover',
              }}
              loading="lazy"
            />
          ) : (
            <div
              style={{
                position: 'absolute',
                top: '50%',
                left: '50%',
                transform: 'translate(-50%, -50%)',
              }}
            >
              <PictureOutlined style={{ fontSize: 32, color: '#555' }} />
            </div>
          )}

          {/* Selection checkbox */}
          {onSelect && (
            <Checkbox
              checked={selected}
              onChange={(e) => { e.stopPropagation(); onSelect(photo.id); }}
              onClick={(e) => e.stopPropagation()}
              style={{ position: 'absolute', top: 6, left: 6, zIndex: 2 }}
            />
          )}

          {/* Publish toggle pill */}
          {onTogglePublish && (
            <div
              onClick={(e) => {
                e.stopPropagation();
                onTogglePublish(photo);
              }}
              style={{
                position: 'absolute',
                top: 8,
                right: 8,
                cursor: 'pointer',
                background: photo.isPublished
                  ? 'linear-gradient(135deg, #10b981 0%, #059669 100%)'
                  : 'linear-gradient(135deg, #6b7280 0%, #4b5563 100%)',
                color: '#fff',
                padding: '4px 10px',
                borderRadius: 20,
                fontSize: 11,
                fontWeight: 600,
                display: 'flex',
                alignItems: 'center',
                gap: 5,
                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={photo.isPublished ? 'Click to unpublish' : 'Click to publish'}
              role="button"
              aria-label={photo.isPublished ? 'Unpublish photo' : 'Publish photo'}
            >
              {photo.isPublished ? (
                <>
                  <CheckCircleOutlined style={{ fontSize: 13 }} />
                  <span>Published</span>
                </>
              ) : (
                <>
                  <ClockCircleOutlined style={{ fontSize: 13 }} />
                  <span>Draft</span>
                </>
              )}
            </div>
          )}

          {/* Album badge */}
          {photo.album && (
            <Tag
              color="blue"
              style={{ position: 'absolute', bottom: 6, left: 6, margin: 0 }}
            >
              <FolderOutlined /> {photo.album.title}
            </Tag>
          )}

          {/* Format badge */}
          {photo.format && (
            <Tag
              style={{ position: 'absolute', bottom: 6, right: 6, margin: 0, fontSize: 10 }}
            >
              {photo.format.toUpperCase()}
            </Tag>
          )}

          {hoverActions}
        </div>
      }
    >
      <Card.Meta
        title={
          <div style={{ fontSize: 12, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
            {photo.title || photo.originalFilename || photo.filename}
          </div>
        }
        description={
          <div style={{ fontSize: 11, color: '#999' }}>
            {photo.width && photo.height ? `${photo.width}×${photo.height}` : ''}
            {photo.fileSize ? ` · ${formatFileSize(photo.fileSize)}` : ''}
          </div>
        }
      />
      <style>{`
        .photo-card-hover { opacity: 0 !important; }
        .ant-card:hover .photo-card-hover { opacity: 1 !important; }
      `}</style>
    </Card>
  );
}
