"use client";

import Image from "next/image";
import DeleteProductComponent from "@/components/delete-product-component";
import { getCartProducts, removeFromCart } from "@/store/slices/cart-slice";
import { useAppDispatch } from "@/store/hooks";
import toast from "react-hot-toast";
import { useState } from "react";
import { useTranslations } from "next-intl";
import StarRating from "./react-stars";
import ProductIncementOrDecrement from "./product-increment-or-decrement";
import { normalizePriceString, formatCurrency } from "@/lib/utils";
import { usePathname } from "next/navigation";
import { useLocale } from "next-intl";

interface CartProductProps {
  product: any;
  quantity: number | string;
  deletedProductId: number | string;
  cartItem?: any;
}

export default function CartProduct({
  product,
  quantity,
  deletedProductId,
  cartItem,
}: CartProductProps) {
  const qty = parseInt(String(quantity ?? 0), 10);
  const dispatch = useAppDispatch();
  const tToast = useTranslations("toast");
  const tProducts = useTranslations("products");
  const [isOpen, setIsOpen] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);
  const pathname = usePathname();
  const locale = pathname?.split("/")?.[1] || "ar";
  const currentLocale = useLocale();

  const handleDelete = async (productId: number | string) => {
    try {
      setIsDeleting(true);
      await dispatch(removeFromCart({ productId: Number(productId) })).unwrap();
      await dispatch(getCartProducts());
      toast.success(tToast("product-deleted"));
      setIsOpen(false);
    } catch (error) {
      console.error("Failed to remove product from cart:", error);
    } finally {
      setIsDeleting(false);
    }
  };

  /* ---- Extract product details (same logic as home page ProductCard) ---- */
  const brandName = product?.brand?.name || product?.brand_name || (currentLocale === "ar" ? "بالمي" : "Balmy");
  const productName = product?.name || "";
  const truncatedName =
    productName.length > 30 ? productName.slice(0, 30) + "..." : productName;
  const productDescription =
    product?.shortDescription ||
    product?.short_description ||
    product?.description ||
    "عطر فاخر بتركيبة مميزة تدوم طويلاً";

  const specialPrice = product?.special_price
    ? Number(product.special_price)
    : null;
  const rawPrice = Number(product?.price) || 0;
  
  // Base unit price
  const unitPrice = specialPrice && specialPrice > 0 ? specialPrice : rawPrice;
  const oldPrice =
    product?.original_price
      ? Number(product.original_price)
      : specialPrice && specialPrice > 0
        ? rawPrice
        : product?.price_regular?.value
          ? Number(product.price_regular.value)
          : null;
  const discount =
    product?.discount_percent ||
    (oldPrice && oldPrice > unitPrice
      ? Math.round(((oldPrice - unitPrice) / oldPrice) * 100)
      : 0);

  // Use the backend's computed cart item fields if available, otherwise manually calculate (fallback)
  const total = Number(cartItem?.total || cartItem?.base_total) || (unitPrice * qty);
  
  // Prioritize the API's formatted total to avoid rendering decimals if the backend already provides a clean format
  const formattedPrice = cartItem?.formated_total 
    ? normalizePriceString(cartItem.formated_total, locale) 
    : formatCurrency(total, locale);
    
  const formattedOldPrice = oldPrice && oldPrice > unitPrice ? formatCurrency(oldPrice * qty, locale) : null;

  const category =
    typeof product?.category === "string"
      ? product.category
      : product?.category?.name ?? "";

  const imageUrl =
    product?.base_image?.original_image_url ||
    product?.thumbNail ||
    product?.images?.[0]?.url ||
    product?.image ||
    product?.base_image?.url ||
    "/placeholder.png";

  return (
    <div
      className={`flex flex-col gap-2 w-full rounded-xl border border-gray-200 bg-white overflow-hidden font-[family-name:var(--font-cairo)] transition-opacity duration-300 ${isDeleting ? 'opacity-50 pointer-events-none' : ''}`}
     
    >
      {/* Top row: Image + Info */}
      <div className="flex gap-3 p-3">
        {/* Product Image */}
        <div className="relative flex-shrink-0">
          <Image
            src={imageUrl}
            alt={productName || tProducts("product")}
            width={100}
            height={100}
            className="rounded-lg object-contain bg-gray-50 w-[90px] h-[90px] md:w-[110px] md:h-[110px] border border-gray-100"
          />
        </div>

        {/* Product Details */}
        <div className="flex flex-col gap-1 flex-1 min-w-0">
          {/* Brand + Category */}
          <div className="flex items-center gap-2">
            <p className="text-[13px] font-semibold text-gray-800 truncate">
              {brandName}
              <Image
                src="/icons svg/Twitter_Verified_Badge.svg.png"
                alt="verified"
                width={14}
                height={14}
                className="w-3.5 h-3.5 inline-block ms-1 align-middle flex-shrink-0"
                style={{ display: "inline-block" }}
              />
            </p>
            {category && (
              <span className="inline-block text-[10px] font-medium text-white bg-[#B5B5B5] rounded-md px-2 py-0.5 flex-shrink-0">
                {category}
              </span>
            )}
          </div>

          {/* Product Name / Description */}
          <p className="text-[12px] text-gray-500 line-clamp-1 leading-relaxed">
            {truncatedName || productDescription}
          </p>

          {/* Price Row */}
          <div className="flex items-baseline gap-2 mt-0.5">
            <span className="text-[15px] font-bold text-gray-900">
              {formattedPrice}
            </span>
            {formattedOldPrice && oldPrice && oldPrice > unitPrice && (
              <span className="text-gray-400 line-through text-[12px]">
                {formattedOldPrice}
              </span>
            )}
          </div>

          {/* Stars + Discount */}
          <div className="flex items-center gap-2 mt-0.5">
            <StarRating rating={5} inline className="inline-flex" size={14} />
            {discount > 0 && (
              <span
                className="inline-flex items-center justify-center rounded-full text-[10px] font-bold text-white px-1.5 py-0.5"
                style={{ backgroundColor: "#ef4444", minWidth: "32px" }}
              >
                %{discount}
              </span>
            )}
          </div>
        </div>
      </div>

      {/* Bottom row: Actions */}
      <div className="flex items-center justify-between px-3 pb-3">
        <DeleteProductComponent
          isOpen={isOpen}
          setIsOpen={setIsOpen}
          action={() => handleDelete(deletedProductId)}
          isActionLoading={isDeleting}
        />
        {/* Increment / Decrement */}
        <div className="bg-[#3866df] text-white py-1 px-2 rounded-md">
          <ProductIncementOrDecrement product={product} quantity={qty} />
        </div>
      </div>
    </div>
  );
}
