'use client';

import Link from 'next/link';
import Image from "next/image";
import { useRouter } from 'next/navigation';
import {
  JSXElementConstructor,
  ReactElement,
  ReactNode,
  ReactPortal,
  useEffect,
  useState
} from "react";
import Swal from 'sweetalert2';

import { useSession } from "next-auth/react";

import {
  fetchCart,
  updateCartItem,
  removeFromCart
} from '../../lib/slices/cartSlice';

import { useAppDispatch, useAppSelector } from '@/lib/hooks';
import { getSessionId } from '@/lib/session';
import { StaticImport } from 'next/dist/shared/lib/get-img-props';

import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faXmark } from "@fortawesome/free-solid-svg-icons";

// Interface definitions
interface Offer {
  id: number;
  category_id: string;
  user_emails: string;
  buy_unit_from: string;
  buy_unit_to: string;
  total_units: string;
  offer_type: string;
  discount_type: string;
  discount: string;
  offer_applicable_on: string;
  is_each: string;
  start_date: string;
  end_date: string;
  offer_description: string;
  status: string;
  created_at: string;
  updated_at: string;
}

interface CartCategory {
  id: number;
  session_id: string;
  user_id: null;
  product_id: string;
  category_id: string;
  size: string;
  quantity: string;
  change_price: string;
  offer_applicable: string;
  offer_used: string;
  expiry_date: string;
  first_reminder_date: string;
  first_reminder_time: string;
  second_reminder_date: string;
  third_reminder_date: string;
  first_reminder_sent: string;
  second_reminder_sent: string;
  third_reminder_sent: string;
  created_at: string;
  updated_at: string;
  cart_sum_count: string;
  offer_category: Offer;
  product?: {
    price: string;
    mrp: string;
    final_price: string;
    product_name: string;
  };
}

interface CartItem {
  id: number;
  product: {
    id?: string | number;
    mrp: ReactNode;
    discount: ReactNode;
    product_image: {
      image: string | StaticImport;
    };
    product_name: string | number | bigint | boolean | ReactElement<unknown, string | JSXElementConstructor<any>> | Iterable<ReactNode> | Promise<any> | null | undefined;
    price: string | number | bigint | boolean | ReactElement<unknown, string | JSXElementConstructor<any>> | Iterable<ReactNode> | Promise<any> | null | undefined;
  };
  size: any;
  quantity: number;
}

