"use client";

import React, { useEffect, useState } from "react";
import { useCart } from "../context/CartContext";
import Link from "next/link";
import { useRouter, usePathname } from "next/navigation";
import { resolveImage, PLACEHOLDER_IMAGE } from "@/utils/imageHelper";
import { formatPrice } from "@/utils/currencyHelper";
import { API_BASE_URL } from "@/utils/apiHelper";

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 CartDrawer() {
  const { isCartOpen, closeCart } = useCart();
  const [cart, setCart] = useState<CartData | null>(null);
  const [loading, setLoading] = useState(false);
  const router = useRouter();
  const pathname = usePathname();

  // Auto-collapse on profile pages
  const isProfilePage = pathname?.startsWith("/profile");
  const [isCollapsed, setIsCollapsed] = useState(isProfilePage);

  // 60-second auto-collapse timer ref
  const autoCollapseTimer = React.useRef<ReturnType<typeof setTimeout> | null>(null);

  // Draggable states
  const [position, setPosition] = useState({ x: 24, y: 128 });
  const [isDragging, setIsDragging] = useState(false);
  const [dragStart, setDragStart] = useState({ x: 0, y: 0 });
  const [dragMoved, setDragMoved] = useState(false);

  const handleMouseDown = (e: React.MouseEvent) => {
    if (e.button !== 0) return;
    const target = e.target as HTMLElement;
    if (target.closest("button") || target.closest("input")) return;

    setIsDragging(true);
    setDragMoved(false);
    setDragStart({
      x: e.clientX - position.x,
      y: e.clientY - position.y,
    });
    e.preventDefault();
  };

  const handleBubbleMouseDown = (e: React.MouseEvent) => {
    if (e.button !== 0) return;
    setIsDragging(true);
    setDragMoved(false);
    setDragStart({
      x: e.clientX - position.x,
      y: e.clientY - position.y,
    });
    e.preventDefault();
  };

  useEffect(() => {
    if (!isDragging) return;

    const handleMouseMove = (e: MouseEvent) => {
      setDragMoved(true);
      const width = isCollapsed ? 56 : 512;
      const height = isCollapsed ? 56 : 580;

      const nextX = Math.max(8, Math.min(window.innerWidth - width - 8, e.clientX - dragStart.x));
      const nextY = Math.max(8, Math.min(window.innerHeight - height - 8, e.clientY - dragStart.y));
      setPosition({ x: nextX, y: nextY });
    };

    const handleMouseUp = () => {
      setIsDragging(false);
    };

    window.addEventListener("mousemove", handleMouseMove);
    window.addEventListener("mouseup", handleMouseUp);
    return () => {
      window.removeEventListener("mousemove", handleMouseMove);
      window.removeEventListener("mouseup", handleMouseUp);
    };
  }, [isDragging, dragStart, isCollapsed]);

  /** Expand the cart and (re)start the 60-second auto-collapse timer */
  const expandCart = () => {
    setIsCollapsed(false);
    if (autoCollapseTimer.current) clearTimeout(autoCollapseTimer.current);
    autoCollapseTimer.current = setTimeout(() => {
      setIsCollapsed(true);
    }, 60_000);
  };

  // Clear timer on unmount
  useEffect(() => {
    return () => {
      if (autoCollapseTimer.current) clearTimeout(autoCollapseTimer.current);
    };
  }, []);

  const handleBubbleClick = (e: React.MouseEvent) => {
    if (!dragMoved) {
      expandCart();
    }
  };

  const fetchCart = async (tokenOverride?: string) => {
    const token = tokenOverride || localStorage.getItem("access_token");
    if (!token) return;
    setLoading(true);
    try {
      const res = await fetch(`${API_BASE_URL}/api/v1/b2b-cart/`, {
        headers: { Authorization: `Bearer ${token}` },
      });
      if (res.status === 401) {
        localStorage.removeItem("access_token");
        router.push("/login");
        closeCart();
        return;
      }
      if (res.ok) setCart(await res.json());
    } catch { /* silent */ }
    finally { setLoading(false); }
  };

  useEffect(() => {
    fetchCart();

    const handleCartUpdate = () => {
      fetchCart();
      expandCart(); // Auto-expand when a product is added or updated!
    };

    window.addEventListener("cart-updated", handleCartUpdate);
    return () => {
      window.removeEventListener("cart-updated", handleCartUpdate);
    };
  }, []);

  useEffect(() => {
    if (isCartOpen) {
      fetchCart();
      expandCart(); // Auto-expand when Cart button is clicked in header!
    }
  }, [isCartOpen]);

  // Collapse cart when navigating to profile pages, expand otherwise
  useEffect(() => {
    if (pathname?.startsWith("/profile")) {
      setIsCollapsed(true);
      if (autoCollapseTimer.current) clearTimeout(autoCollapseTimer.current);
    }
  }, [pathname]);

  useEffect(() => {
    if (!isCollapsed) {
      // Auto-correct position when expanding to stay fully visible inside the screen
      const width = 512;
      const height = 580;
      
      const nextX = Math.max(8, Math.min(window.innerWidth - width - 8, position.x));
      const nextY = Math.max(8, Math.min(window.innerHeight - height - 8, position.y));
      
      setPosition({ x: nextX, y: nextY });
    }
  }, [isCollapsed, position.x, position.y]);

  const updateQuantity = async (inward_id: string, qty: number) => {
    if (qty < 1) return;
    const token = localStorage.getItem("access_token");
    if (!token) return;
    const res = await fetch(`${API_BASE_URL}/api/v1/b2b-cart/items/${inward_id}`, {
      method: "PUT",
      headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
      body: JSON.stringify({ quantity: qty }),
    });
    if (res.ok) fetchCart(token);
  };

  const removeItem = async (inward_id: string) => {
    const token = localStorage.getItem("access_token");
    if (!token) return;
    const res = await fetch(`${API_BASE_URL}/api/v1/b2b-cart/items/${inward_id}`, {
      method: "DELETE",
      headers: { Authorization: `Bearer ${token}` },
    });
    if (res.ok) fetchCart(token);
  };

  const isEmpty = !cart || !cart.items || cart.items.length === 0;
  const isCartOrCheckoutPage = pathname === "/cart" || pathname === "/checkout";

  if (isEmpty || isCartOrCheckoutPage) {
    return null;
  }

  if (isCollapsed) {
    return (
      <>
        {/* Collapsed Bubble for Desktop */}
        <div 
          onClick={handleBubbleClick}
          onMouseDown={handleBubbleMouseDown}
          style={{ left: `${position.x}px`, top: `${position.y}px` }}
          className={`fixed z-40 w-16 h-16 rounded-full bg-white border border-gray-200 shadow-[0_8px_30px_rgba(0,0,0,0.12)] hidden lg:flex items-center justify-center cursor-grab active:cursor-grabbing hover:bg-gray-50 active:scale-95 group ${isDragging ? "transition-none" : "transition-all duration-300"}`}
          title="Drag to move, click to expand"
        >
          <svg className="w-7 h-7 text-gray-700 transition-transform duration-300 group-hover:scale-110 group-hover:text-[#FFC633]" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z" />
          </svg>
          <span className="absolute -top-1 -right-1 flex h-6 min-w-[24px] px-1 items-center justify-center rounded-full bg-primary text-xs font-black text-[#121212] shadow-md leading-none select-none z-10">
            {cart.total_items}
          </span>
        </div>

        {/* Mobile/Tablet Sticky Bottom Cart Banner */}
        <div className="fixed bottom-4 left-4 right-4 z-40 bg-white/95 backdrop-blur-md rounded-2xl border border-gray-250/30 shadow-[0_12px_40px_rgba(0,0,0,0.15)] flex lg:hidden items-center justify-between px-4 py-3 gap-3 transition-all duration-300">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl bg-primary/10 border border-primary/20 flex items-center justify-center text-[#121212]">
              <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z" />
              </svg>
            </div>
            <div>
              <div className="text-[10px] font-extrabold text-gray-400 uppercase tracking-wider">Cart Subtotal</div>
              <div className="flex items-baseline gap-1.5">
                <span className="text-sm font-extrabold text-gray-900">{formatPrice(cart.total_price, cart.items[0]?.currency)}</span>
                <span className="text-[10px] text-gray-500 font-medium">({cart.total_items} {cart.total_items === 1 ? "item" : "items"})</span>
              </div>
            </div>
          </div>

          <div className="flex items-center gap-2">
            <Link
              href="/cart"
              className="h-8 px-3 rounded-lg border border-gray-200 text-[10px] font-bold text-gray-700 bg-white hover:bg-gray-50 flex items-center justify-center"
            >
              Edit
            </Link>
            <Link
              href="/checkout"
              className="h-8 px-4 rounded-lg bg-primary text-[#121212] text-[10px] font-extrabold flex items-center justify-center gap-1 shadow-md active:scale-95"
            >
              Checkout
              <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M9 5l7 7-7 7" />
              </svg>
            </Link>
          </div>
        </div>
      </>
    );
  }

  return (
    <>
      {/* Desktop Permanent Cart (Left Side) */}
      <div 
        style={{ left: `${position.x}px`, top: `${position.y}px` }}
        className={`fixed z-40 w-[32rem] max-h-[calc(100vh-120px)] bg-white rounded-[2rem] border border-gray-250/80 shadow-[0_16px_60px_rgba(0,0,0,0.12)] hidden lg:flex flex-col ${isDragging ? "transition-none select-none" : "transition-all duration-300"}`}
      >
        {/* Header (Drag Handle) */}
        <div 
          onMouseDown={handleMouseDown}
          className="flex items-center justify-between px-5 py-4 border-b border-gray-200 bg-white rounded-t-[2rem] cursor-grab active:cursor-grabbing select-none"
        >
          <div className="flex items-center gap-3">
            <h2 className="text-sm font-black text-gray-900 tracking-tight uppercase">Cart</h2>
            <span className="inline-flex items-center px-2 py-0.5 rounded text-[10px] font-black bg-primary/10 text-[#121212] border border-primary/20">
              {cart.total_items} {cart.total_items === 1 ? "item" : "items"}
            </span>
          </div>
          <button 
            onClick={() => {
              setIsCollapsed(true);
              if (autoCollapseTimer.current) clearTimeout(autoCollapseTimer.current);
            }}
            className="w-6 h-6 rounded flex items-center justify-center text-gray-400 hover:bg-gray-100 hover:text-gray-700 transition-colors"
            title="Collapse Cart"
          >
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M18 12H6" />
            </svg>
          </button>
        </div>

        {/* Table Body */}
        <div className="flex-grow overflow-y-auto custom-scrollbar">
          {loading && !cart ? (
            <div className="flex justify-center py-12">
              <span className="w-8 h-8 border-3 border-primary/30 border-t-primary rounded-full animate-spin" />
            </div>
          ) : (
            <table className="w-full text-left border-collapse">
              <thead>
                <tr className="border-b border-gray-200 bg-gray-50/80">
                  <th className="py-2 px-3 text-[9px] font-black text-gray-500 uppercase tracking-widest w-[20%]">SKU</th>
                  <th className="py-2 px-2 text-[9px] font-black text-gray-500 uppercase tracking-widest">Product</th>
                  <th className="py-2 px-2 text-[9px] font-black text-gray-500 uppercase tracking-widest text-center w-[22%]">Qty</th>
                  <th className="py-2 px-3 text-[9px] font-black text-gray-500 uppercase tracking-widest text-right w-[16%]">Amount</th>
                  <th className="py-2 px-2 w-[8%]"></th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100">
                {cart.items.map((item, idx) => {
                  const boxSize = item.carton_box_size || 1;
                  const isCartonOnly = item.is_carton && !item.is_individual;
                  return (
                    <tr
                      key={item.inward_id || idx}
                      className="hover:bg-blue-50/40 transition-colors group"
                    >
                      {/* SKU */}
                      <td className="py-3 px-3 align-middle">
                        <div className="text-[10px] font-black text-slate-700 leading-tight break-all">{item.sku_no}</div>
                      </td>
                      {/* Product name */}
                      <td className="py-3 px-2 align-middle">
                        <div className="text-[11px] 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-0.5 inline-block">
                            Box ×{boxSize}
                          </span>
                        )}
                      </td>
                      {/* Qty stepper */}
                      <td className="py-3 px-2 align-middle">
                        <div className="flex items-center justify-center gap-0.5">
                          <button
                            onClick={() => {
                              const diff = isCartonOnly ? (item.quantity > boxSize ? boxSize : 0) : 1;
                              updateQuantity(item.inward_id, item.quantity - diff);
                            }}
                            className="w-5 h-5 flex items-center justify-center rounded border border-gray-200 text-gray-500 hover:bg-gray-100 text-xs 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-8 text-center text-[11px] 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-5 h-5 flex items-center justify-center rounded border border-gray-200 text-gray-500 hover:bg-gray-100 text-xs font-bold leading-none"
                          >+</button>
                        </div>
                      </td>
                      {/* Amount */}
                      <td className="py-3 px-3 align-middle text-right">
                        <div className="text-[12px] font-black text-gray-900 tabular-nums">{formatPrice(item.subtotal, item.currency)}</div>
                      </td>
                      {/* Delete */}
                      <td className="py-3 px-2 align-middle text-center">
                        <button
                          onClick={() => removeItem(item.inward_id)}
                          className="w-6 h-6 flex items-center justify-center rounded-full text-gray-300 hover:bg-red-50 hover:text-red-500 transition-colors"
                          title="Remove item"
                        >
                          <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
                            <path strokeLinecap="round" strokeLinejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                          </svg>
                        </button>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          )}
        </div>

        {/* Footer Summary */}
        <div className="border-t border-gray-200 bg-gray-50/50 rounded-b-[2rem]">
          {/* Total quantity row */}
          <div className="flex justify-between items-center px-5 py-2.5 border-b border-gray-100">
            <span className="text-[11px] font-bold text-gray-600">Total quantity</span>
            <span className="text-[12px] font-black text-gray-900 tabular-nums">{cart.total_items}</span>
          </div>
          {/* Subtotal */}
          <div className="flex justify-between items-center px-5 py-2.5 border-b border-gray-100">
            <span className="text-[11px] font-bold text-gray-600">Subtotal</span>
            <span className="text-sm font-black text-gray-900 tabular-nums">{formatPrice(cart.total_price, cart.items[0]?.currency)}</span>
          </div>
          {/* Actions */}
          <div className="flex flex-col gap-2 px-5 py-3.5">
            <Link
              href="/checkout"
              className="inline-flex items-center justify-center gap-2 rounded-xl font-black bg-primary text-[#121212] hover:bg-primary-dark shadow-sm transition-all duration-200 cursor-pointer select-none active:scale-[.97] h-10 text-[11px] uppercase tracking-widest w-full"
            >
              Proceed to Checkout
              <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M9 5l7 7-7 7" />
              </svg>
            </Link>
            <Link
              href="/cart"
              className="inline-flex items-center justify-center gap-2 rounded-xl font-black bg-white text-gray-600 border border-gray-200 hover:bg-gray-50 transition-all duration-200 cursor-pointer select-none active:scale-[.97] h-8 text-[10px] uppercase tracking-widest w-full"
            >
              View Full Cart
            </Link>
          </div>
        </div>
      </div>

      {/* Mobile/Tablet Sticky Bottom Cart Banner */}
      <div className="fixed bottom-4 left-4 right-4 z-40 bg-white/95 backdrop-blur-md rounded-2xl border border-gray-250/30 shadow-[0_12px_40px_rgba(0,0,0,0.15)] flex lg:hidden items-center justify-between px-4 py-3 gap-3 transition-all duration-300">
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 rounded-xl bg-primary/10 border border-primary/20 flex items-center justify-center text-[#121212]">
            <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z" />
            </svg>
          </div>
          <div>
            <div className="text-[10px] font-extrabold text-gray-400 uppercase tracking-wider">Cart Subtotal</div>
            <div className="flex items-baseline gap-1.5">
              <span className="text-sm font-extrabold text-gray-900">{formatPrice(cart.total_price, cart.items[0]?.currency)}</span>
              <span className="text-[10px] text-gray-500 font-medium">({cart.total_items} {cart.total_items === 1 ? "item" : "items"})</span>
            </div>
          </div>
        </div>

        <div className="flex items-center gap-2">
          <Link
            href="/cart"
            className="h-8 px-3 rounded-lg border border-gray-200 text-[10px] font-bold text-gray-700 bg-white hover:bg-gray-50 flex items-center justify-center"
          >
            Edit
          </Link>
          <Link
            href="/checkout"
            className="h-8 px-4 rounded-lg bg-primary text-[#121212] text-[10px] font-extrabold flex items-center justify-center gap-1 shadow-md active:scale-95"
          >
            Checkout
            <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M9 5l7 7-7 7" />
            </svg>
          </Link>
        </div>
      </div>
    </>
  );
}
