import * as React from "react"

import { cn } from "@/lib/utils"
import { Spinner } from "./spinner"

interface MTGCardProps {
  className?: string,
  imageURI: string,
  cardname: string,
  url: string,
  nbrDecks?: number,
  totalDecks?: number,
  percentDecks?: number,
  price?: string,
  cardmarketURI?: string
}

const MTGCard = ({ className, imageURI, cardname, url, nbrDecks, totalDecks, percentDecks, price, cardmarketURI }: MTGCardProps) => {
  const [loaded, setLoaded] = React.useState(false)

  return (
    <div
      className={cn(
        "flex flex-col w-48",
        className
      )}
    >
      {!loaded && 
        <div className="flex flex-col items-center justify-center h-64 bg-stone-500 rounded-md">
          <Spinner />
        </div>
      }
      <img src={imageURI} className={ loaded ? "rounded h-64" : "absolute opacity-0" }  onLoad={() => {setLoaded(true)}} loading="lazy" />
      <div className="flex flex-col items-center gap-0">
        { price != undefined && (
          <a className="text-xs" href={cardmarketURI != undefined ? cardmarketURI : "#"} target={cardmarketURI != undefined ? "_blank" : "_self"}>{price}€</a>
        )}
        <span className="text-center text-xs">{cardname}</span>
        { nbrDecks != undefined && (
          <>
            <span className="text-md">{nbrDecks} Deck{nbrDecks > 1 ? "s" : ""}
              { percentDecks != undefined && ( <span> sur {totalDecks} ({percentDecks}%)</span>)}</span>
          </>
        )}
      </div>
    </div>
  )}
MTGCard.displayName = "MTGCard"

export { MTGCard, type MTGCardProps }