export default function Cart() {

  const router = useRouter();
  const dispatch = useAppDispatch();

  const {
    items,
    total,
    loading,
    error
  } = useAppSelector(state => state.cart);

  console.log('cart items : ', items);

  const session = useSession();
  const sessionId = getSessionId();

  let token = '';
  if (session?.data?.user?.token) {
    token = session.data.user.token;
  } else {
    token = '';
  }

  /*
  |--------------------------------------------------------------------------
  | Coupon States
  |--------------------------------------------------------------------------
  */

  const [showCouponModal, setShowCouponModal] = useState(false);
  const [couponCode, setCouponCode] = useState('');
  const [couponError, setCouponError] = useState('');
  const [isApplyingCoupon, setIsApplyingCoupon] = useState(false);
  const [appliedCoupon, setAppliedCoupon] = useState<{
    coupon_code: string;
    discount_amount: number;
    original_total: number;
    discounted_total: number;
  } | null>(null);

  /*
  |--------------------------------------------------------------------------
  | Offer State
  |--------------------------------------------------------------------------
  */

  const [offers, setOffers] = useState<string>('');
  
  /*
  |--------------------------------------------------------------------------
  | Cart Categories State (for dynamic offer messages)
  |--------------------------------------------------------------------------
  */
  
  const [cartCategories, setCartCategories] = useState<CartCategory[]>([]);

  /*
  |--------------------------------------------------------------------------
  | Offer Discount State
  |--------------------------------------------------------------------------
  */
  
  const [offerDiscount, setOfferDiscount] = useState<number>(0);

  /*
  |--------------------------------------------------------------------------
  | Load Coupon & Offer Discount from localStorage
  |--------------------------------------------------------------------------
  */

  useEffect(() => {
    // Load saved coupon
    const savedCoupon = localStorage.getItem('applied_coupon');
    if (savedCoupon) {
      try {
        const couponData = JSON.parse(savedCoupon);
        setAppliedCoupon(couponData);
      } catch (e) {
        console.error('Failed to parse coupon data:', e);
      }
    }

    // Load saved offer discount
    const savedOfferDiscount = localStorage.getItem('offer_discount');
    if (savedOfferDiscount) {
      try {
        const discount = parseFloat(savedOfferDiscount);
        if (!isNaN(discount) && discount > 0) {
          setOfferDiscount(discount);
        }
      } catch (e) {
        console.error('Failed to parse offer discount:', e);
      }
    }
  }, []);

  /*
  |--------------------------------------------------------------------------
  | Format Amount (Helper)
  |--------------------------------------------------------------------------
  */

  const formatAmount = (price: string | number): string => {
    const numPrice = typeof price === 'string' ? parseFloat(price) : price;
    if (isNaN(numPrice)) return '0';
    return numPrice.toLocaleString('en-IN', {
      maximumFractionDigits: 2,
      minimumFractionDigits: 2
    });
  };

  /*
  |--------------------------------------------------------------------------
  | Get Offer Price Based on Description
  |--------------------------------------------------------------------------
  */

  const getOfferPrice = (offerDescription: string): string => {
    const offerMap: { [key: string]: string } = {
      '2 for 999': '₹ 499!',
      '3 for 999': '₹ 333!',
      '2 for 1399': '₹ 699!',
      '2 for 1199': '₹ 599!',
    };
    
    return offerMap[offerDescription] || '₹ 0!';
  };

  /*
  |--------------------------------------------------------------------------
  | Generate Offer Message
  |--------------------------------------------------------------------------
  */

  const generateOfferMessage = (cartCategoriesData: CartCategory[]): string => {
    if (!cartCategoriesData || cartCategoriesData.length === 0) {
      return '';
    }

    let messages: string[] = [];

    cartCategoriesData.forEach((cartCategory: CartCategory) => {
      const offer = cartCategory.offer_category;
      if (!offer) return;

      const cartSumCount = parseInt(cartCategory.cart_sum_count || '0');
      const totalUnits = parseInt(offer.total_units || '0');
      
      // Check if the offer is not yet fully utilized
      if (cartSumCount < totalUnits) {
        const remainingUnits = totalUnits - cartSumCount;
        const offerPrice = getOfferPrice(offer.offer_description);

        // Check if it's a "Buy X Get Y Free" type offer
        if (offer.offer_description && offer.offer_description.toLowerCase().includes('buy')) {
          messages.push(
            `Product added to cart! Add ${remainingUnits} more product to grab ${offer.offer_description} offer`
          );
        } else {
          // For "2 for 999" type offers - use product price from the cart
          // We need to get the product price from the cart item
          const productPrice = 799; // Default fallback
          messages.push(
            `Nice pick! Add another item worth ₹${formatAmount(productPrice)} from this offer and snag this product for only ${offerPrice}`
          );
        }
      }
    });

    return messages.join(' | ');
  };

  /*
  |--------------------------------------------------------------------------
  | Quantity Change
  |--------------------------------------------------------------------------
  */

  const handleQuantityChange = (cartId: number, newQuantity: number) => {
    console.log("newQuantity : ", newQuantity);

    if (newQuantity < 1) {
      return;
    }

    dispatch(
      updateCartItem({
        sessionId: sessionId,
        cartId: cartId,
        quantity: Number(newQuantity)
      })
    );
    
    // Fetch updated cart data after quantity change
    setTimeout(async () => {
      const cartResult = await dispatch(
        fetchCart({
          session_id: sessionId,
          token: token,
        })
      ).unwrap();

      // Update offers and cart categories
      updateOfferData(cartResult);
    }, 500); // Small delay to allow the update to complete
  };

  /*
  |--------------------------------------------------------------------------
  | Remove Item
  |--------------------------------------------------------------------------
  */

  const handleRemoveItem = (cartId: number, session_id: string, token: string) => {
    Swal.fire({
      title: 'Are you sure?',
      text: "You won't be able to remove this! ",
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#2ee44cff',
      cancelButtonColor: 'rgba(222, 41, 50, 1)',
      confirmButtonText: 'Yes, delete it!'
    }).then(async (result: { isConfirmed: any; }) => {
      if (result.isConfirmed) {
        await dispatch(
          removeFromCart({
            cartId: cartId,
            session_id: session_id,
            token: token
          })
        ).unwrap();

        const cartResult = await dispatch(
          fetchCart({
            session_id: sessionId,
            token: token,
          })
        ).unwrap();

        // Update offers and cart categories
        updateOfferData(cartResult);

        router.refresh();
      }
    });
  };

  /*
  |--------------------------------------------------------------------------
  | Discount Total
  |--------------------------------------------------------------------------
  */

  const getDiscountedTotal = () => {
    let discountedTotal = total;
    
    // Apply offer discount first (before coupon)
    if (offerDiscount > 0) {
      discountedTotal = Math.max(discountedTotal - offerDiscount, 0);
    }
    
    // Then apply coupon discount
    if (appliedCoupon) {
      discountedTotal = Math.max(
        discountedTotal - Number(appliedCoupon.discount_amount),
        0
      );
    }
    
    return discountedTotal;
  };

  /*
  |--------------------------------------------------------------------------
  | Apply Coupon
  |--------------------------------------------------------------------------
  */

  const handleApplyCoupon = async () => {
    if (!couponCode.trim()) {
      setCouponError('Please enter a coupon code');
      return;
    }

    setIsApplyingCoupon(true);
    setCouponError('');

    try {
      console.log('Applying coupon:', couponCode.trim(), 'Session ID:', sessionId, 'Total:', total, 'Token:', token);

      const response = await fetch(
        `${process.env.NEXT_PUBLIC_API_URL}/api/user/coupon-code-apply`,
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${token}`,
          },
          body: JSON.stringify({
            coupon_code: couponCode.trim(),
            session_id: sessionId,
            cart_total: total,
          }),
        }
      );

      const data = await response.json();
      console.log('Coupon API response:', data);

      if (!response.ok) {
        throw new Error(data.message || 'Failed to apply coupon');
      }

      if (data.status === true) {
        const discountAmount = Number(data.code_discount_total || 0);
        const discountedTotal = Math.max(total - offerDiscount - discountAmount, 0);

        const couponData = {
          coupon_code: data.coupon_code || couponCode.trim(),
          discount_amount: discountAmount,
          original_total: total,
          discounted_total: discountedTotal,
        };

        localStorage.setItem('applied_coupon', JSON.stringify(couponData));
        setAppliedCoupon(couponData);

        Swal.fire({
          title: 'Coupon Applied!',
          text: data.message || `Coupon "${couponCode.trim()}" has been applied successfully. You saved ₹${discountAmount.toFixed(2)}`,
          icon: 'success',
          confirmButtonColor: '#2ee44cff',
          confirmButtonText: 'OK'
        });

        setCouponCode('');
        setCouponError('');
        setShowCouponModal(false);

        const cartResult = await dispatch(
          fetchCart({
            session_id: sessionId,
            token: token,
          })
        ).unwrap();

        updateOfferData(cartResult);
      } else {
        throw new Error(data.message || 'Failed to apply coupon');
      }
    } catch (error: any) {
      console.error('Coupon application error:', error);
      setCouponError(error.message || 'Failed to apply coupon. Please try again.');
    } finally {
      setIsApplyingCoupon(false);
    }
  };

  /*
  |--------------------------------------------------------------------------
  | Remove Coupon
  |--------------------------------------------------------------------------
  */

  const handleRemoveCoupon = () => {
    Swal.fire({
      title: 'Remove Coupon?',
      text: `Are you sure you want to remove the coupon "${appliedCoupon?.coupon_code}"?`,
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#ef4444',
      cancelButtonColor: '#6b7280',
      confirmButtonText: 'Yes, remove it!',
      cancelButtonText: 'Cancel'
    }).then(async result => {
      if (result.isConfirmed) {
        localStorage.removeItem('applied_coupon');
        setAppliedCoupon(null);

        Swal.fire({
          title: 'Coupon Removed!',
          text: 'Coupon has been removed successfully.',
          icon: 'success',
          confirmButtonColor: '#2ee44cff',
          confirmButtonText: 'OK'
        });

        const cartResult = await dispatch(
          fetchCart({
            session_id: sessionId,
            token: token,
          })
        ).unwrap();

        updateOfferData(cartResult);
      }
    });
  };

  /*
  |--------------------------------------------------------------------------
  | Close Coupon Modal
  |--------------------------------------------------------------------------
  */

  const handleCloseModal = () => {
    setShowCouponModal(false);
    setCouponCode('');
    setCouponError('');
    setIsApplyingCoupon(false);
  };

  /*
  |--------------------------------------------------------------------------
  | Update Offer Data
  |--------------------------------------------------------------------------
  */

  const updateOfferData = (cartResult: any) => {
    console.log('Updating offer data with:', cartResult);

    // Set offer discount from cartPricing and store in localStorage
    if (cartResult?.cartPricing?.offer_discount !== undefined) {
      const discount = Number(cartResult.cartPricing.offer_discount);
      console.log('Offer discount from API:', discount);
      setOfferDiscount(discount);
      
      // Store offer discount in localStorage
      if (discount > 0) {
        localStorage.setItem('offer_discount', discount.toString());
      } else {
        localStorage.removeItem('offer_discount');
      }
    }

    // Set cart categories for dynamic offer message generation
    if (cartResult?.CartCategory && Array.isArray(cartResult.CartCategory) && cartResult.CartCategory.length > 0) {
      setCartCategories(cartResult.CartCategory);
      
      // Generate dynamic offer message
      const dynamicMessage = generateOfferMessage(cartResult.CartCategory);
      console.log('Generated dynamic message:', dynamicMessage);
      
      if (dynamicMessage) {
        setOffers(dynamicMessage);
        return;
      }
    }

    // Fallback: Get offers from response
    const apiOffers = cartResult?.offers ?? cartResult?.cartmessage ?? cartResult?.cart_message ?? cartResult?.offer_message ?? cartResult?.data?.offers ?? cartResult?.data?.cartmessage ?? cartResult?.data?.cart_message ?? cartResult?.data?.offer_message ?? '';

    console.log('API Offers:', apiOffers);

    if (typeof apiOffers === 'string') {
      setOffers(apiOffers);
    } else if (Array.isArray(apiOffers) && apiOffers.length > 0) {
      const firstOffer = apiOffers[0];
      if (typeof firstOffer === 'string') {
        setOffers(firstOffer);
      } else {
        setOffers(firstOffer?.message ?? firstOffer?.cartmessage ?? firstOffer?.offer_message ?? firstOffer?.description ?? '');
      }
    } else {
      setOffers('');
    }
  };

  /*
  |--------------------------------------------------------------------------
  | Load Cart
  |--------------------------------------------------------------------------
  */

  useEffect(() => {
    const loadCartData = async () => {
      try {
        console.log('Session ID:', sessionId);
        console.log('Token:', token);

        const result = await dispatch(
          fetchCart({
            session_id: sessionId,
            token: token,
          })
        ).unwrap();

        console.log('Cart loaded successfully:', result);

        // Update offer data with cart categories
        updateOfferData(result);
        
      } catch (err) {
        console.error('Failed to load cart:', err);
      }
    };

    loadCartData();
  }, [dispatch, sessionId, token]);

  /*
  |--------------------------------------------------------------------------
  | Coupon Total Update
  |--------------------------------------------------------------------------
  */

  useEffect(() => {
    if (appliedCoupon) {
      const discountAmount = Number(appliedCoupon.discount_amount);
      const discountedTotal = Math.max(total - offerDiscount - discountAmount, 0);

      const updatedCouponData = {
        ...appliedCoupon,
        original_total: total,
        discounted_total: discountedTotal,
      };

      localStorage.setItem('applied_coupon', JSON.stringify(updatedCouponData));
      setAppliedCoupon(updatedCouponData);
    }
  }, [total, offerDiscount]);

  /*
  |--------------------------------------------------------------------------
  | Clear offer discount on component unmount (optional)
  |--------------------------------------------------------------------------
  */

  useEffect(() => {
    return () => {
      // Clear offer discount when component unmounts if needed
      // localStorage.removeItem('offer_discount');
    };
  }, []);

  const finalTotal = getDiscountedTotal();

  /*
  |--------------------------------------------------------------------------
  | Format Offer Message
  |--------------------------------------------------------------------------
  */

  const renderOfferMessage = (message: string) => {
    if (!message) {
      return null;
    }

    // Remove Markdown ** if Backend Has It
    const cleanMessage = message.replace(/\*\*/g, '');

    // Split ₹ Amounts
    const parts = cleanMessage.split(/(₹\s*[\d,.]+)/g);

    return parts.map((part, index) => {
      console.log('Offer message part:', part);
      if (/^₹\s*[\d,.]+$/.test(part)) {
        return <strong key={index}>{part}</strong>;
      }
      return <span key={index}>{part}</span>;
    });
  };

  return (
    <>
      <style jsx>{`
        footer {
          display: none !important;
        }
      `}</style>

      <div className="index-page cart-page">
        <main className="main">

          {items.length === 0 ? (
            <div className="w-100 empty-cart text-center">
              <div className="cart-icon">
                <i className="bi bi-cart"></i>
              </div>
              <div className="empty-cart-text">
                No items found in cart to checkout
              </div>
              <div className="cart-continue-shopping">
                <Link href="/" className="btn btn-primary" prefetch={false}>
                  Continue Shopping
                </Link>
              </div>
            </div>
          ) : (
            <>
              <section id="cart" className="cart section cart-page-section">
                <div className="container aos-init aos-animate" data-aos="fade-up" data-aos-delay="100">
                  <div className="row g-4">

                    <div className="d-flex justify-content-center mb-4 step-header">
                      <div className="step-item active">
                        <span className="step-number">1</span>
                        <span className="step-label">Cart</span>
                      </div>
                      <div className="step-line"></div>
                      <div className="step-item">
                        <span className="step-number">2</span>
                        <span className="step-label">Address</span>
                      </div>
                      <div className="step-line"></div>
                      <div className="step-item">
                        <span className="step-number">3</span>
                        <span className="step-label">Payment</span>
                      </div>
                      <div className="step-line"></div>
                      <div className="step-item">
                        <span className="step-number">4</span>
                        <span className="step-label">Summary</span>
                      </div>
                    </div>

                    <div className="col-lg-8 aos-init aos-animate" data-aos="fade-up" data-aos-delay="200">

                      <div className="d-flex justify-content-between align-items-center mb-3">
                        <h4 className="fw-bold">
                          Shopping cart
                          <span className="text-muted"> ({items.length} Items)</span>
                        </h4>
                      </div>

                      {/* ======================================================
                          AVAILABLE OFFERS
                      ====================================================== */}

                      {offers && (
                        <div className="available-offer-box">
                          <div className="available-offer-title">
                            <i className="bx bx-error-circle"></i> Available Offers
                          </div>
                          <div className="available-offer-message">
                            {renderOfferMessage(offers)}
                          </div>
                        </div>
                      )}

                      {/* ======================================================
                          PRODUCTS
                      ====================================================== */}

                      {items.map((item: CartItem) => (
                        <div key={item.id} className="card p-3 mt-3 shadow-sm">
                          <div className="row align-items-center0">

                            <div className="col-md-2 col-4">
                              <Image
                                height={575}
                                width={862}
                                src={item?.product?.product_image?.image ?? ''}
                                alt={item.product.product_name as string}
                                className="img-fluid rounded"
                              />
                            </div>

                            <div className="col-md-6 col-8">
                              <div className="mb-1 fw-semibold cart-product-name">
                                {item.product.product_name}
                              </div>
                              <div className="d-flex align-items-center mb-1">
                                <span className="fs-5 fw-bold text-dark">
                                  ₹ {item.product.price}
                                </span>
                                <span className="text-decoration-line-through text-muted ms-2">
                                  ₹ {item.product.mrp}
                                </span>
                                <span className="badge bg-danger text-white ms-2">
                                  {item.product.discount}% off
                                </span>
                              </div>
                              <div className="d-flex gap-3">
                                <div>
                                  <label className="form-label small mb-1 w-100">Size</label>
                                  <div className="cart-size-show">{item.size}</div>
                                </div>
                                <div>
                                  <label className="form-label small mb-1 w-100">Qty</label>
                                  <div className="quantity-selector">
                                    <button
                                      className="quantity-btn decrease"
                                      onClick={() => handleQuantityChange(item.id, Number(item.quantity) - 1)}
                                      disabled={item.quantity <= 1}
                                    >
                                      <i className="bi bi-dash"></i>
                                    </button>
                                    <div className="item-quantity">{item.quantity}</div>
                                    <button
                                      className="quantity-btn increase"
                                      onClick={() => handleQuantityChange(item.id, Number(item.quantity) + 1)}
                                    >
                                      <i className="bi bi-plus"></i>
                                    </button>
                                  </div>
                                </div>
                              </div>
                            </div>

                            <div className="col-md-4 text-end mt-3 mt-md-0">
                              <span className="cart-product-remove" onClick={() => handleRemoveItem(item.id, sessionId, token)}>
                                <FontAwesomeIcon icon={faXmark} className="text-red-500 text-2xl ms-4" />
                              </span>
                            </div>

                          </div>
                        </div>
                      ))}

                    </div>

                    {/* ======================================================
                        ORDER SUMMARY
                    ====================================================== */}

                    <div className="col-lg-4 aos-init aos-animate" data-aos="fade-up" data-aos-delay="300">
                      <h4 className="summary-title mb-4">Order Summary</h4>

                      <div className="cart-summary mb-3">
                        <div className="cart-detail">
                          <div className="summary-item">
                            <div className="w-100">
                              <div className="coupons-base-header">Coupons</div>
                              <div className="coupons-base-content">
                                <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 18 18" className="coupons-base-couponIcon">
                                  <g fill="none" fillRule="evenodd" transform="rotate(45 6.086 5.293)">
                                    <path stroke="#000" d="M17.5 10V1a1 1 0 0 0-1-1H5.495a1 1 0 0 0-.737.323l-4.136 4.5a1 1 0 0 0 0 1.354l4.136 4.5a1 1 0 0 0 .737.323H16.5a1 1 0 0 0 1-1z" />
                                    <circle cx="5.35" cy="5.35" r="1.35" fill="#000" fillRule="nonzero" />
                                  </g>
                                </svg>
                                <div className="coupons-base-label">Apply Coupons</div>
                                {appliedCoupon ? (
                                  <div className="applied-coupon-container">
                                    <span className="applied-coupon-badge">{appliedCoupon.coupon_code}</span>
                                    <button className="remove-coupon-btn" onClick={handleRemoveCoupon}>
                                      <FontAwesomeIcon icon={faXmark} />
                                    </button>
                                  </div>
                                ) : (
                                  <button role="button" className="css-15k6cs5" onClick={() => setShowCouponModal(true)}>
                                    <div className="css-xjhrni">APPLY</div>
                                  </button>
                                )}
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>

                      <div className="cart-summary mt-2">
                        <div className="cart-detail">
                          {/* Offer Discount - Show if greater than 0 */}
                          {offerDiscount > 0 && (
                            <div className="summary-item discount">
                              <span className="summary-label">Offer Discount</span>
                              <span className="summary-value text-success">-₹ {Number(offerDiscount).toFixed(2)}</span>
                            </div>
                          )}
                          
                          <div className="summary-item">
                            <span className="summary-label">Subtotal</span>
                            <span className="summary-value">₹ {Number(total).toFixed(2)}</span>
                          </div>
                          <div className="summary-item">
                            <span className="summary-label">Tax</span>
                            <span className="summary-value">₹ 0.00</span>
                          </div>
                          {appliedCoupon && (
                            <div className="summary-item discount">
                              <span className="summary-label">Discount ({appliedCoupon.coupon_code})</span>
                              <span className="summary-value text-success">-₹ {Number(appliedCoupon.discount_amount).toFixed(2)}</span>
                            </div>
                          )}
                          <div className="summary-total">
                            <span className="summary-label">Total</span>
                            <span className="summary-value">₹ {Number(finalTotal).toFixed(2)}</span>
                          </div>
                        </div>

                        <div className="payment-methods">
                          <p className="payment-title">We Accept</p>
                          <div className="payment-icons">
                            <i className="bi bi-credit-card-2-front"></i>
                            <i className="bi bi-paypal"></i>
                            <i className="bi bi-wallet2"></i>
                            <i className="bi bi-apple"></i>
                            <i className="bi bi-google"></i>
                          </div>
                        </div>
                      </div>
                    </div>

                  </div>
                </div>
              </section>
            </>
          )}
        </main>

        {items.length > 0 && (
          <div className="add-to-cart-detail mt-1 text-center">
            <div className="detail-cart-btn">
              <button className="btn btn-primary buy-now-btn" type="button">
                ₹ {Number(finalTotal).toFixed(2)}
              </button>
              {token ? (
                <Link href="/address" className="btn btn-primary process-to-checkout" prefetch={false}>
                  Proceed to Checkout <i className="bi bi-arrow-right"></i>
                </Link>
              ) : (
                <Link href="/login" className="btn btn-primary" prefetch={false} style={{ marginBottom: 10 }}>
                  Proceed to Checkout <i className="bi bi-arrow-right"></i>
                </Link>
              )}
            </div>
          </div>
        )}
      </div>

      {/* ================================================================
          COUPON MODAL
      ================================================================ */}

      {showCouponModal && (
        <div className="coupon-modal-overlay" onClick={handleCloseModal}>
          <div className="coupon-modal-content" onClick={e => e.stopPropagation()}>
            <div className="coupon-modal-header">
              <h3>Apply Coupon</h3>
              <button className="coupon-modal-close" onClick={handleCloseModal}>
                <FontAwesomeIcon icon={faXmark} />
              </button>
            </div>
            <div className="coupon-modal-body">
              <p className="coupon-modal-text">Enter your coupon code to get discount on your order.</p>
              <div className="coupon-input-group">
                <input
                  type="text"
                  className={`coupon-input ${couponError ? 'error' : ''}`}
                  placeholder="Enter coupon code"
                  value={couponCode}
                  onChange={e => {
                    setCouponCode(e.target.value);
                    setCouponError('');
                  }}
                  onKeyDown={e => {
                    if (e.key === 'Enter') {
                      handleApplyCoupon();
                    }
                  }}
                  disabled={isApplyingCoupon}
                />
                {couponError && <span className="coupon-error">{couponError}</span>}
              </div>
            </div>
            <div className="coupon-modal-footer">
              <button className="coupon-modal-cancel" onClick={handleCloseModal} disabled={isApplyingCoupon}>
                Cancel
              </button>
              <button className="coupon-modal-apply" onClick={handleApplyCoupon} disabled={isApplyingCoupon}>
                {isApplyingCoupon ? 'Applying...' : 'Apply Coupon'}
              </button>
            </div>
          </div>
        </div>
      )}

      <style jsx>{`
        .cart-page-section {
          margin-bottom: 50px;
        }

        /*
        |--------------------------------------------------------------------------
        | Available Offers
        |--------------------------------------------------------------------------
        */

        .available-offer-box {
          margin-bottom: 16px;
          background: #fff;
          border: 1px solid #e5e7eb;
          border-radius: 8px;
          padding: 15px 18px;
        }

        .available-offer-title {
          font-size: 16px;
          font-weight: 700;
          color: #111;
          margin-bottom: 6px;
        }

        .available-offer-title i {
          margin-right: 6px;
        }

        .available-offer-message {
          font-size: 14px;
          line-height: 22px;
          color: #333;
        }

        .available-offer-message strong {
          font-weight: 700;
          color: #111;
        }

        /*
        |--------------------------------------------------------------------------
        | Coupon Modal
        |--------------------------------------------------------------------------
        */

        .coupon-modal-overlay {
          position: fixed;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background-color: rgba(0, 0, 0, 0.5);
          display: flex;
          justify-content: center;
          align-items: center;
          z-index: 9999;
          animation: fadeIn 0.3s ease;
        }

        .coupon-modal-content {
          background: white;
          border-radius: 12px;
          max-width: 450px;
          width: 90%;
          padding: 0;
          box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
          animation: slideUp 0.3s ease;
        }

        .coupon-modal-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 20px 24px;
          border-bottom: 1px solid #e5e7eb;
        }

        .coupon-modal-header h3 {
          margin: 0;
          font-size: 20px;
          font-weight: 600;
          color: #1f2937;
        }

        .coupon-modal-close {
          background: none;
          border: none;
          font-size: 24px;
          cursor: pointer;
          color: #6b7280;
          padding: 4px 8px;
          border-radius: 6px;
        }

        .coupon-modal-close:hover {
          background: #f3f4f6;
        }

        .coupon-modal-body {
          padding: 24px;
        }

        .coupon-modal-text {
          margin: 0 0 16px 0;
          font-size: 14px;
          color: #6b7280;
          line-height: 1.5;
        }

        .coupon-input-group {
          display: flex;
          flex-direction: column;
          gap: 8px;
        }

        .coupon-input {
          padding: 12px 16px;
          border: 2px solid #e5e7eb;
          border-radius: 8px;
          font-size: 16px;
          outline: none;
        }

        .coupon-input:focus {
          border-color: #2ee44cff;
        }

        .coupon-input.error {
          border-color: #ef4444;
        }

        .coupon-input:disabled {
          background: #f3f4f6;
          cursor: not-allowed;
        }

        .coupon-error {
          color: #ef4444 !important;
          font-size: 13px;
        }

        .coupon-modal-footer {
          display: flex;
          justify-content: flex-end;
          gap: 12px;
          padding: 16px 24px 24px;
          border-top: 1px solid #e5e7eb;
        }

        .coupon-modal-cancel {
          padding: 10px 20px;
          border: 2px solid #e5e7eb;
          border-radius: 8px;
          background: white;
          color: #6b7280;
          font-weight: 600;
          cursor: pointer;
        }

        .coupon-modal-apply {
          padding: 10px 24px;
          border: none;
          border-radius: 8px;
          background: #2ee44cff;
          color: white;
          font-weight: 600;
          cursor: pointer;
        }

        .coupon-modal-apply:hover:not(:disabled) {
          background: #1fc73c;
        }

        .applied-coupon-container {
          display: flex;
          align-items: center;
          gap: 8px;
        }

        .applied-coupon-badge {
          background: #2ee44cff;
          color: white;
          padding: 4px 12px;
          border-radius: 20px;
          font-size: 13px;
          font-weight: 600;
          text-transform: uppercase;
        }

        .remove-coupon-btn {
          background: none;
          border: none;
          color: #ef4444;
          cursor: pointer;
          padding: 6px 5px;
          font-size: 11px;
        }

        .text-success {
          color: #22c55e !important;
        }

        @keyframes fadeIn {
          from { opacity: 0; }
          to { opacity: 1; }
        }

        @keyframes slideUp {
          from {
            opacity: 0;
            transform: translateY(20px);
          }
          to {
            opacity: 1;
            transform: translateY(0);
          }
        }
      `}</style>
    </>
  );
}