"use client";

import { useEffect, useState } from "react";
import { useCart } from "@/hooks/useCart";
import AppHeader from "@/components/app-layout/AppHeader";
import AppFooter from "@/components/app-layout/AppFooter";
import Link from "next/link";
import { useRouter } from "next/navigation";
import useAuth from "@/hooks/useAuth";
import { X } from "lucide-react";

const DeleteIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 16 16" width={16} height={16}>
    <path d="M5.5 5.5A.5.5 0 0 1 6 6v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5m2.5 0a.5.5 0 0 1 .5.5v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5m3 .5a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0z"/>
    <path d="M14.5 3a1 1 0 0 1-1 1H13v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V4h-.5a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1H6a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1h3.5a1 1 0 0 1 1 1zM4.118 4 4 4.059V13a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V4.059L11.882 4zM2.5 3h11V2h-11z"/>
  </svg>
);

export default function CartPage() {
  const { isAuthenticated } = useAuth();
  const router = useRouter();
  const { cart, loading, fetchCart, updateItem, removeItem } = useCart();
  const [showModal, setShowModal] = useState(false);

  // Fetch cart from API if redux state is empty
  useEffect(() => {
    if (!cart || cart.length === 0) {
      fetchCart();
    }
  }, []);

  // helpers
  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 formatPrice = (n: number) =>
    `₹ ${n.toLocaleString("en-IN", { minimumFractionDigits: 2 })}`;

const handleCheckout = () => {
  if (isAuthenticated) {
    router.push("/orderdetails");
    return;
  }

  setShowModal(true);
};

  const handleGuestCheckout = () => {
    // Generate a guest ID if not exists
    let guestId = localStorage.getItem("guest_id");
    if (!guestId) {
      guestId = `guest_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
      localStorage.setItem("guest_id", guestId);
    }
    setShowModal(false);
    router.push("/orderdetails");
  };

  const handleLogin = () => {
    setShowModal(false);
    router.push("/login?next=/orderdetails");
  };

  return (
    <div className="font-montserrat">
      <main>
        <section className="breadcrumbcontainer">
          <div className="container px-3">
            <ol className="breadcrumb">
              <li><a href="/">Home</a></li>
              <li className="active">Cart</li>
            </ol>
          </div>
        </section>

        <section className="cartcontainer">
          <div className="container px-3">
            <div className="flex flex-wrap -mx-3 xl:-mx-6 2xl:-mx-10">

              {/* Left — Cart Items */}
              <div className="2xl:w-8/12 xl:w-8/12 lg:w-8/12 md:w-7/12 sm:w-full w-full px-3 xl:px-6 2xl:px-10 mb-4">
                <div className="section-heading">
                  <h2>Shopping Cart</h2>
                </div>

                {loading && !cart?.length ? (
                  /* skeleton */
                  <div>
                    {[1, 2, 3].map(i => (
                      <div key={i} style={{ height: 100, marginBottom: 16, borderRadius: 8, background: "linear-gradient(90deg,#f0f0f0 25%,#e8e8e8 50%,#f0f0f0 75%)", backgroundSize: "600px 100%", animation: "shimmer 1.5s infinite linear" }} />
                    ))}
                  </div>
                ) : !cart?.length ? (
                  <div style={{ padding: "60px 0", textAlign: "center" }}>
                    <p style={{ fontSize: 18, color: "#888", marginBottom: 20 }}>Your cart is empty.</p>
                    <a href="/products" className="theme-btn">Shop Now</a>
                  </div>
                ) : (
                  <div className="cartouter style1">
                    {cart.map((item: any) => {
                      const product = item.product;
                      const sku = item.sku;
                      const price = getPrice(product?.price);

                      return (
                        <div className="cartproductlist" key={item._id ?? sku?._id}>
                          {/* Item */}
                          <div className="cartitem">
                            <a className="cartlis-img" href={`/productdetails/${product?.slug}`}>
                              <img src={product?.defaultImage} alt={product?.name} />
                            </a>
                            <div className="carttitle">
                              <div className="p-0">
                                <h3>
                                  <a href={`/productdetails/${product?.slug}`}>{product?.name}</a>
                                </h3>
                                <div className="flex gap-3">
                                  {sku?.size?.name && (
                                    <p className="flex items-center gap-2">Size: {sku.size.name}</p>
                                  )}
                                  {sku?.color && (
                                    <p className="flex items-center gap-2">Color: {sku.color}</p>
                                  )}
                                </div>
                                {/* Qty */}
                                <div className="flex items-center gap-2 cart-flex-item">
                                  <label className="text-nowrap">QTY</label>
                                  <div className="cart__qty flex">
                                    <div className="qtyinner">
                                      <button
                                        type="button"
                                        className="subbtns"
                                        disabled={loading || item.quantity <= 1}
                                        onClick={() => updateItem(sku._id, item.quantity - 1)}
                                      >
                                        <i className="icon icon-minus" />
                                      </button>
                                      <input
                                        type="text"
                                        className="form-control"
                                        value={item.quantity}
                                        readOnly
                                      />
                                      <button
                                        type="button"
                                        className="addbtns"
                                        disabled={loading}
                                        onClick={() => updateItem(sku._id, item.quantity + 1)}
                                      >
                                        <i className="icon icon-plus" />
                                      </button>
                                    </div>
                                  </div>
                                </div>
                              </div>
                            </div>
                          </div>

                          {/* Price */}
                          <div className="cart-price">
                            <span className="money fw-500">
                              {formatPrice(price * item.quantity)}
                            </span>
                          </div>

                          {/* Delete */}
                          <div className="cart-delete">
                            <a
                              href="javascript:void(0);"
                              className="refresh-btn"
                              title="Remove item"
                              onClick={() => removeItem(sku._id)}
                            >
                              <DeleteIcon />
                            </a>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>

              {/* Right — Cart Summary */}
              <div className="2xl:w-4/12 xl:w-4/12 lg:w-4/12 md:w-5/12 sm:w-full w-full px-3 xl:px-6 2xl:px-10 mb-4">
                <div className="cartsummarybx">
                  <div className="section-heading">
                    <h2>Cart Summary</h2>
                  </div>

                  <div id="cartSummary">
                    <div className="flex 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 borderbtm pb-3 pt-3">
                      <span className="w-6/12 cart__subtotal-title">Packing Charge</span>
                      <span className="w-6/12 text-right">Free</span>
                    </div>
                    <div className="flex borderbtm pb-3 pt-3">
                      <span className="w-6/12 cart__subtotal-title">Tax</span>
                      <span className="w-6/12 text-right">₹ 0.00</span>
                    </div>
                    <div className="flex 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(subtotal)}</strong>
                      </span>
                    </div>
                  </div>

                  {/* Proceed to Checkout Button */}
                  <button
                    onClick={handleCheckout}
                    className="theme-btn w-full gap-2 justify-center"
                    style={{ display: cart?.length ? "inline-flex" : "none" }}
                  >
                    <span>Proceed To Checkout</span>
                    <i className="icon icon-arrow-right" />
                  </button>
                </div>
              </div>

            </div>
          </div>
        </section>
      </main>

      {/* Modal for Login/Guest Checkout */}
      {showModal && !isAuthenticated && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black bg-opacity-50">
          <div className="relative bg-white rounded-xl shadow-xl max-w-md w-full p-6 animate-in fade-in zoom-in duration-300">
            {/* Close Button */}
            <button
              onClick={() => setShowModal(false)}
              className="absolute top-4 right-4 text-gray-400 hover:text-gray-600 transition"
            >
              <X size={24} />
            </button>

            {/* Modal Content */}
            <div className="text-center">
              <div className="w-16 h-16 mx-auto mb-4 bg-primary/10 rounded-full flex items-center justify-center">
                <svg className="w-8 h-8 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                </svg>
              </div>
              <h3 className="text-xl font-semibold text-gray-800 mb-2">
                Ready to Checkout?
              </h3>
              <p className="text-gray-500 mb-6">
                Sign in to your account for faster checkout, track orders, and manage your wishlist.
              </p>

              {/* Login Button */}
              <button
                onClick={handleLogin}
                className="w-full bg-primary text-white py-3 rounded-lg font-semibold hover:bg-primary-dark transition mb-3"
              >
                Sign In / Create Account
              </button>

              {/* Divider */}
              <div className="relative my-4">
                <div className="absolute inset-0 flex items-center">
                  <div className="w-full border-t border-gray-300"></div>
                </div>
                <div className="relative flex justify-center text-sm">
                  <span className="px-2 bg-white text-gray-500">or continue as</span>
                </div>
              </div>

              {/* Guest Checkout Button */}
              <button
                onClick={handleGuestCheckout}
                className="w-full border-2 border-primary text-primary py-3 rounded-lg font-semibold hover:bg-primary hover:text-white transition"
              >
                Continue as Guest
              </button>

              <p className="text-xs text-gray-400 mt-4">
                By continuing, you agree to our Terms of Service and Privacy Policy.
              </p>
            </div>
          </div>
        </div>
      )}

      {/* Add animation styles */}
      <style jsx>{`
        @keyframes fade-in {
          from { opacity: 0; }
          to { opacity: 1; }
        }
        @keyframes zoom-in {
          from { transform: scale(0.95); opacity: 0; }
          to { transform: scale(1); opacity: 1; }
        }
        .animate-in {
          animation-duration: 0.2s;
          animation-fill-mode: both;
        }
        .fade-in {
          animation-name: fade-in;
        }
        .zoom-in {
          animation-name: zoom-in;
        }
      `}</style>
    </div>
  );
}