"use client";
import { User } from "@/constants/types";
import React, { useState } from "react";
import { useSelector } from "react-redux";

export interface CartItem {
  packId: number;
  packName: string;
  quantity: number;
  price: number; // per pack price
}

interface CartProps {
  cart: CartItem[];
  onPurchase: () => void;
  onRemove: (packId: number) => void;
}

export const Cart: React.FC<CartProps> = ({ cart, onPurchase, onRemove }) => {
  const [removingIds, setRemovingIds] = useState<number[]>([]);

  // TOTAL QUANTITY IN CART
  const totalQuantity = cart.reduce((sum, item) => sum + item.quantity, 0);
  const user = useSelector((state: any) => state.auth.user) as User | null;

  // ---- OLD PROJECT STYLE DISCOUNT LOGIC ----
  let subtotal = 0;
  let discountRaw = 0;

  for (const item of cart) {
    const lineTotal = item.price * item.quantity;
    subtotal += lineTotal;

    if (item.quantity > 5 && item.quantity < 36) {
      discountRaw += (lineTotal * 5) / 100;
    } else if (item.quantity > 35 && item.quantity < 216) {
      discountRaw += (lineTotal * 10) / 100;
    } else if (item.quantity >= 216) {
      discountRaw += (lineTotal * 15) / 100;
    }
  }

  // const discount = Number(discountRaw.toFixed(2));
  // const total = Number((subtotal - discount).toFixed(2));
  const total = Number(subtotal.toFixed(2));

  // -----------------------------------------
  // function getDiscountMessage(quantity: number) {
  //   if (quantity < 6) return "Get a discount when you purchase 6";
  //   if (quantity < 36) return "Get a discount when you purchase 36";
  //   if (quantity < 216) return "Get a discount when you purchase 216";
  //   return "You’re getting the maximum discount!";
  // }

  const handleRemoveClick = (packId: number) => {
    if (removingIds.includes(packId)) return;

    // Start exit animation
    setRemovingIds((prev) => [...prev, packId]);

    // Wait for animation to finish, then actually remove from parent state
    setTimeout(() => {
      onRemove(packId);
      setRemovingIds((prev) => prev.filter((id) => id !== packId));
    }, 300); // matches Tailwind duration-300
  };

  return (
    <div className="bg-[#1a1d29] rounded-lg p-3 md:p-6">
      <h2 className="text-white text-sm md:text-2xl 2xl:text-[30px] font-sofia font-extrabold mb-6">
        YOUR CART
      </h2>

      {/* Header */}
      <div className="flex text-xs md:text-sm 2xl:text-base text-white font-normal font-onest mb-2">
        <div className="flex-1 ">Items</div>
        <div className="w-24 text-center">Quantity</div>
        <div className="w-24 text-right ">Price</div>
      </div>

      {/* Rows */}
      <div className="mb-3 md:mb-4 2xl:mb-6">
        {cart.map((item, ind) => {
          const isRemoving = removingIds.includes(item.packId);

          return (
            <div
              key={item.packId}
              className={`
                ${ind % 2 === 1 ? "bg-[#202A38]" : ""}
                flex items-center 2xl:text-base pl-2 font-onest text-xs md:text-sm text-white
                transform transition-all duration-300 ease-out
                ${
                  isRemoving
                    ? "-translate-x-1/5 opacity-0"
                    : "translate-x-0 opacity-100"
                }
              `}
            >
              <div className="flex-1 py-3 pr-2">{item.packName}</div>

              <div className="w-24  text-center py-3">{item.quantity}</div>

              <div className="w-24 text-right py-3 flex items-center gap-1 pr-2">
                {!user ? (
                  <img
                    src="/images/header/win.svg"
                    alt=""
                    className="h-4 w-4"
                  />
                ) : (
                  <>
                    {user?.activeMode === "coins" ? (
                      <img
                        src="/images/header/win.svg"
                        alt=""
                        className="h-4 w-4"
                      />
                    ) : (
                      <img
                        src="/images/header/star.svg"
                        alt=""
                        className="h-4 w-4"
                      />
                    )}
                  </>
                )}
                {(item.price * item.quantity).toFixed(2)}
              </div>

              {/* ✕ remove button */}
              <button
                onClick={() => handleRemoveClick(item.packId)}
                className="px-2 text-xs md:text-sm text-white/70 hover:text-red-400 transition-colors"
              >
                ✕
              </button>
            </div>
          );
        })}

        {cart.length === 0 && (
          <div className="px-4 py-4 text-white text-center text-sm">
            Cart is empty
          </div>
        )}
      </div>

      {/* Discount & total */}
      <div className="space-y-1">
        {/* <div className="flex justify-between font-extrabold font-sofia text-sm md:text-lg 2xl:text-xl">
          <span className="text-white">DISCOUNT</span>
          <span className="text-white">${discount.toFixed(2)}</span>
        </div> */}
        <div className="flex justify-between font-extrabold font-sofia text-sm md:text-lg 2xl:text-xl">
          <span className="text-white">TOTAL</span>
          <span className="text-white flex items-center gap-2">
            {!user ? (
              <img src="/images/header/win.svg" alt="" className="h-4 w-4" />
            ) : (
              <>
                {user?.activeMode === "coins" ? (
                  <img
                    src="/images/header/win.svg"
                    alt=""
                    className="h-4 w-4"
                  />
                ) : (
                  <img
                    src="/images/header/star.svg"
                    alt=""
                    className="h-4 w-4"
                  />
                )}
              </>
            )}
            {total.toFixed(2)}
          </span>
        </div>
      </div>

      {/* <div className="mt-4 flex items-start gap-2 text-xs">
        <img src="/images/shop/!.svg" alt="!" />
        <p className="text-gray-300">{getDiscountMessage(totalQuantity)}</p>
      </div> */}

      <button
        onClick={onPurchase}
        disabled={cart.length === 0}
        className="w-full mt-6 cursor-pointer text-xs md:text-sm 2xl:text-base bg-[var(--color-blue)] hover:bg-[var(--color-hoverBlue)] font-onest disabled:cursor-not-allowed text-white font-bold py-4  transition-colors duration-500"
      >
        PURCHASE
      </button>
    </div>
  );
};
