"use client";

import React, { useState } from "react";
import Link from "next/link";
import { useCart } from "@/context/CartContext";
import { PRODUCTS } from "@/data/products";
import {
  X,
  Plus,
  Minus,
  Trash2,
  ShoppingBag,
  Sparkles,
  ArrowRight,
  ShieldCheck,
  Tag,
  CheckCircle2,
} from "lucide-react";

export function CartDrawer() {
  const {
    cart,
    isCartOpen,
    setIsCartOpen,
    updateQuantity,
    removeFromCart,
    subtotal,
    shippingCost,
    discount,
    total,
    hasFreeShipping,
    amountNeededForFreeShipping,
    appliedCoupon,
    applyCoupon,
    removeCoupon,
    addToCart,
  } = useCart();

  const [couponCode, setCouponCode] = useState("");
  const [couponMsg, setCouponMsg] = useState<{
    text: string;
    isError: boolean;
  } | null>(null);

  // Cross-sell suggestion: pick a popular non-panettone product not in cart
  const crossSellProduct = PRODUCTS.find(
    (p) =>
      p.category === "Toñas y Magdalenas" &&
      !cart.some((item) => item.product.id === p.id)
  );

  const handleApplyCoupon = (e: React.FormEvent) => {
    e.preventDefault();
    if (!couponCode.trim()) return;
    const res = applyCoupon(couponCode);
    setCouponMsg({ text: res.message, isError: !res.success });
    if (res.success) setCouponCode("");
  };

  if (!isCartOpen) return null;

  return (
    <div className="fixed inset-0 z-50 overflow-hidden">
      {/* Backdrop */}
      <div
        className="absolute inset-0 bg-black/50 backdrop-blur-xs transition-opacity duration-300"
        onClick={() => setIsCartOpen(false)}
      />

      <div className="fixed inset-y-0 right-0 max-w-full flex pl-10">
        <div className="w-screen max-w-md bg-white shadow-2xl flex flex-col h-full animate-in slide-in-from-right duration-300">
          {/* Header */}
          <div className="px-6 py-4 bg-stone-900 text-stone-100 flex items-center justify-between border-b border-stone-800">
            <div className="flex items-center gap-2">
              <ShoppingBag className="w-5 h-5 text-amber-400" />
              <h2 className="font-serif text-lg font-bold">Tu Cesta Gourmet</h2>
              <span className="bg-amber-500/20 text-amber-300 text-xs px-2 py-0.5 rounded-full border border-amber-500/30">
                {cart.reduce((acc, i) => acc + i.quantity, 0)} artículos
              </span>
            </div>
            <button
              onClick={() => setIsCartOpen(false)}
              className="text-stone-400 hover:text-white p-1 rounded-md transition"
              aria-label="Cerrar carrito"
            >
              <X className="w-5 h-5" />
            </button>
          </div>

          {/* Dynamic Free Shipping Progress Bar */}
          <div className="bg-amber-50 px-6 py-3 border-b border-amber-200/60">
            {hasFreeShipping ? (
              <div className="flex items-center gap-2 text-emerald-800 text-xs font-semibold">
                <CheckCircle2 className="w-4 h-4 text-emerald-600 shrink-0" />
                <span>¡Enhorabuena! Tienes <strong>Gastos de Envío GRATIS</strong> en este pedido.</span>
              </div>
            ) : (
              <div>
                <div className="flex justify-between items-center text-xs font-medium text-amber-950 mb-1.5">
                  <span>
                    Añade un <strong>Panettone</strong> o <strong>{amountNeededForFreeShipping.toFixed(2)}€</strong> más
                  </span>
                  <span className="text-[11px] font-bold text-amber-700">
                    {Math.min(100, Math.round((subtotal / 50) * 100))}%
                  </span>
                </div>
                <div className="w-full bg-amber-200/70 rounded-full h-2 overflow-hidden">
                  <div
                    className="bg-amber-600 h-2 rounded-full transition-all duration-500"
                    style={{
                      width: `${Math.min(100, (subtotal / 50) * 100)}%`,
                    }}
                  />
                </div>
              </div>
            )}
          </div>

          {/* Cart Items Scrollable List */}
          <div className="flex-1 overflow-y-auto p-6 space-y-4">
            {cart.length === 0 ? (
              <div className="text-center py-12">
                <div className="w-16 h-16 bg-amber-100/70 rounded-full flex items-center justify-center mx-auto mb-4 text-amber-900">
                  <ShoppingBag className="w-8 h-8 opacity-60" />
                </div>
                <h3 className="font-serif text-lg font-bold text-stone-800 mb-1">
                  Tu carrito está vacío
                </h3>
                <p className="text-xs text-stone-500 max-w-xs mx-auto mb-6">
                  Descubre nuestros panettones artesanos elaborados con masa madre de cultivo y 4 días de fermentación.
                </p>
                <button
                  onClick={() => setIsCartOpen(false)}
                  className="bg-amber-900 hover:bg-amber-950 text-amber-50 px-6 py-2.5 rounded-full text-xs font-bold uppercase tracking-wider transition"
                >
                  Explorar Panettones
                </button>
              </div>
            ) : (
              <>
                <div className="divide-y divide-stone-100">
                  {cart.map((item) => (
                    <div key={item.product.id} className="py-4 flex gap-4">
                      {/* eslint-disable-next-line @next/next/no-img-element */}
                      <img
                        src={item.product.thumbnail}
                        alt={item.product.name}
                        className="w-18 h-18 object-cover rounded-lg border border-stone-200 shrink-0"
                      />
                      <div className="flex-1 min-w-0">
                        <div className="flex justify-between items-start gap-2">
                          <h4 className="text-sm font-semibold text-stone-900 truncate">
                            {item.product.name}
                          </h4>
                          <button
                            onClick={() => removeFromCart(item.product.id)}
                            className="text-stone-400 hover:text-rose-600 transition p-1"
                            title="Eliminar producto"
                          >
                            <Trash2 className="w-4 h-4" />
                          </button>
                        </div>
                        <p className="text-xs text-stone-500 mb-2">
                          {item.product.weight}
                        </p>
                        <div className="flex items-center justify-between">
                          <div className="flex items-center border border-stone-300 rounded-md bg-stone-50">
                            <button
                              onClick={() =>
                                updateQuantity(item.product.id, item.quantity - 1)
                              }
                              className="p-1 hover:bg-stone-200 text-stone-600 transition"
                            >
                              <Minus className="w-3.5 h-3.5" />
                            </button>
                            <span className="px-2.5 text-xs font-bold text-stone-800">
                              {item.quantity}
                            </span>
                            <button
                              onClick={() =>
                                updateQuantity(item.product.id, item.quantity + 1)
                              }
                              className="p-1 hover:bg-stone-200 text-stone-600 transition"
                            >
                              <Plus className="w-3.5 h-3.5" />
                            </button>
                          </div>
                          <span className="font-bold text-sm text-amber-950">
                            {(item.product.price * item.quantity).toFixed(2)} €
                          </span>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>

                {/* Cross-sell Recommendation Box */}
                {crossSellProduct && (
                  <div className="mt-4 bg-amber-50/70 border border-amber-200/70 rounded-xl p-3 flex items-center justify-between gap-3">
                    <div className="flex items-center gap-2.5">
                      {/* eslint-disable-next-line @next/next/no-img-element */}
                      <img
                        src={crossSellProduct.thumbnail}
                        alt={crossSellProduct.name}
                        className="w-11 h-11 object-cover rounded-md border border-amber-200"
                      />
                      <div className="min-w-0">
                        <span className="text-[10px] uppercase font-bold text-amber-800 tracking-wider flex items-center gap-1">
                          <Sparkles className="w-3 h-3 text-amber-600" /> Especialidad
                        </span>
                        <h5 className="text-xs font-semibold text-stone-900 truncate">
                          {crossSellProduct.name}
                        </h5>
                        <span className="text-xs font-bold text-amber-950">
                          +{crossSellProduct.price.toFixed(2)} €
                        </span>
                      </div>
                    </div>
                    <button
                      onClick={() => addToCart(crossSellProduct, 1)}
                      className="bg-amber-900 hover:bg-amber-950 text-amber-50 text-xs px-3 py-1.5 rounded-md font-semibold transition shrink-0"
                    >
                      Añadir
                    </button>
                  </div>
                )}

                {/* Coupon Box */}
                <div className="pt-2">
                  {appliedCoupon ? (
                    <div className="bg-emerald-50 border border-emerald-200 rounded-lg p-2.5 flex items-center justify-between text-xs text-emerald-800">
                      <div className="flex items-center gap-2">
                        <Tag className="w-4 h-4 text-emerald-600" />
                        <span>
                          Cupón aplicado: <strong>{appliedCoupon.code}</strong>{" "}
                          ({appliedCoupon.discountPercent ? `${appliedCoupon.discountPercent}%` : `${appliedCoupon.discountAmount}€`})
                        </span>
                      </div>
                      <button
                        onClick={removeCoupon}
                        className="text-emerald-700 hover:text-emerald-900 font-bold underline text-[11px]"
                      >
                        Quitar
                      </button>
                    </div>
                  ) : (
                    <form onSubmit={handleApplyCoupon} className="flex gap-2">
                      <input
                        type="text"
                        placeholder="Cupón de descuento (ej. BIENVENIDO10)"
                        value={couponCode}
                        onChange={(e) => setCouponCode(e.target.value)}
                        className="flex-1 border border-stone-300 rounded-md px-3 py-1.5 text-xs outline-none focus:border-amber-700 uppercase"
                      />
                      <button
                        type="submit"
                        className="bg-stone-800 hover:bg-stone-900 text-stone-100 text-xs px-3 py-1.5 rounded-md font-semibold transition"
                      >
                        Aplicar
                      </button>
                    </form>
                  )}
                  {couponMsg && (
                    <p
                      className={`text-[11px] mt-1.5 ${
                        couponMsg.isError ? "text-rose-600" : "text-emerald-700 font-medium"
                      }`}
                    >
                      {couponMsg.text}
                    </p>
                  )}
                </div>
              </>
            )}
          </div>

          {/* Footer with Totals and Checkout CTA */}
          {cart.length > 0 && (
            <div className="p-6 bg-stone-50 border-t border-stone-200 space-y-3">
              <div className="space-y-1.5 text-xs text-stone-600">
                <div className="flex justify-between">
                  <span>Subtotal (IVA incluido)</span>
                  <span className="font-semibold text-stone-900">
                    {subtotal.toFixed(2)} €
                  </span>
                </div>
                {discount > 0 && (
                  <div className="flex justify-between text-emerald-700 font-medium">
                    <span>Descuento aplicado</span>
                    <span>-{discount.toFixed(2)} €</span>
                  </div>
                )}
                <div className="flex justify-between">
                  <span>Gastos de envío (24-48h)</span>
                  {shippingCost === 0 ? (
                    <span className="font-bold text-emerald-700 uppercase text-[11px]">
                      GRATIS
                    </span>
                  ) : (
                    <span className="font-semibold text-stone-900">
                      {shippingCost.toFixed(2)} €
                    </span>
                  )}
                </div>
                <div className="flex justify-between text-base font-serif font-bold text-stone-900 pt-2 border-t border-stone-200">
                  <span>Total Pedido</span>
                  <span className="text-amber-950 font-sans text-lg">
                    {total.toFixed(2)} €
                  </span>
                </div>
              </div>

              {/* Checkout Button */}
              <Link
                href="/checkout"
                onClick={() => setIsCartOpen(false)}
                className="w-full bg-amber-900 hover:bg-amber-950 text-amber-50 py-3 rounded-lg font-bold text-sm tracking-wide flex items-center justify-center gap-2 shadow-md hover:shadow-lg transition transform active:scale-98"
              >
                <span>Tramitar Pedido</span>
                <ArrowRight className="w-4 h-4" />
              </Link>

              {/* Trust Badges */}
              <div className="flex items-center justify-center gap-4 pt-1 text-[11px] text-stone-500">
                <span className="flex items-center gap-1">
                  <ShieldCheck className="w-3.5 h-3.5 text-emerald-600" />
                  Pago 100% Seguro
                </span>
                <span>·</span>
                <span>Redsys / Bizum / PayPal</span>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
