"use client";

import { Button, Card, Chip, NumberField } from "@heroui/react";
import Image from "next/image";
import Link from "next/link";
import { formatPrice } from "@repo/utils";
import { getCartItemProductUrl } from "@/lib/cart/constants";
import type { CartEnrichedItem } from "@/lib/cart/types";

const PLACEHOLDER_IMAGE = "/images/placeholder-product.png";

type CartItemCardProps = {
  item: CartEnrichedItem;
  onUpdateQuantity: (variantId: string, quantity: number) => void;
  onRemove: (variantId: string) => void;
  variant?: "compact" | "full";
};

export function CartItemCard({
  item,
  onUpdateQuantity,
  onRemove,
  variant = "compact",
}: CartItemCardProps) {
  const lineTotal = item.priceSnapshot * item.quantity;
  const productUrl = getCartItemProductUrl(item);
  const maxQty =
    item.stockQuantity != null && item.stockQuantity > 0
      ? item.stockQuantity
      : 99;

  const imgSize = variant === "full" ? 80 : 56;

  return (
    <Card variant="transparent" className="gap-0 p-0 rounded-xs p-2">
      <Card.Content className="p-0">
        <div className="flex items-start gap-3 md:gap-4">
          {/* Product image */}
          <Link
            href={productUrl}
            className="relative block shrink-0 overflow-hidden rounded-xl bg-[var(--surface)]"
            style={{ width: imgSize, height: imgSize }}
          >
            <Image
              src={item.imageUrl ?? PLACEHOLDER_IMAGE}
              alt=""
              width={imgSize}
              height={imgSize}
              className="object-cover"
              unoptimized={!(item.imageUrl ?? "").startsWith("http")}
            />
          </Link>

          {/* Details + controls */}
          <div className="flex min-w-0 flex-1 flex-col gap-1.5">
            {/* Top row: name + remove */}
            <div className="flex items-start justify-between gap-2">
              <div className="min-w-0">
                <Link
                  href={productUrl}
                  className="line-clamp-2 text-sm font-medium text-[var(--foreground)] hover:underline md:text-base"
                >
                  {item.productName}
                </Link>
                {item.variantName && (
                  <Chip
                    size="sm"
                    variant="soft"
                    className="mt-1 bg-[#e8f7f6] text-[var(--foreground)]"
                  >
                    {item.variantName}
                  </Chip>
                )}
              </div>
              <Button
                isIconOnly
                size="sm"
                variant="ghost"
                className="shrink-0 text-[var(--destructive)] hover:bg-[#fce0da]"
                aria-label={`Remove ${item.productName} from cart`}
                onPress={() => onRemove(item.variantId)}
              >
                <TrashIcon />
              </Button>
            </div>

            {/* Bottom row: price + quantity + line total */}
            <div className="flex flex-wrap items-center justify-between gap-2 pt-1">
              <span className="text-sm font-semibold text-[#236f6b]">
                {formatPrice(item.priceSnapshot)}
              </span>

              <div className="flex items-center gap-3">
                <NumberField
                  aria-label={`Quantity for ${item.productName}`}
                  value={item.quantity}
                  minValue={1}
                  maxValue={maxQty}
                  onChange={(val) => {
                    if (val !== undefined && val >= 1) {
                      onUpdateQuantity(item.variantId, val);
                    }
                  }}
                >
                  <NumberField.Group className="h-8 text-sm">
                    <NumberField.DecrementButton className="w-8" />
                    <NumberField.Input className="w-10 text-center" />
                    <NumberField.IncrementButton className="w-8" />
                  </NumberField.Group>
                </NumberField>

                {variant === "full" && (
                  <span className="text-sm font-semibold text-[#236f6b]">
                    {formatPrice(lineTotal)}
                  </span>
                )}
              </div>
            </div>
          </div>
        </div>
      </Card.Content>
    </Card>
  );
}

function TrashIcon() {
  return (
    <svg
      width="16"
      height="16"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <polyline points="3 6 5 6 21 6" />
      <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
      <line x1="10" y1="11" x2="10" y2="17" />
      <line x1="14" y1="11" x2="14" y2="17" />
    </svg>
  );
}
