"use client";

import { Trash2 } from "lucide-react";
import Image from "next/image";
import { Button } from "@/components/ui/button";
import { TableCell, TableRow } from "@/components/ui/table";
import { CartItemWithProduct } from "../types";

interface CartItemRowProps {
  item: CartItemWithProduct;
  onUpdateQuantity: (productId: string, quantity: number) => void;
  onRemoveItem: (productId: string) => void;
}

export default function CartItemRow({
  item,
  onUpdateQuantity,
  onRemoveItem,
}: CartItemRowProps) {
  const { product, quantity } = item;
  const maxQty = product.stock;

  const handleDecrement = () => {
    if (quantity > 1) {
      onUpdateQuantity(product.id, quantity - 1);
    }
  };

  const handleIncrement = () => {
    if (quantity < maxQty) {
      onUpdateQuantity(product.id, quantity + 1);
    }
  };

  return (
    <TableRow>
      <TableCell className="whitespace-normal">
        <div className="flex items-center">
          <div className="relative h-10 w-10 overflow-hidden rounded">
            <Image
              src={product.image}
              alt={product.name}
              fill
              className="object-contain"
            />
          </div>
        </div>
      </TableCell>

      <TableCell className="whitespace-normal">
        <div className="flex items-center gap-1">
          <Button
            variant="ghost"
            size="icon"
            className="h-6 w-6"
            onClick={handleDecrement}
            disabled={quantity <= 1}
          >
            ‑
          </Button>
          <span className="w-10 h-6 text-center text-sm border rounded-full">
            {quantity}
          </span>
          <Button
            variant="ghost"
            size="icon"
            className="h-6 w-6"
            onClick={handleIncrement}
            disabled={quantity >= maxQty}
          >
            +
          </Button>
        </div>
      </TableCell>

      <TableCell className="whitespace-normal ">
        <span className="text-sm">${product.price.toFixed(2)}</span>
      </TableCell>

      <TableCell className="whitespace-normal">
        <Button
          variant="ghost"
          size="sm"
          onClick={() => onRemoveItem(product.id)}
          className="h-6 w-6 p-0 text-destructive hover:text-destructive"
        >
          <Trash2 className="h-3 w-3" />
        </Button>
      </TableCell>
    </TableRow>
  );
}
