import type { StorePrice } from '../types/basicBasket'
import { formatPrice, formatDate } from '../utils/formatters'

interface StorePriceCardProps {
  storePrice: StorePrice
}

export default function StorePriceCard({ storePrice }: StorePriceCardProps) {
  const {
    store_name,
    store_logo_url,
    price,
    currency,
    checked_at,
    is_price_stale,
    external_url,
    external_url_type,
  } = storePrice

  const hasValidExternalUrl = external_url !== null && external_url_type === 'store_product'
  const priceText = formatPrice(price, currency)
  const hasPrice = price !== null

  return (
    <article className="flex items-center gap-4 p-4 bg-white border border-[#e5e7eb] rounded-xl hover:shadow-sm transition-shadow">
      {/* Logo tienda */}
      <div className="w-14 h-14 flex-shrink-0 flex items-center justify-center bg-[#f4f5f6] rounded-lg overflow-hidden">
        {store_logo_url ? (
          <img
            src={store_logo_url}
            alt={store_name}
            className="w-full h-full object-contain p-1"
          />
        ) : (
          <span className="text-xs text-gray-400 text-center leading-tight px-1">{store_name}</span>
        )}
      </div>

      {/* Nombre + precio */}
      <div className="flex-1 min-w-0">
        <p className="text-sm font-semibold text-[#3d3c3a] truncate">{store_name}</p>
        <p className={`text-xl font-bold mt-0.5 ${hasPrice ? 'text-[#3d3c3a]' : 'text-gray-400 text-base'}`}>
          {priceText}
        </p>
        {is_price_stale === true && hasPrice && (
          <p className="text-xs text-amber-600 mt-0.5">
            Precio histórico ({formatDate(checked_at)})
          </p>
        )}
        {!is_price_stale && hasPrice && checked_at && (
          <p className="text-xs text-gray-400 mt-0.5">
            Actualizado {formatDate(checked_at)}
          </p>
        )}
      </div>

      {/* Botón ir al producto */}
      <div className="flex-shrink-0">
        {hasValidExternalUrl ? (
          <a
            href={external_url}
            target="_blank"
            rel="noopener noreferrer"
            className="inline-block px-4 py-2 text-sm font-semibold text-white bg-[#3d3c3a] rounded-lg hover:bg-[#87afa4] transition-colors focus:outline-none focus:ring-2 focus:ring-[#87afa4] whitespace-nowrap"
            aria-label={`Ir al producto en ${store_name}`}
          >
            Ir al producto
          </a>
        ) : (
          <button
            type="button"
            disabled
            aria-disabled="true"
            className="px-4 py-2 text-sm font-semibold text-gray-400 bg-gray-100 border border-gray-200 rounded-lg cursor-not-allowed whitespace-nowrap"
            title="URL del producto no disponible"
          >
            Ir al producto
          </button>
        )}
      </div>
    </article>
  )
}

