"use client";

import Image from "next/image";
import { PlusIcon } from "@/modules/icons/plus-icon";
import { useCartStore } from "@/zustand/cartStore";
import {
  CartInformationModal,
  CartResponse,
} from "@/lib/types/models/shopping-cart";
import { usePreviewSlider } from "@/lib/context/preview-slider-context";
import RemoveItemCart from "@/modules/cart/components/remove-item";
import CloneItemCart from "@/modules/cart/components/clone-item";
import ShopItemCart from "@/modules/cart/components/shop-later-item";
import ClearCartItem from "@/modules/cart/components/clear-cart-item";
import EditCartItem from "@/modules/cart/components/edit-cart-item";
import orderService from "@/lib/services/order";
import { getStoreData } from "@/lib/utils/storagedata";
import shoppingCartService from "@/lib/services/shoppingcart";
import { Dropdown as SelectDropdown } from "@/modules/ui/select-dropdown";
import { computeTierPrice } from "@/lib/utils/orderPricing";

export default function Page() {
  const { cartItems, setCartItems } = useCartStore();
  const { openPreviewModal } = usePreviewSlider();

  const updateQuantity = async (data: CartInformationModal, val: number, price: number) => {
    const { _id } = data;
    const body = {
      documentId: _id,
      quantity: val,
      price: Number(price),
    };

    const response = await orderService.updateOrder(body);
    if (response.success) {
      const token = await getStoreData<string>("token");
      const cartResponse: CartResponse = token
        ? await shoppingCartService.getShoppingCart(token, 'incart')
        : { success: false, data: [] };
      const data = cartResponse.success ? cartResponse?.data : [];
      setCartItems(data);
    }
  };

  const handlePreviewSlider = (item: CartInformationModal) => {
    const images: string[] = (item?.artworkFiles || []).map((side) => side.image || "");
    openPreviewModal(images);
  };
  console.log(cartItems)


  return (
    <>
      <div className="flex justify-between items-center">
        <h1 className="text-xl md:text-3xl font-bold text-gray-900 ">
          Your Shopping Cart
        </h1>
        {cartItems?.length > 0 && <ClearCartItem />}
      </div>
      {cartItems.map((item, index) => {
        const detailArray = item?.productId?.options || [];
        const totalExtraPrice = detailArray.reduce((sum: number, opt) => {
          const price = opt?.extraPrice ? Number(opt.extraPrice) : 0;
          return sum + price;
        }, 0);

        const rawTiers = item?.productId?.quantityOptions?.length
          ? item?.productId?.quantityOptions
          : [];

        const computedQuantities = (rawTiers || [])
          .filter((tier) => tier.status !== false)
          .map((tier) => {
            const calc = computeTierPrice(tier, totalExtraPrice);
            return {
              _id: tier._id,
              quantity: calc.quantity,
              price: calc.totalPrice,
              markBasePrice: calc.unitPrice,
              percentage: calc.discountPercent,
              unitPrice: calc.unitPrice,
              totalPrice: calc.totalPrice,
              withoutpercentageprice: calc.baseUnitPrice,
            };
          });
        return (
          <div
            key={index}
            className="p-4 md:p-6 bg-white border border-gray-200 rounded-lg shadow-sm"
          >
            <div className="flex flex-col md:flex-row md:items-center justify-between mb-4 md:mb-6 gap-4">
              <h2 className="text-base md:text-lg font-semibold text-gray-900 bg-gray-100 px-3 md:px-4 py-2 rounded">
                {item?.productId?.parentId?.name}
              </h2>
              <div className="flex flex-wrap gap-2">
                <CloneItemCart data={item} />
                <EditCartItem data={item} />
                <ShopItemCart data={item} />
                <RemoveItemCart id={item?._id} isCart={false} />
              </div>
            </div>

            <div className="flex flex-col md:flex-row gap-4 md:gap-6">
              <div className="flex-shrink-0 relative self-center md:self-start">
                <Image
                  src={item?.artworkFiles?.[0]?.image || "/assets/images/logo.png"}
                  alt={item._id}
                  width={150}
                  height={120}
                  className="rounded-lg object-cover w-[150px] h-auto"
                />

                <button
                  onClick={() => handlePreviewSlider(item)}
                  className="absolute bottom-2 md:bottom-3 right-2 bg-white p-1 rounded-full shadow hover:bg-gray-100 z-10"
                >
                  <PlusIcon />
                </button>
              </div>

              <div className="flex-1 grid grid-cols-1 lg:grid-cols-3 gap-4">
                <div className="xl:col-span-2 ">
                  <div className="space-y-1">
                    {item?.productId?.options && item.productId.options.length > 0 &&
                      item.productId.options.map((detailItem, index) => {
                        return (
                          <div
                            className="flex md:flex-row md:items-center gap-1 text-black text-sm md:text-base"
                            key={index}
                          >
                            <span className="font-bold">
                              {detailItem.variantItemId?.variantId?.attributeType?.name} :
                            </span>
                            <span className="text-black">
                              {detailItem.variantItemId?.attributeItemId?.displayName}
                            </span>
                          </div>
                        );
                      })}

                    {/* {item.productId.turnaroundOptions. && (
                      <div className="flex md:flex-row md:items-center gap-1 text-black text-sm md:text-base">
                        <span className="font-bold">Printing Time :</span>
                        <span className="text-black">
                          {item.TurnAroundTime}
                        </span>
                      </div>
                    )} */}
                  </div>
                </div>
                <div className="xl:col-span-1 space-y-1space-y-1">

                  {item.quantity && (
                    <SelectDropdown
                      disabled={false}
                      isSearchable={false}
                      isFullRounded={false}
                      options={computedQuantities || []}
                      label="quantity"
                      value="quantity"
                      selected={Number(item?.quantity)}
                      onChange={(e) => {
                        e && updateQuantity(item, Number(e?.quantity), Number(e?.totalPrice))

                      }
                      }
                    />
                  )}
                </div>
              </div>
              <div className="flex-shrink-0 text-left md:text-right mt-4 lg:mt-0">
                <div className="text-lg md:text-xl font-bold text-gray-900">
                  ${(Number(item?.price) + (item.pdfProofAmount ? Number(item.pdfProofAmount) : 0))?.toFixed(2)}
                </div>
              </div>
            </div>
          </div>
        );
      })}

      {cartItems.length === 0 && (
        <div className="p-8 md:p-12 text-center bg-white border border-gray-200 rounded-lg shadow-sm">
          <p className="text-gray-500 text-base md:text-lg">
            Your cart is empty
          </p>
        </div>
      )}
    </>
  );
}
