"use client";

import React, { useEffect } from "react";
import OrderSummaryItem from "./OrderSummaryItem";
import { useCart } from "@/hooks/useCart";

interface OrderSummaryProps {
  onPlaceOrder?: () => void;
  isLoading?: boolean;
  onTotalCalculated?: (total: number) => void;
}

const OrderSummary = ({ onPlaceOrder, isLoading = false, onTotalCalculated }: OrderSummaryProps) => {
  const { cart, fetchCart } = useCart();

  useEffect(() => {
    if (!cart || cart.length === 0) {
      fetchCart();
    }
  }, []);

  // Handle Decimal128 values from MongoDB
  const getPrice = (val: any) =>
    typeof val === "object"
      ? Number(val?.$numberDecimal ?? 0)
      : Number(val ?? 0);

  const subtotal =
    cart?.reduce((sum: number, item: any) => {
      return sum + getPrice(item.product?.price) * item.quantity;
    }, 0) ?? 0;

  const packingCharge = 0;
  const tax = 0;
  const grandTotal = subtotal + packingCharge + tax;

  // Pass grand total to parent component
  useEffect(() => {
    if (onTotalCalculated) {
      onTotalCalculated(grandTotal);
    }
  }, [grandTotal, onTotalCalculated]);

  const formatPrice = (amount: number) =>
    `₹ ${amount.toLocaleString("en-IN", {
      minimumFractionDigits: 2,
    })}`;

  return (
    <div className="cartsummarybx">
      <div className="section-heading">
        <h2>Order Summary</h2>
      </div>

      {/* Products */}
      {cart?.length > 0 && (
        <div className="responsiveList">
          <div className="responsiveListinner">
            {cart.map((item: any) => (
              <OrderSummaryItem
                key={item._id ?? item.sku?._id}
                item={{
                  id: item._id ?? item.sku?._id,
                  name: item.product?.name,
                  image: item.product?.defaultImage,
                  size: item.sku?.size?.name || "",
                  quantity: item.quantity,
                  price: getPrice(item.product?.price),
                }}
              />
            ))}
          </div>
        </div>
      )}

      {/* Empty Cart */}
      {!cart?.length && (
        <div className="text-center py-4">
          <p>Your cart is empty.</p>
        </div>
      )}

      {/* Summary */}
      <div id="cartSummary">
        <div className="flex flex-wrap borderbtm pb-3">
          <span className="w-6/12 cart__subtotal-title">Subtotal</span>
          <span className="w-6/12 text-right">
            <span className="money">{formatPrice(subtotal)}</span>
          </span>
        </div>

        {/* <div className="flex flex-wrap borderbtm pb-3 pt-3">
          <span className="w-6/12 cart__subtotal-title">Packing Charge</span>
          <span className="w-6/12 text-right">
            {packingCharge === 0 ? 'Free' : formatPrice(packingCharge)}
          </span>
        </div> */}

        <div className="flex flex-wrap borderbtm pb-3 pt-3">
          <span className="w-6/12 cart__subtotal-title">Tax</span>
          <span className="w-6/12 text-right">
            {formatPrice(tax)}
          </span>
        </div>

        <div className="flex flex-wrap borderbtm pb-3 pt-3">
          <span className="w-6/12 cart__subtotal-title">
            <strong>Grand Total</strong>
          </span>
          <span className="w-6/12 cart__subtotal text-right">
            <strong className="money">
              {formatPrice(grandTotal)}
            </strong>
          </span>
        </div>
      </div>

      {/* Place Order Button */}
      <div className="order-button-payment mt-2 clearfix">
        <button
          type="submit"
          className="theme-btn w-full gap-2 justify-center"
          disabled={!cart?.length || isLoading}
          onClick={onPlaceOrder}
        >
          {isLoading ? (
            <>
              <i className="fa fa-spinner fa-pulse mr-2"></i>
              Processing...
            </>
          ) : (
            <>
              <span>Place Order</span>
              <i className="icon icon-arrow-right"></i>
            </>
          )}
        </button>
      </div>
    </div>
  );
};

export default OrderSummary;