import React from 'react';
import { Item } from '../types';
import { getImageUrl } from '../services/uploadService';

interface ItemMarkerInfoProps {
  item: Item;
  onViewDetails?: () => void;
}

const ItemMarkerInfo: React.FC<ItemMarkerInfoProps> = ({ item, onViewDetails }) => {
  const getPriceDisplay = () => {
    if (item.pricePerDay !== undefined) {
      return Number(item.pricePerDay) === 0 
        ? "Free to Borrow" 
        : `$${Math.floor(Number(item.pricePerDay))}/Day`;
    } else if (item.pricePerHour !== undefined) {
      return Number(item.pricePerHour) === 0 
        ? "Free to Borrow" 
        : `$${Math.floor(Number(item.pricePerHour))}/Hour`;
    }
    return 'Contact for pricing';
  };

  return (
    <div style={{ width: 'min(280px, 90vw)', maxWidth: '280px' }}>
      <div className="card border-0">
        {item.imageFilenames && item.imageFilenames[0] ? (
          <img
            src={getImageUrl(item.imageFilenames[0], 'thumbnail')}
            className="card-img-top"
            alt={item.name}
            onError={(e) => {
              const target = e.currentTarget;
              if (!target.dataset.fallback) {
                target.dataset.fallback = 'true';
                target.src = getImageUrl(item.imageFilenames[0], 'original');
              }
            }}
            style={{
              height: '120px',
              objectFit: 'contain',
              backgroundColor: '#f8f9fa',
              borderRadius: '8px 8px 0 0'
            }}
          />
        ) : (
          <div
            className="bg-light d-flex align-items-center justify-content-center"
            style={{ 
              height: '120px',
              borderRadius: '8px 8px 0 0'
            }}
          >
            <i className="bi bi-image text-muted" style={{ fontSize: '1.5rem' }}></i>
          </div>
        )}
        
        <div className="card-body p-3">
          <div className="card-title mb-2 text-dark fw-bold text-truncate" style={{ fontSize: '0.875rem' }}>
            {item.name}
          </div>

          <div className="mb-2">
            <span className="text-primary fw-semibold" style={{ fontSize: '0.8rem' }}>
              {getPriceDisplay()}
            </span>
          </div>

          {item.description && (
            <p className="card-text text-muted small mb-3" 
               style={{ 
                 display: '-webkit-box',
                 WebkitLineClamp: 2,
                 WebkitBoxOrient: 'vertical',
                 overflow: 'hidden',
                 lineHeight: '1.2em',
                 maxHeight: '2.4em'
               }}>
              {item.description}
            </p>
          )}

          <div className="d-grid">
            <button 
              className="btn btn-primary btn-sm"
              onClick={onViewDetails}
            >
              View Details
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ItemMarkerInfo;