import { HttpTypes } from "@medusajs/types"
import { Button, Heading, Text, clx } from "@medusajs/ui"
import LocalizedClientLink from "@modules/common/components/localized-client-link"
import Divider from "@modules/common/components/divider"
import PreviewPrice from "@modules/products/components/product-preview/price"
import { getProductPrice } from "@lib/util/get-product-price"
import { addToCart } from "@lib/data/cart"
import VtThumbnail from "../vt-thumbnail"
import { Plus, ChevronRight } from "@medusajs/icons"
type ProductCardProps = {
  product: HttpTypes.StoreProduct
  badgeText?: string
  deliveryTime?: string
  className?: string
  countryCode: string
  styles?: any
}

export default function ProductCard({
  product,
  badgeText = "Saved up to 20%",
  deliveryTime = "2-4 Wochen",
  className,
  countryCode,
  styles,
}: ProductCardProps) {
  const firstVariant = product.variants?.[0]

  const inStock = (() => {
    if (!firstVariant) return false
    if (!firstVariant.manage_inventory) return true
    if (firstVariant.allow_backorder) return true
    return (firstVariant.inventory_quantity || 0) > 0
  })()
  console.dir(product, { depth: null })
  const { cheapestPrice } = getProductPrice({ product })

  async function handleAddToCart() {
    "use server"
    if (!firstVariant?.id) return
    await addToCart({
      variantId: firstVariant.id,
      quantity: 1,
      countryCode,
    })
  }

  const description = (() => {
    const prodDescription = product.description || ""
    const textSlice =
      prodDescription.length > 120
        ? prodDescription.slice(0, 117) + "…"
        : prodDescription
    return textSlice
  })()

  const classes = {
    card: styles?.card ?? className ?? "",
    badge: {
      container: styles?.badge?.container ?? " pb-4",
      text:
        styles?.badge?.text ??
        "z-20 px-3 py-1 border-[0.5px] rounded bg-[#c9e0f5] txt-compact-small-plus shadow-borders-base text-[#285A86] ",
    },
    thumbnail: {
      className: styles?.thumbnail?.className ?? "rounded-none h-[240px]",
      size: styles?.thumbnail?.size ?? "full",
    },
    subtitle: styles?.subtitle ?? "",
    content: styles?.content ?? "p-6 flex flex-col flex-1",
    title: styles?.title ?? "",
    price: styles?.price ?? "",
    description: styles?.description ?? "",
    reviews: {
      container: styles?.reviews?.container ?? undefined,
      stars: styles?.reviews?.stars ?? "flex gap-1",
      star: styles?.reviews?.star ?? "text-[#C4622C] text-xl leading-none",
      emptyStar:
        styles?.reviews?.emptyStar ??
        "text-[#C4622C] text-xl opacity-30 leading-none",
      text: styles?.reviews?.text ?? "txt-small text-ui-fg-subtle",
      rating: styles?.reviews?.rating,
      count: styles?.reviews?.count,
    },
    button: {
      addToCart: styles?.button?.addToCart ?? "",
      moreInfo: styles?.button?.moreInfo ?? "",
      isShowIcon: styles?.button?.isShowIcon ?? false,
    },
  }

  return (
    <div className={clx(classes.card)}>
      <LocalizedClientLink
        href={`/products/${product.handle}`}
        className="block"
      >
        <div className="relative">
          {badgeText && (
            <div className={classes.badge.container}>
              <span className={classes.badge.text}>{badgeText}</span>
            </div>
          )}
          <VtThumbnail
            thumbnail={product.thumbnail}
            className={classes.thumbnail.className}
            images={product.images}
            size={classes.thumbnail.size}
            isFeatured
          />
        </div>
      </LocalizedClientLink>

      <div className={classes.content}>
        {classes.subtitle && product.collection && (
          <LocalizedClientLink
            href={`/collections/${product.collection.handle}`}
            className="txt-small text-ui-fg-muted hover:text-ui-fg-subtle"
          >
            {product.subtitle}
          </LocalizedClientLink>
        )}

        <LocalizedClientLink
          href={`/products/${product.handle}`}
          className="block"
        >
          <Heading
            level="h3"
            className={classes.title}
            data-testid="product-card-title"
          >
            {product.title}
          </Heading>
        </LocalizedClientLink>

        {classes.price && (
          <div className={classes.price}>
            {cheapestPrice && <PreviewPrice price={cheapestPrice} />}
          </div>
        )}

        {(classes.reviews.rating !== undefined ||
          classes.reviews.count !== undefined) && (
          <div
            className={
              classes.reviews.container || "mt-2 flex items-center gap-3"
            }
          >
            <div className="relative inline-block">
              <div className={classes.reviews.stars}>
                {Array.from({ length: 5 }).map((_, i) => (
                  <span
                    key={`star-empty-${i}`}
                    className={classes.reviews.emptyStar}
                  >
                    ★
                  </span>
                ))}
              </div>
              <div
                className="absolute inset-0 overflow-hidden"
                style={{
                  width: `${Math.max(
                    0,
                    Math.min(
                      100,
                      (((classes.reviews.rating as number) ?? 0) / 5) * 100
                    )
                  )}%`,
                }}
              >
                <div className={classes.reviews.stars}>
                  {Array.from({ length: 5 }).map((_, i) => (
                    <span
                      key={`star-fills-${i}`}
                      className={classes.reviews.star}
                    >
                      ★
                    </span>
                  ))}
                </div>
              </div>
            </div>
            {typeof classes.reviews.count === "number" && (
              <span className={classes.reviews.text}>
                {classes.reviews.count} Reviews
              </span>
            )}
          </div>
        )}

        {classes.description && (
          <Text className={clx(classes.description, "txt-small my-4")}>
            {description}
          </Text>
        )}

        <div className="flex gap-3 mt-auto">
          {classes.button?.addToCart && (
            <Button
              formAction={handleAddToCart}
              disabled={!inStock}
              variant="primary"
              className={classes.button.addToCart}
            >
              Add to cart {classes.button.isShowIcon && <Plus />}
            </Button>
          )}

          {classes.button?.moreInfo && (
            <LocalizedClientLink
              href={`/products/${product.handle}`}
              className="flex-1"
            >
              <Button variant="secondary" className={classes.button.moreInfo}>
                More Info {classes.button.isShowIcon && <ChevronRight />}
              </Button>
            </LocalizedClientLink>
          )}
        </div>
      </div>
    </div>
  )
}
