'use client';

import React from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useCart } from '@/context/CartContext';
import { useSiteSettings } from '@/context/SiteSettingsContext';
import { useAuth } from '@/context/AuthContext';
import { Header } from '@/components/Header';
import { Footer } from '@/components/Footer';
import { Trash2, ShoppingBag, ArrowRight, Loader2 } from 'lucide-react';

export default function CartPage() {
  const router = useRouter();
  const { cartItems, subtotal, updateQuantity, removeItem, loading } = useCart();
  const { formatPrice } = useSiteSettings();
  const { user } = useAuth();
  const isReseller = user?.role === 'reseller';

  const handleQtyChange = async (itemId: number, newQty: number, maxStock: number) => {
    if (newQty <= 0) {
      await removeItem(itemId);
      return;
    }
    if (newQty > maxStock) {
      alert(`Cannot add more. Only ${maxStock} items available in stock.`);
      return;
    }
    try {
      await updateQuantity(itemId, newQty);
    } catch (err: any) {
      alert(err.message || 'Failed to update quantity');
    }
  };

  if (loading) {
    return (
      <>
        <Header />
        <main className="bg-slate-50 min-h-screen py-8 animate-pulse">
          <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 space-y-6">
            {/* Title Skeleton */}
            <div className="h-7 bg-slate-350 rounded w-44"></div>

            <div className="grid grid-cols-1 lg:grid-cols-3 gap-8 items-start">
              
              {/* Left Column: Cart items skeleton */}
              <div className="lg:col-span-2 space-y-4">
                {[...Array(2)].map((_, i) => (
                  <div key={i} className="flex gap-4 bg-white p-4 border border-slate-200/60 rounded-2xl items-center">
                    <div className="h-16 w-16 bg-slate-200 rounded-xl"></div>
                    <div className="flex-1 space-y-2">
                      <div className="h-4 bg-slate-200 rounded w-2/3"></div>
                      <div className="h-3.5 bg-slate-150 rounded w-1/4"></div>
                    </div>
                    <div className="h-9 w-24 bg-slate-150 rounded-xl"></div>
                    <div className="h-8 w-8 bg-slate-200 rounded-lg"></div>
                  </div>
                ))}
              </div>

              {/* Right Column: Cart summary skeleton */}
              <div className="bg-white p-6 border border-slate-200/60 rounded-3xl space-y-6">
                <div className="h-5 bg-slate-300 rounded w-32"></div>
                <div className="space-y-4">
                  <div className="flex justify-between">
                    <div className="h-4 bg-slate-200 rounded w-20"></div>
                    <div className="h-4 bg-slate-200 rounded w-10"></div>
                  </div>
                  <div className="flex justify-between pt-3 border-t border-slate-100">
                    <div className="h-4 bg-slate-300 rounded w-16"></div>
                    <div className="h-4 bg-slate-300 rounded w-12"></div>
                  </div>
                  <div className="h-3.5 bg-slate-200 rounded w-full"></div>
                </div>
                <div className="h-11 bg-slate-350 rounded-xl w-full"></div>
              </div>

            </div>
          </div>
        </main>
        <Footer />
      </>
    );
  }

  return (
    <>
      <Header />
      <main className="bg-slate-50 min-h-screen py-8">
        <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 space-y-6">
          <h1 className="text-xl font-black text-slate-900">Shopping Cart</h1>

          {cartItems.length === 0 ? (
            <div className="text-center py-24 bg-white border border-slate-200 rounded-3xl space-y-4 max-w-xl mx-auto shadow-sm">
              <div className="mx-auto h-12 w-12 text-slate-300 flex items-center justify-center">
                <ShoppingBag className="h-10 w-10" />
              </div>
              <h2 className="text-sm font-bold text-slate-800">Your cart is empty</h2>
              <p className="text-xxs text-slate-400">Add some items from our store to get started.</p>
              <Link
                href="/shop"
                className="inline-flex items-center gap-2 px-6 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl text-xs font-bold transition-all shadow-md shadow-indigo-100"
              >
                Start Shopping
              </Link>
            </div>
          ) : (
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-8 items-start">
              
              {/* Left Column: Cart items */}
              <div className="lg:col-span-2 space-y-4">
                {cartItems.map((item) => {
                  const resolvedImageUrl = item.image_url.startsWith('http') 
                    ? item.image_url 
                    : `${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000'}${item.image_url}`;

                  return (
                    <div
                      key={item.id}
                      className="flex gap-4 bg-white p-4 border border-slate-200 rounded-2xl items-center"
                    >
                      {/* Image */}
                      <Link href={`/products/${item.slug}`} className="h-16 w-16 flex-shrink-0 overflow-hidden bg-slate-100 rounded-xl border border-slate-150">
                        <img src={resolvedImageUrl} alt={item.name} className="h-full w-full object-cover" />
                      </Link>

                      {/* Detail */}
                      <div className="flex-1 min-w-0">
                        <h3 className="text-xs font-bold text-slate-800 truncate hover:text-indigo-600">
                          <Link href={`/products/${item.slug}`}>{item.name}</Link>
                        </h3>
                        
                        {/* Variant options */}
                        {item.options && Object.keys(item.options).length > 0 && (
                          <div className="flex gap-2 mt-1">
                            {Object.entries(item.options).map(([key, val]) => (
                              <span key={key} className="text-xxs bg-slate-100 border border-slate-200 text-slate-600 px-1.5 py-0.5 rounded-md">
                                {key}: {val}
                              </span>
                            ))}
                          </div>
                        )}

                        {isReseller ? (
                          <div className="flex flex-col gap-0.5 mt-2">
                            <span className="text-xs font-black text-slate-900 block">
                              {formatPrice(item.price)} <span className="text-[10px] text-slate-400 font-normal">(খুচরা)</span>
                            </span>
                            <span className="text-xs font-bold text-emerald-600 block">
                              রিসেলার দাম: {formatPrice(Number(item.reseller_price || 0))}
                            </span>
                            <span className="text-[10px] text-emerald-700 bg-emerald-50 border border-emerald-100 rounded px-1.5 py-0.5 self-start font-bold mt-1">
                              লাভ: {formatPrice(Math.max(0, item.price - Number(item.reseller_price || 0)) * item.quantity)}
                            </span>
                          </div>
                        ) : (
                          <span className="text-xs font-black text-slate-900 block mt-2">
                            {formatPrice(item.price)}
                          </span>
                        )}
                      </div>

                      {/* Qty Controls */}
                      <div className="flex items-center border border-slate-250 rounded-xl overflow-hidden bg-slate-50 h-9">
                        <button
                          onClick={() => handleQtyChange(item.id, item.quantity - 1, item.stock)}
                          className="px-2.5 text-slate-650 hover:bg-slate-150 font-bold transition-all text-xs cursor-pointer"
                        >
                          -
                        </button>
                        <span className="px-2 text-xxs font-bold text-slate-800">{item.quantity}</span>
                        <button
                          onClick={() => handleQtyChange(item.id, item.quantity + 1, item.stock)}
                          className="px-2.5 text-slate-650 hover:bg-slate-150 font-bold transition-all text-xs cursor-pointer"
                        >
                          +
                        </button>
                      </div>

                      {/* Remove Button */}
                      <button
                        onClick={() => removeItem(item.id)}
                        className="text-slate-400 hover:text-rose-500 p-2 transition-all"
                      >
                        <Trash2 className="h-4.5 w-4.5" />
                      </button>

                    </div>
                  );
                })}
              </div>

              {/* Right Column: Summary */}
              <div className="bg-white p-6 border border-slate-200 rounded-3xl space-y-6">
                <h2 className="text-sm font-bold text-slate-900 border-b border-slate-100 pb-3">Cart Summary</h2>

                <div className="space-y-3">
                  <div className="flex justify-between text-xs text-slate-500 font-semibold">
                    <span>Items Count</span>
                    <span>{cartItems.reduce((acc, item) => acc + item.quantity, 0)}</span>
                  </div>
                  <div className="flex justify-between text-xs text-slate-500 font-semibold border-t border-slate-105 pt-2.5">
                    <span>Sub total</span>
                    <span>{formatPrice(subtotal)}</span>
                  </div>
                  {isReseller && (
                    <div className="flex justify-between text-xs text-emerald-650 font-bold">
                      <span>রিসেলার লাভ (কমিশন)</span>
                      <span>{formatPrice(cartItems.reduce((acc, item) => acc + Math.max(0, item.price - Number(item.reseller_price || 0)) * item.quantity, 0))}</span>
                    </div>
                  )}
                  <div className="flex justify-between text-xs text-slate-500 font-semibold">
                    <span>Delivery cost</span>
                    <span>{formatPrice(0)}</span>
                  </div>
                  <div className="flex justify-between text-xs font-black text-slate-900 border-t border-slate-100 pt-3">
                    <span>Total</span>
                    <span>{formatPrice(subtotal)}</span>
                  </div>
                  <span className="text-xxs text-slate-400 block mt-1 leading-relaxed">
                    * Shipping fees will be calculated during the checkout steps.
                  </span>
                </div>

                <button
                  onClick={() => router.push('/checkout')}
                  className="w-full h-11 inline-flex items-center justify-center gap-2 bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-bold rounded-xl shadow-md shadow-indigo-100 transition-all"
                >
                  <span>Proceed to Checkout</span>
                  <ArrowRight className="h-4 w-4" />
                </button>
              </div>

            </div>
          )}
        </div>
      </main>
      <Footer />
    </>
  );
}

// Helper to format prices
function numberWithCommas(x: number | null | undefined) {
  if (x === null || x === undefined || isNaN(Number(x))) {
    return '0';
  }
  return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
