"use client";

import React, { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { FaShoppingCart, FaTrash, FaShoppingBag, FaArrowRight } from "react-icons/fa";
import { formatPrice } from "../../utils/currencyHelper";

type CartItem = {
  inward_id: string;
  variant_id: string;
  sku_no: string;
  name: string;
  image: string;
  dealer_price: number;
  mrp: number;
  currency?: string;
  quantity: number;
  subtotal: number;
  is_individual?: boolean;
  is_carton?: boolean;
  carton_box_size?: number;
};

type CartData = {
  items: CartItem[];
  total_items: number;
  total_price: number;
};

export default function CartPage() {
  const [cart, setCart] = useState<CartData | null>(null);
  const [loading, setLoading] = useState(true);
  const router = useRouter();

  const fetchCart = async (tokenOverride?: string) => {
    const token = tokenOverride || localStorage.getItem("access_token");
    if (!token) return;

    try {
      const res = await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/b2b-cart/`, {
        headers: { Authorization: `Bearer ${token}` }
      });

      if (res.status === 401) {
        localStorage.removeItem("access_token");
        router.push("/login");
        return;
      }

      if (res.ok) {
        const data = await res.json();
        setCart(data);
      }
    } catch (err) {
      console.error("Failed to fetch cart", err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    const token = localStorage.getItem("access_token");
    if (!token) {
      router.push("/login");
      return;
    }
    const fetchCart = async (tokenOverride?: string) => {
      const token = tokenOverride || localStorage.getItem("access_token");
      if (!token) return;

      try {
        const cartRes = await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/b2b-cart/`, {
          headers: { Authorization: `Bearer ${token}` }
        });

        if (cartRes.status === 401) {
          localStorage.removeItem("access_token");
          router.push("/login");
          return;
        }

        if (cartRes.ok) {
          const data = await cartRes.json();
          setCart(data);
        }
      } catch (err) {
        console.error("Failed to fetch data", err);
      } finally {
        setLoading(false);
      }
    };

    fetchCart();
  }, [router]);

  const updateQuantity = async (inward_id: string, newQuantity: number) => {
    if (newQuantity < 1) return;
    const token = localStorage.getItem("access_token");
    if (!token) return;

    try {
      const res = await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/b2b-cart/items/${inward_id}`, {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`
        },
        body: JSON.stringify({ quantity: newQuantity })
      });
      if (res.ok) {
        fetchCart(token);
        window.dispatchEvent(new Event("cart-updated"));
      } else {
        alert("Failed to update quantity.");
      }
    } catch (err) {
      console.error("Error updating quantity:", err);
    }
  };

  const removeItem = async (inward_id: string) => {
    const token = localStorage.getItem("access_token");
    if (!token) return;

    try {
      const res = await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/b2b-cart/items/${inward_id}`, {
        method: "DELETE",
        headers: { Authorization: `Bearer ${token}` }
      });
      if (res.ok) {
        fetchCart(token);
        window.dispatchEvent(new Event("cart-updated"));
      } else {
        alert("Failed to remove item.");
      }
    } catch (err) {
      console.error("Error removing item:", err);
    }
  };

  const clearCart = async () => {
    const token = localStorage.getItem("access_token");
    if (!token) return;

    if (!confirm("Are you sure you want to clear your entire cart?")) return;

    try {
      const res = await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/b2b-cart/`, {
        method: "DELETE",
        headers: { Authorization: `Bearer ${token}` }
      });
      if (res.ok) {
        setCart({ items: [], total_items: 0, total_price: 0 });
        window.dispatchEvent(new Event("cart-updated"));
      } else {
        alert("Failed to clear cart.");
      }
    } catch (err) {
      console.error("Error clearing cart:", err);
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50/30 flex items-center justify-center">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-gray-900"></div>
      </div>
    );
  }

  const isEmpty = !cart || !cart.items || cart.items.length === 0;

  return (
    <div className="bg-gray-50/30 min-h-screen">
      <div className="max-w-[90rem] mx-auto px-4 sm:px-6 lg:px-8 py-12 lg:py-20">
        <div className="flex items-center justify-between mb-12">
          <div className="flex items-center gap-4">
            <h1 className="text-4xl md:text-5xl font-black text-gray-900 tracking-tight">Your Cart</h1>
            {!isEmpty && (
              <span className="bg-gray-200 text-gray-700 text-sm font-bold px-3 py-1 rounded-full">
                {cart.total_items} items
              </span>
            )}
          </div>
          {!isEmpty && (
            <button 
              onClick={clearCart}
              className="text-[13px] font-bold text-gray-400 hover:text-red-500 hover:bg-red-50 px-4 py-2 rounded-xl transition-colors flex items-center gap-2"
            >
              <FaTrash /> Clear Cart
            </button>
          )}
        </div>

      {isEmpty ? (
        <div className="flex flex-col items-center justify-center py-32 bg-white rounded-3xl border border-gray-100 shadow-[0_2px_10px_rgb(0,0,0,0.02)] text-center">
          <div className="w-24 h-24 bg-gray-50 rounded-full flex items-center justify-center mb-6">
            <FaShoppingBag className="text-4xl text-gray-300" />
          </div>
          <h2 className="text-2xl font-bold text-gray-900 mb-2">Your cart is empty</h2>
          <p className="text-gray-500 mb-8 max-w-md">Looks like you haven't added anything to your cart yet. Explore our latest arrivals and fill it up!</p>
          <Link 
            href="/"
            className="bg-gray-900 text-white px-8 py-3.5 rounded-xl font-bold hover:bg-gray-800 transition-colors shadow-md"
          >
            Continue Shopping
          </Link>
        </div>
      ) : (
        <div className="flex flex-col lg:flex-row gap-8 xl:gap-12">
          
          {/* Left Column: Cart Items Table */}
          <div className="w-full lg:w-2/3 bg-white rounded-3xl border border-gray-100 shadow-[0_2px_10px_rgb(0,0,0,0.02)] overflow-hidden">
            <div className="overflow-x-auto">
              <table className="w-full text-left border-collapse">
                <thead>
                  <tr className="border-b border-gray-200 bg-gray-50/80">
                    <th className="py-3 px-6 text-[10px] font-black text-gray-500 uppercase tracking-widest w-[18%]">SKU</th>
                    <th className="py-3 px-4 text-[10px] font-black text-gray-500 uppercase tracking-widest">Product</th>
                    <th className="py-3 px-4 text-[10px] font-black text-gray-500 uppercase tracking-widest text-center w-[20%]">Qty</th>
                    <th className="py-3 px-6 text-[10px] font-black text-gray-500 uppercase tracking-widest text-right w-[18%]">Amount</th>
                    <th className="py-3 px-4 w-[8%]"></th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-100">
                  {cart.items.map((item, index) => {
                    const boxSize = item.carton_box_size || 1;
                    const isCartonOnly = item.is_carton && !item.is_individual;
                    return (
                      <tr key={`${item.inward_id}-${index}`} className="hover:bg-blue-50/20 transition-colors group">
                        {/* SKU */}
                        <td className="py-4 px-6 align-middle">
                          <div className="text-[11px] font-black text-slate-700 leading-tight break-all">{item.sku_no}</div>
                        </td>
                        {/* Product Image & Name */}
                        <td className="py-4 px-4 align-middle">
                          <div className="flex items-center gap-3">
                            <div className="w-12 h-12 shrink-0 bg-gray-50/80 rounded-lg flex items-center justify-center overflow-hidden border border-gray-100">
                              <img 
                                src={`${process.env.NEXT_PUBLIC_API_BASE_URL || ''}${item.image}`} 
                                alt={item.name} 
                                className="w-full h-full object-contain mix-blend-multiply p-1 group-hover:scale-105 transition-transform duration-300"
                                onError={(e) => {
                                  (e.target as HTMLImageElement).src = "https://static.wixstatic.com/media/703249_3a76a53b765e46d4b3a5e4c3ec6ddd7e~mv2.png/v1/fill/w_1362,h_1002,al_c,q_90,usm_0.66_1.00_0.01,enc_avif,quality_auto/Full%20Face%20Helmet.png";
                                }}
                              />
                            </div>
                            <div>
                              <div className="text-[13px] font-semibold text-gray-800 leading-snug line-clamp-2">{item.name}</div>
                              {item.is_carton && (
                                <span className="text-[9px] font-bold text-slate-500 bg-slate-100 px-1.5 py-0.5 rounded mt-1 inline-block">
                                  Box ×{boxSize}
                                </span>
                              )}
                            </div>
                          </div>
                        </td>
                        {/* Qty Stepper */}
                        <td className="py-4 px-4 align-middle text-center">
                          <div className="flex items-center justify-center gap-1">
                            <button
                              onClick={() => {
                                const diff = isCartonOnly ? (item.quantity > boxSize ? boxSize : 0) : 1;
                                updateQuantity(item.inward_id, item.quantity - diff);
                              }}
                              className="w-6 h-6 flex items-center justify-center rounded border border-gray-250 text-gray-500 hover:bg-gray-100 text-sm font-bold leading-none"
                            >−</button>
                            <input
                              type="number"
                              value={item.quantity}
                              onChange={(e) => {
                                const val = parseInt(e.target.value, 10);
                                if (!isNaN(val) && val >= 0) {
                                  if (isCartonOnly) {
                                    updateQuantity(item.inward_id, Math.ceil(val / boxSize) * boxSize);
                                  } else {
                                    updateQuantity(item.inward_id, val);
                                  }
                                }
                              }}
                              className="w-10 text-center text-xs font-black text-gray-800 bg-transparent outline-none [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"
                              style={{ MozAppearance: 'textfield' }}
                            />
                            <button
                              onClick={() => {
                                const diff = isCartonOnly ? boxSize : 1;
                                updateQuantity(item.inward_id, item.quantity + diff);
                              }}
                              className="w-6 h-6 flex items-center justify-center rounded border border-gray-250 text-gray-500 hover:bg-gray-100 text-sm font-bold leading-none"
                            >+</button>
                          </div>
                        </td>
                        {/* Amount */}
                        <td className="py-4 px-6 align-middle text-right">
                          <div className="text-[13px] font-black text-gray-900 tabular-nums">{formatPrice(item.subtotal, item.currency)}</div>
                        </td>
                        {/* Remove Button */}
                        <td className="py-4 px-4 align-middle text-center">
                          <button
                            onClick={() => removeItem(item.inward_id)}
                            className="w-8 h-8 flex items-center justify-center rounded-full text-gray-300 hover:bg-red-50 hover:text-red-500 transition-colors"
                            title="Remove item"
                          >
                            <FaTrash className="text-xs" />
                          </button>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </div>

          {/* Right Column: Order Summary */}
          <div className="w-full lg:w-1/3">
            <div className="bg-gray-900 rounded-3xl p-8 text-white shadow-xl sticky top-28">
              <h2 className="text-xl font-black mb-6 uppercase tracking-wider opacity-90 border-b border-white/10 pb-4">Order Summary</h2>
              
              <div className="flex flex-col gap-4 mb-8">
                <div className="flex justify-between items-center text-[15px] font-medium text-gray-400">
                  <span>Total Items</span>
                  <span className="text-white">{cart.total_items}</span>
                </div>
                <div className="flex justify-between items-center text-[15px] font-medium text-gray-400">
                  <span>Shipping</span>
                  <span className="text-white">Calculated at checkout</span>
                </div>
                
                <div className="border-t border-white/10 pt-6 mt-2 flex justify-between items-end">
                  <span className="text-sm font-bold text-gray-400 uppercase tracking-widest">Subtotal</span>
                  <span className="text-4xl font-black tracking-tight text-white">{formatPrice(cart.total_price, cart.items[0]?.currency)}</span>
                </div>
              </div>

              <Link 
                href="/checkout"
                className="w-full bg-white text-gray-900 h-14 rounded-2xl font-black text-[15px] hover:bg-gray-100 transition-all flex items-center justify-center gap-2 active:scale-[0.98]"
              >
                Proceed to Checkout <FaArrowRight className="text-sm" />
              </Link>
            </div>
          </div>

        </div>
      )}
      </div>
    </div>
  );
}
