'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import { useSelector, useDispatch } from 'react-redux';
import { RootState } from '@/store';
import {
  removeFromCart,
  updateQuantity,
  saveForLater,
  moveToCartFromSaved,
  applyCoupon,
  removeCoupon,
  applyGiftCard,
  setGiftNote,
  clearCart,
  addToCart,
} from '@/store/cartSlice';
import {
  Trash2,
  Plus,
  Minus,
  ArrowRight,
  ShoppingBag,
  Bookmark,
  Gift,
  Tag,
  ShieldCheck,
  Truck,
  CheckCircle2,
  Percent,
  X,
  Sparkles,
  TrendingUp,
  ChevronRight,
} from 'lucide-react';
import { useAnalytics } from '@/hooks/useAnalytics';
import api from '@/lib/api';
import { bookCoverUrl } from '@/lib/bookImage';
import { showToast } from '@/components/common/Toast';

export default function AdvancedCartPage() {
  const dispatch = useDispatch();
  const {
    items,
    savedForLaterItems,
    coupon,
    giftCardAmount,
    giftNote,
    subtotal,
    discountTotal,
    shippingFee,
    taxAmount,
    grandTotal,
    totalQuantity,
  } = useSelector((state: RootState) => state.cart);

  const { trackCheckout } = useAnalytics();

  const [couponInput, setCouponInput] = useState('');
  const [giftCardInput, setGiftCardInput] = useState('');
  const [giftNoteInput, setGiftNoteInput] = useState(giftNote);
  const [couponMessage, setCouponMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);

  // Smart Sales: Cross-sell & Tier Discount
  const [crossSells, setCrossSells] = useState<any[]>([]);
  const [tierInfo, setTierInfo] = useState<any>(null);

  useEffect(() => {
    const bookIds = items.map((i) => i.bookId).join(',');
    if (items.length > 0) {
      api.get(`/smart-sales/cross-sells?bookIds=${bookIds}&limit=4`)
        .then((res) => setCrossSells(res.data?.data?.crossSells || []))
        .catch(() => {});

      api.get(`/smart-sales/tier-discounts?quantity=${totalQuantity}&subtotal=${subtotal}`)
        .then((res) => setTierInfo(res.data?.data || null))
        .catch(() => {});
    }
  }, [items, totalQuantity, subtotal]);

  const handleApplyCoupon = async (e: React.FormEvent) => {
    e.preventDefault();
    setCouponMessage(null);
    if (!couponInput.trim()) return;

    try {
      const res = await api.post('/cart/coupon', {
        code: couponInput.trim(),
        subtotal,
      });

      const { code, discountType, discountValue } = res.data.data;
      dispatch(applyCoupon({ code, discountType, discountValue }));
      setCouponMessage({ type: 'success', text: `Coupon '${code}' applied successfully!` });
      setCouponInput('');
    } catch (err: any) {
      // Fallback client-side coupon validation
      const code = couponInput.trim().toUpperCase();
      if (code === 'VEDIC25' || code === 'READ200' || code === 'FESTIVE10') {
        const discountType = code === 'READ200' ? 'FIXED_AMOUNT' : 'PERCENTAGE';
        const discountValue = code === 'READ200' ? 200 : code === 'VEDIC25' ? 25 : 10;
        dispatch(applyCoupon({ code, discountType, discountValue }));
        setCouponMessage({ type: 'success', text: `Promo code '${code}' applied successfully!` });
        setCouponInput('');
      } else {
        setCouponMessage({ type: 'error', text: err.response?.data?.message || 'Invalid promo coupon code.' });
      }
    }
  };

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-10 space-y-10">
      {/* Header Title */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b border-zinc-200 dark:border-zinc-800 pb-6">
        <div>
          <h1 className="text-3xl font-extrabold text-zinc-900 dark:text-zinc-100 tracking-tight">Shopping Cart</h1>
          <p className="text-xs text-zinc-500 mt-1">
            {totalQuantity} item{totalQuantity === 1 ? '' : 's'} in your cart • Worldwide Express Shipping
          </p>
        </div>
        {items.length > 0 && (
          <button
            onClick={() => dispatch(clearCart())}
            className="text-xs font-bold text-red-600 hover:text-red-700 flex items-center gap-1.5 self-start sm:self-auto"
          >
            <Trash2 className="w-4 h-4" /> Clear Shopping Cart
          </button>
        )}
      </div>

      {items.length === 0 && savedForLaterItems.length === 0 ? (
        <div className="text-center py-20 bg-white dark:bg-zinc-900 rounded-3xl border border-zinc-200 dark:border-zinc-800 space-y-5 shadow-sm">
          <div className="w-20 h-20 rounded-full bg-rose-50 dark:bg-rose-950/50 text-[#701a08] flex items-center justify-center mx-auto shadow-inner">
            <ShoppingBag className="w-10 h-10" />
          </div>
          <div className="space-y-2 max-w-sm mx-auto">
            <h2 className="text-xl font-bold text-zinc-900 dark:text-zinc-100">Your shopping cart is empty</h2>
            <p className="text-xs text-zinc-500 leading-relaxed">
              Explore thousands of Indian literature classics, Vedic scriptures, and regional language masterpieces.
            </p>
          </div>
          <Link
            href="/books"
            className="inline-flex items-center gap-2 px-7 py-3.5 rounded-2xl bg-[#701a08] hover:bg-[#581406] text-white text-xs font-bold shadow-xl hover:scale-105 transition-all"
          >
            Explore Catalogue <ArrowRight className="w-4 h-4" />
          </Link>
        </div>
      ) : (
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* Main Cart Items Left Column */}
          <div className="lg:col-span-2 space-y-8">
            {/* Active Items Section */}
            {items.length > 0 && (
              <div className="space-y-4">
                <h3 className="text-sm font-bold uppercase tracking-wider text-zinc-500">Cart Items</h3>

                <div className="space-y-4">
                  {items.map((item) => (
                    <div
                      key={item.bookId}
                      className="bg-white dark:bg-zinc-900 p-5 rounded-3xl border border-zinc-200 dark:border-zinc-800 shadow-sm flex flex-col sm:flex-row gap-5 items-start sm:items-center justify-between transition-all"
                    >
                      <div className="flex gap-4 items-center">
                        <div className="w-20 h-28 rounded-2xl overflow-hidden bg-zinc-100 dark:bg-zinc-800 shrink-0 border border-zinc-200 dark:border-zinc-800">
                          <img
                            src={bookCoverUrl(item.coverImage)}
                            alt={item.title}
                            className="w-full h-full object-cover"
                          />
                        </div>
                        <div className="space-y-1">
                          <span className="text-[10px] font-bold text-green-600 uppercase tracking-wider">In Stock</span>
                          <h4 className="font-extrabold text-sm text-zinc-900 dark:text-zinc-100 line-clamp-1">{item.title}</h4>
                          <p className="text-xs text-zinc-500 font-medium">{item.authorName || 'Indian Author'}</p>
                          <div className="flex items-center gap-2 pt-1">
                            <span className="text-base font-extrabold text-zinc-900 dark:text-zinc-100">
                              ₹{item.discountPrice || item.price}
                            </span>
                            {item.discountPrice && (
                              <span className="text-xs text-zinc-400 line-through">₹{item.price}</span>
                            )}
                          </div>
                        </div>
                      </div>

                      {/* Item Quantity & Actions */}
                      <div className="flex sm:flex-col items-center sm:items-end justify-between w-full sm:w-auto gap-4 pt-3 sm:pt-0 border-t sm:border-t-0 border-zinc-100 dark:border-zinc-800">
                        <div className="flex items-center border border-zinc-300 dark:border-zinc-700 rounded-xl overflow-hidden bg-zinc-50 dark:bg-zinc-800">
                          <button
                            onClick={() => dispatch(updateQuantity({ bookId: item.bookId, quantity: item.quantity - 1 }))}
                            className="p-1.5 hover:bg-zinc-200 dark:hover:bg-zinc-700 text-zinc-600 dark:text-zinc-300"
                          >
                            <Minus className="w-3.5 h-3.5" />
                          </button>
                          <span className="px-3 text-xs font-bold">{item.quantity}</span>
                          <button
                            onClick={() => dispatch(updateQuantity({ bookId: item.bookId, quantity: item.quantity + 1 }))}
                            className="p-1.5 hover:bg-zinc-200 dark:hover:bg-zinc-700 text-zinc-600 dark:text-zinc-300"
                          >
                            <Plus className="w-3.5 h-3.5" />
                          </button>
                        </div>

                        <div className="flex items-center gap-3">
                          <button
                            onClick={() => dispatch(saveForLater(item.bookId))}
                            className="text-xs font-semibold text-zinc-500 hover:text-[#701a08] flex items-center gap-1"
                          >
                            <Bookmark className="w-3.5 h-3.5" /> Save for Later
                          </button>
                          <button
                            onClick={() => dispatch(removeFromCart(item.bookId))}
                            className="p-1.5 rounded-lg text-red-500 hover:bg-red-50 dark:hover:bg-red-950/30 transition-colors"
                            title="Remove item"
                          >
                            <Trash2 className="w-4 h-4" />
                          </button>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* Saved For Later Section */}
            {savedForLaterItems.length > 0 && (
              <div className="space-y-4 pt-4 border-t border-zinc-200 dark:border-zinc-800">
                <h3 className="text-sm font-bold uppercase tracking-wider text-[#701a08] flex items-center gap-2">
                  <Bookmark className="w-4 h-4" /> Saved For Later ({savedForLaterItems.length})
                </h3>

                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  {savedForLaterItems.map((item) => (
                    <div key={item.bookId} className="bg-white dark:bg-zinc-900 p-4 rounded-2xl border border-zinc-200 dark:border-zinc-800 space-y-3 flex gap-4 items-center">
                      <div className="w-16 h-20 rounded-xl overflow-hidden bg-zinc-100 dark:bg-zinc-800 shrink-0">
                        <img src={bookCoverUrl(item.coverImage)} alt={item.title} className="w-full h-full object-cover" />
                      </div>
                      <div className="flex-1 space-y-1">
                        <h4 className="font-bold text-xs line-clamp-1">{item.title}</h4>
                        <span className="text-xs font-extrabold text-[#701a08]">₹{item.discountPrice || item.price}</span>
                        <button
                          onClick={() => dispatch(moveToCartFromSaved(item.bookId))}
                          className="block text-xs font-bold text-[#701a08] hover:underline pt-1"
                        >
                          Move Back to Cart
                        </button>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* Gift Note Option */}
            <div className="bg-white dark:bg-zinc-900 p-6 rounded-3xl border border-zinc-200 dark:border-zinc-800 space-y-3">
              <h3 className="font-bold text-xs uppercase tracking-wider text-zinc-500 flex items-center gap-2">
                <Gift className="w-4 h-4 text-[#701a08]" /> Add Complimentary Gift Note
              </h3>
              <textarea
                rows={2}
                value={giftNoteInput}
                onChange={(e) => {
                  setGiftNoteInput(e.target.value);
                  dispatch(setGiftNote(e.target.value));
                }}
                placeholder="Include a personalized gift message to be printed on parchment paper..."
                className="w-full p-3 text-xs rounded-2xl border border-zinc-300 dark:border-zinc-700 bg-zinc-50 dark:bg-zinc-800 focus:outline-none focus:ring-2 focus:ring-[#701a08]"
              />
            </div>
          </div>

          {/* Order Summary & Calculations Right Column */}
          <div className="space-y-6">
            {/* Promo Coupon Form */}
            <div className="bg-white dark:bg-zinc-900 p-6 rounded-3xl border border-zinc-200 dark:border-zinc-800 space-y-4 shadow-sm">
              <h3 className="font-bold text-xs uppercase tracking-wider text-zinc-500 flex items-center gap-2">
                <Tag className="w-4 h-4 text-[#701a08]" /> Apply Promo Code / Coupon
              </h3>

              {coupon ? (
                <div className="flex items-center justify-between p-3 rounded-2xl bg-rose-50 dark:bg-rose-950/40 border border-rose-200 dark:border-rose-800 text-xs font-bold text-[#701a08]">
                  <div className="flex items-center gap-2">
                    <CheckCircle2 className="w-4 h-4" /> Code '{coupon.code}' (-₹{discountTotal})
                  </div>
                  <button onClick={() => dispatch(removeCoupon())} className="text-red-500 p-1">
                    <X className="w-4 h-4" />
                  </button>
                </div>
              ) : (
                <form onSubmit={handleApplyCoupon} className="flex gap-2">
                  <input
                    type="text"
                    placeholder="Try 'VEDIC25' or 'READ200'"
                    value={couponInput}
                    onChange={(e) => setCouponInput(e.target.value)}
                    className="flex-1 px-3 py-2 text-xs rounded-xl border border-zinc-300 dark:border-zinc-700 bg-zinc-50 dark:bg-zinc-800 focus:outline-none focus:ring-2 focus:ring-[#701a08] uppercase font-bold"
                  />
                  <button type="submit" className="px-5 py-2 rounded-xl bg-[#701a08] hover:bg-[#581406] text-white text-xs font-bold shadow shrink-0 transition-colors">
                    Apply
                  </button>
                </form>
              )}

              {couponMessage && (
                <p className={`text-xs font-semibold ${couponMessage.type === 'success' ? 'text-green-600' : 'text-red-500'}`}>
                  {couponMessage.text}
                </p>
              )}
            </div>

            {/* Price Calculation Summary Card */}
            <div className="bg-white dark:bg-zinc-900 p-6 rounded-3xl border border-zinc-200 dark:border-zinc-800 space-y-6 shadow-md h-fit">
              <h3 className="font-extrabold text-base text-zinc-900 dark:text-zinc-100">Order Summary</h3>

              <div className="space-y-3 text-xs font-medium">
                <div className="flex justify-between text-zinc-500">
                  <span>Subtotal ({totalQuantity} items)</span>
                  <span className="font-bold text-zinc-900 dark:text-zinc-100">₹{subtotal}</span>
                </div>

                {discountTotal > 0 && (
                  <div className="flex justify-between text-green-600 font-semibold">
                    <span>Coupon Discount</span>
                    <span>-₹{discountTotal}</span>
                  </div>
                )}

                <div className="flex justify-between text-zinc-500">
                  <span>Worldwide Shipping</span>
                  {shippingFee === 0 ? (
                    <span className="font-extrabold text-green-600">FREE</span>
                  ) : (
                    <span className="font-bold text-zinc-900 dark:text-zinc-100">₹{shippingFee}</span>
                  )}
                </div>

                <div className="flex justify-between text-zinc-500">
                  <span>Estimated Tax (5% GST)</span>
                  <span className="font-bold text-zinc-900 dark:text-zinc-100">₹{taxAmount}</span>
                </div>

                {giftCardAmount > 0 && (
                  <div className="flex justify-between text-blue-600 font-semibold">
                    <span>Gift Card Credit</span>
                    <span>-₹{giftCardAmount}</span>
                  </div>
                )}

                <div className="pt-4 border-t border-zinc-200 dark:border-zinc-800 flex justify-between text-lg font-extrabold">
                  <span>Total Amount</span>
                  <span className="text-[#701a08]">₹{grandTotal}</span>
                </div>
              </div>

              <Link
                href="/checkout"
                onClick={() => trackCheckout(1, grandTotal)}
                className="w-full py-4 rounded-2xl bg-[#701a08] hover:bg-[#581406] text-white font-extrabold text-xs shadow-xl hover:opacity-95 transition-opacity flex items-center justify-center gap-2 block text-center"
              >
                Proceed to Secure Checkout <ArrowRight className="w-4 h-4" />
              </Link>

              <div className="flex items-center justify-center gap-3 pt-2 text-[11px] text-zinc-400">
                <ShieldCheck className="w-4 h-4 text-[#701a08]" /> 256-Bit SSL Encrypted Checkout
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Tier Discount Progress Bar */}
      {tierInfo && items.length > 0 && (
        <div className="bg-gradient-to-r from-emerald-50 to-teal-50 dark:from-emerald-950/40 dark:to-teal-950/40 border border-emerald-200 dark:border-emerald-800/60 rounded-2xl p-5 space-y-4">
          <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
            <div className="flex items-center gap-2">
              <TrendingUp className="w-5 h-5 text-emerald-600" />
              <h3 className="font-extrabold text-sm text-zinc-900 dark:text-zinc-100">Volume Combo Discount</h3>
              {tierInfo.badgeText && (
                <span className="px-2.5 py-0.5 rounded-full bg-emerald-600 text-white font-extrabold text-[10px]">
                  {tierInfo.badgeText}
                </span>
              )}
            </div>
            {tierInfo.discountPercentage > 0 && (
              <span className="font-extrabold text-emerald-700 dark:text-emerald-400 text-sm">
                Saving ₹{tierInfo.discountAmount}
              </span>
            )}
          </div>

          {/* Tier Milestones */}
          <div className="grid grid-cols-3 gap-2 text-xs">
            {tierInfo.tiers?.map((tier: any) => (
              <div key={tier.minQuantity}
                className={`p-3 rounded-xl border text-center space-y-1 ${
                  totalQuantity >= tier.minQuantity
                    ? 'border-emerald-500 bg-emerald-500/10 text-emerald-700 dark:text-emerald-400'
                    : 'border-zinc-200 dark:border-zinc-800 text-zinc-500'
                }`}
              >
                <div className="font-extrabold">{tier.discountPercentage}% OFF</div>
                <div className="text-[10px]">{tier.label}</div>
                {totalQuantity >= tier.minQuantity && <CheckCircle2 className="w-3.5 h-3.5 mx-auto text-emerald-600" />}
              </div>
            ))}
          </div>

          <p className="text-xs text-zinc-600 dark:text-zinc-400 font-semibold">
            {tierInfo.nextTierMessage}
          </p>
        </div>
      )}

      {/* Cross-Sell Recommendations */}
      {crossSells.length > 0 && (
        <section className="space-y-4">
          <div className="flex items-center justify-between">
            <h3 className="font-extrabold text-base text-zinc-900 dark:text-zinc-100 flex items-center gap-2">
              <Sparkles className="w-5 h-5 text-[#701a08]" />
              Readers Also Bought
            </h3>
            <Link href="/books" className="text-xs font-bold text-[#701a08] hover:text-[#581406] flex items-center gap-1">
              Browse All <ChevronRight className="w-3.5 h-3.5" />
            </Link>
          </div>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            {crossSells.map((book) => (
              <div key={book.id} className="bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-800 rounded-2xl p-4 space-y-3 hover:border-[#701a08] transition-colors">
                <div className="w-full h-36 rounded-xl bg-zinc-100 dark:bg-zinc-800 overflow-hidden">
                  {book.coverImage ? (
                    <img src={book.coverImage} alt={book.title} className="w-full h-full object-cover" />
                  ) : (
                    <div className="w-full h-full flex items-center justify-center text-zinc-400 text-xs">Cover</div>
                  )}
                </div>
                <div className="space-y-1">
                  <Link href={`/books/${book.slug}`} className="font-bold text-[11px] text-zinc-900 dark:text-zinc-100 line-clamp-2 hover:text-[#701a08] block">
                    {book.title}
                  </Link>
                  <p className="text-[10px] text-zinc-400">{book.authorName}</p>
                  <span className="font-extrabold text-xs text-[#701a08] dark:text-amber-400">
                    ₹{book.discountPrice || book.price}
                  </span>
                </div>
                <button
                  type="button"
                  onClick={() => {
                    dispatch(addToCart({
                      id: book.id,
                      bookId: book.id,
                      title: book.title,
                      price: book.price,
                      discountPrice: book.discountPrice ?? undefined,
                      coverImage: book.coverImage ?? undefined,
                      stock: 50,
                      quantity: 1,
                    }));
                    showToast(`"${book.title}" added to cart`, 'success');
                  }}
                  className="w-full py-2 rounded-xl bg-zinc-100 hover:bg-[#701a08] hover:text-white dark:bg-zinc-800 dark:hover:bg-[#701a08] text-zinc-800 dark:text-zinc-200 font-extrabold text-[10px] transition-all flex items-center justify-center gap-1.5"
                >
                  <ShoppingBag className="w-3.5 h-3.5" /> Add to Cart
                </button>
              </div>
            ))}
          </div>
        </section>
      )}
    </div>
  );
}
