"use client";

import { Card, Chip, CloseButton } from "@heroui/react";
import Image from "next/image";
import Link from "next/link";
import { formatPrice } from "@repo/utils";
import { getStockStatus, STOCK_STATUS_CONFIG } from "@/lib/wishlist/constants";
import type { WishlistItem } from "@/lib/wishlist/types";
import { WishlistActions } from "./WishlistActions";

type WishlistItemCardProps = {
  item: WishlistItem;
  onRemove: (id: string) => void;
  onAddToCart: (variantId: string) => void;
  isRemoving: boolean;
  isAddingToCart: boolean;
};

export function WishlistItemCard({
  item,
  onRemove,
  onAddToCart,
  isRemoving,
  isAddingToCart,
}: WishlistItemCardProps) {
  const { product, variant } = item;

  if (!product) {
    return (
      <Card className="relative opacity-60">
        <Card.Header className="relative">
          <CloseButton
            aria-label="Remove unavailable item from wishlist"
            className="absolute right-2 top-2 z-10"
            onPress={() => onRemove(item._id)}
          />
          <Card.Title className="text-sm text-gray-500">
            Product no longer available
          </Card.Title>
        </Card.Header>
        <Card.Footer>
          <button
            className="w-full rounded-lg border border-gray-200 py-2 text-sm text-gray-500 transition-colors hover:bg-gray-50"
            onClick={() => onRemove(item._id)}
          >
            Remove
          </button>
        </Card.Footer>
      </Card>
    );
  }

  const productUrl = `/shop/${product.parentCategorySlug}/${product.childCategorySlug}/${product.slug}`;
  const imageSrc = product.images[0]?.url ?? "/placeholder-product.png";
  const imageAlt = product.images[0]?.alt ?? product.name;

  const activeVariant = variant ?? product.variants[0];
  const currentPrice = activeVariant?.price ?? 0;
  const compareAtPrice = activeVariant?.compareAtPrice;

  const stockStatus = getStockStatus(product.status, activeVariant?.stockQuantity);
  const stockConfig = STOCK_STATUS_CONFIG[stockStatus];
  const isAvailable = stockStatus === "in_stock" || stockStatus === "low_stock";

  const priceDiff = currentPrice - item.priceWhenAdded;

  return (
    <Card className="relative flex flex-col">
      <Card.Header className="relative p-0">
        <CloseButton
          aria-label={`Remove ${product.name} from wishlist`}
          className="absolute right-2 top-2 z-10"
          onPress={() => onRemove(item._id)}
        />
        <Link href={productUrl} className="block aspect-square w-full overflow-hidden rounded-t-2xl">
          <div className="relative h-full w-full">
            <Image
              src={imageSrc}
              alt={imageAlt}
              fill
              sizes="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 33vw"
              className="object-contain mix-blend-multiply p-4"
              loading="lazy"
            />
          </div>
        </Link>
      </Card.Header>

      <Card.Content className="flex flex-1 flex-col gap-2 p-4">
        <Link href={productUrl} className="group">
          {product.brand && (
            <span className="block font-[family-name:var(--font-fraunces)] text-xs font-bold text-[var(--foreground)] group-hover:text-[#38a99f]">
              {product.brand}
            </span>
          )}
          <span className="line-clamp-2 text-sm font-medium leading-snug text-[var(--foreground)]">
            {product.name}
          </span>
        </Link>

        {variant && (
          <Chip size="sm" className="w-fit text-xs">
            {variant.name}
          </Chip>
        )}

        <Chip size="sm" className={`w-fit text-xs ${stockConfig.colorClass}`}>
          {stockConfig.label}
        </Chip>

        <div className="mt-auto flex items-baseline gap-2 pt-2">
          <span className="text-lg font-semibold text-[var(--brand-dark)]">
            {formatPrice(currentPrice)}
          </span>
          {compareAtPrice && compareAtPrice > currentPrice && (
            <s className="text-sm text-[var(--muted)]" aria-label="Original price">
              {formatPrice(compareAtPrice)}
            </s>
          )}
        </div>

        {item.priceWhenAdded > 0 && priceDiff < 0 && (
          <span className="text-xs font-medium text-[var(--coral)]">
            Price dropped!
          </span>
        )}
        {item.priceWhenAdded > 0 && priceDiff > 0 && (
          <span className="text-xs text-[var(--muted)]">
            Price increased
          </span>
        )}
      </Card.Content>

      <Card.Footer className="p-4 pt-0">
        <WishlistActions
          onRemove={() => onRemove(item._id)}
          onAddToCart={() => {
            if (activeVariant) onAddToCart(activeVariant._id);
          }}
          isRemoving={isRemoving}
          isAddingToCart={isAddingToCart}
          isAvailable={isAvailable}
        />
      </Card.Footer>
    </Card>
  );
}
