"use client";

import { useEffect } from "react";
import { normalizeMediaUrl } from "@/lib/media-url";
import { motion, AnimatePresence } from "framer-motion";
import { ShoppingCart, Plus, Minus, Trash2, Loader2, Package, Ticket } from "lucide-react";
import { useCart, Product, type PaymentMethod } from "@/components/CartContext";
import { CHILE_REGIONS } from "@/lib/chile-regions";
import { BRAND } from "@/lib/brand";

const PHONE_LENGTH = 9;

/** Color del cuerpo de cada boleto */
const PACK_GRADIENTS = [
  "from-brand-cyan to-brand-green",
  "from-brand-purple via-brand-violet to-brand-pink",
  "from-brand-pink to-brand-purple",
];

export default function StoreFront({
  initialProducts,
  isLoggedIn = false,
  enabledPaymentMethods = ["mercadopago"] as PaymentMethod[],
}: {
  initialProducts: Product[];
  isLoggedIn?: boolean;
  enabledPaymentMethods?: PaymentMethod[];
}) {
  const {
    cart,
    isCartOpen,
    setIsCartOpen,
    addToCart,
    removeFromCart,
    updateQuantity,
    total,
    guestEmail,
    setGuestEmail,
    buyerName,
    setBuyerName,
    buyerPhone,
    setBuyerPhone,
    hasPhysicalItems,
    shipping,
    setShippingAddress,
    setShippingComuna,
    setShippingRegion,
    setShippingNotes,
    paymentMethod,
    setPaymentMethod,
    isCheckoutLoading,
    handleCheckout,
    syncProductPrices,
  } = useCart();

  void isLoggedIn;

  // cart.length en deps: el carrito se carga de localStorage después del primer render.
  useEffect(() => {
    syncProductPrices(initialProducts);
  }, [initialProducts, syncProductPrices, cart.length]);

  const sortedProducts = [...initialProducts].sort((a, b) => a.price - b.price);
  const featuredIndex = Math.floor(sortedProducts.length / 2);

  const mpEnabled = enabledPaymentMethods.includes("mercadopago");
  const paykuEnabled = enabledPaymentMethods.includes("payku");
  const hasAnyPayment = enabledPaymentMethods.length > 0;

  useEffect(() => {
    if (!hasAnyPayment) return;
    if (!enabledPaymentMethods.includes(paymentMethod)) {
      setPaymentMethod(enabledPaymentMethods[0]);
    }
  }, [enabledPaymentMethods, hasAnyPayment, paymentMethod, setPaymentMethod]);

  const handleNameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setBuyerName(e.target.value);
  };

  const handlePhoneChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setBuyerPhone(e.target.value);
  };

  return (
    <div>
      {/* Floating Cart Button */}
      <button
        onClick={() => setIsCartOpen(true)}
        aria-label="Abrir carrito"
        className="fixed bottom-6 right-6 z-50 flex items-center justify-center rounded-full bg-brand-gradient p-4 shadow-lg shadow-brand-purple/30 transition-transform hover:scale-105"
      >
        <ShoppingCart className="h-6 w-6 text-white" />
        {cart.length > 0 && (
          <span className="absolute -right-1.5 -top-1.5 flex h-6 w-6 items-center justify-center rounded-full bg-brand-pink text-xs font-bold text-white">
            {cart.reduce((acc, item) => acc + item.quantity, 0)}
          </span>
        )}
      </button>

      {/* Packs de boletos: diseño de boleto físico (cuerpo + perforado + talón) */}
      {sortedProducts.length === 0 ? (
        <p className="card-soft mx-auto max-w-md p-8 text-center text-brand-muted">
          Pronto habilitaremos la venta de boletos.
        </p>
      ) : (
        <div className="grid grid-cols-1 gap-6 md:grid-cols-3">
          {sortedProducts.map((product, i) => {
            const featured = sortedProducts.length >= 3 && i === featuredIndex;
            const soldOut = product.isLimited && product.stock <= 0;
            const hasDiscount = !!product.originalPrice && product.originalPrice > product.price;
            const count = product.ticketCount ?? 1;
            const perTicket = Math.round(product.price / Math.max(1, count));
            return (
              <motion.div
                key={product.id}
                whileHover={{ y: -8, rotate: featured ? 0 : i === 0 ? -1 : 1 }}
                transition={{ type: "spring", stiffness: 260, damping: 18 }}
                className={`relative flex flex-col drop-shadow-xl ${featured ? "md:-mt-4" : ""}`}
              >
                {featured && (
                  <span className="absolute -top-3 left-1/2 z-20 -translate-x-1/2 rounded-full bg-brand-pink px-4 py-1 text-xs font-bold text-white shadow-md">
                    ★ Más elegido
                  </span>
                )}

                {/* Cuerpo del boleto */}
                <div className={`relative overflow-hidden rounded-t-3xl bg-gradient-to-br ${PACK_GRADIENTS[i % PACK_GRADIENTS.length]} px-6 pb-6 pt-7 text-white`}>
                  <span className="pointer-events-none absolute -right-8 -top-8 h-32 w-32 rounded-full bg-white/15" />
                  <span className="pointer-events-none absolute -bottom-10 left-10 h-24 w-24 rounded-full bg-white/10" />
                  <div className="relative flex items-start justify-between">
                    <p className="font-script text-2xl leading-none text-white/95">Gran Sorteo</p>
                    {hasDiscount ? (
                      <span className="rounded-full bg-white px-2.5 py-0.5 text-xs font-bold text-brand-pink">
                        -{Math.round((1 - product.price / product.originalPrice!) * 100)}%
                      </span>
                    ) : (
                      <Ticket className="h-6 w-6 text-white/70" aria-hidden />
                    )}
                  </div>
                  <p className="relative mt-4 flex items-baseline gap-2">
                    <span className="font-serif text-6xl font-bold leading-none">{count}</span>
                    <span className="text-lg font-semibold text-white/90">{count === 1 ? "boleto" : "boletos"}</span>
                  </p>
                  <p className="relative mt-3 min-h-[2.5rem] text-sm text-white/90">
                    {product.description || product.name}
                  </p>
                </div>

                {/* Perforado con muescas laterales */}
                <div className="relative h-6 bg-white">
                  <span className="absolute -left-3 top-1/2 h-6 w-6 -translate-y-1/2 rounded-full bg-brand-soft" />
                  <span className="absolute -right-3 top-1/2 h-6 w-6 -translate-y-1/2 rounded-full bg-brand-soft" />
                  <span className="absolute inset-x-5 top-1/2 border-t-2 border-dashed border-slate-300" />
                </div>

                {/* Talón */}
                <div className="flex flex-1 flex-col rounded-b-3xl bg-white px-6 pb-6 pt-2">
                  <div className="flex items-end justify-between gap-3">
                    <div>
                      {hasDiscount && (
                        <span className="block text-sm text-slate-400 line-through">
                          ${product.originalPrice!.toLocaleString("es-CL")}
                        </span>
                      )}
                      <span className="font-serif text-3xl font-bold text-brand-ink">
                        ${product.price.toLocaleString("es-CL")}
                      </span>
                      {count > 1 && (
                        <span className="block text-xs text-brand-muted">
                          ${perTicket.toLocaleString("es-CL")} c/u
                        </span>
                      )}
                    </div>
                    <span className="rounded-lg border-2 border-dashed border-slate-200 px-2 py-1 font-mono text-[10px] text-slate-400">
                      Nº {BRAND.ticketPrefix}•••
                    </span>
                  </div>
                  <p className="mt-2 text-xs font-bold text-brand-cyan">
                    {soldOut
                      ? "Agotado"
                      : product.isLimited
                        ? `Quedan ${product.stock.toLocaleString("es-CL")} disponibles`
                        : "Disponible"}
                  </p>
                  <button
                    onClick={() => addToCart(product)}
                    disabled={soldOut}
                    className={`mt-4 w-full rounded-full py-3 font-bold transition disabled:cursor-not-allowed disabled:opacity-50 ${
                      featured
                        ? "bg-brand-gradient text-white shadow-md shadow-brand-purple/25 hover:opacity-90"
                        : "border-2 border-brand-purple/30 bg-white text-brand-purple hover:border-brand-purple hover:bg-brand-purple hover:text-white"
                    }`}
                  >
                    {soldOut ? "Agotado" : "Agregar al carrito"}
                  </button>
                </div>
              </motion.div>
            );
          })}
        </div>
      )}

      {/* Cart Drawer */}
      <AnimatePresence>
        {isCartOpen && (
          <>
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={() => setIsCartOpen(false)}
              className="fixed inset-0 bg-brand-ink/40 backdrop-blur-sm z-50"
            />
            <motion.div
              initial={{ x: "100%" }}
              animate={{ x: 0 }}
              exit={{ x: "100%" }}
              transition={{ type: "spring", damping: 25, stiffness: 200 }}
              className="fixed top-0 right-0 h-full w-full max-w-md bg-white border-l border-slate-200 shadow-2xl z-50 text-brand-ink flex flex-col"
            >
              <div className="p-6 border-b border-slate-200 flex items-center justify-between">
                <h2 className="font-serif text-2xl font-bold flex items-center gap-2">
                  <ShoppingCart className="text-brand-purple" /> Tu carrito
                </h2>
                <button
                  onClick={() => setIsCartOpen(false)}
                  className="text-brand-muted hover:text-brand-ink"
                >
                  Cerrar
                </button>
              </div>

              <div className="flex-1 overflow-y-auto p-6 space-y-6">
                {cart.length === 0 ? (
                  <div className="text-center text-brand-muted mt-20">
                    <ShoppingCart className="w-16 h-16 mx-auto mb-4 opacity-20" />
                    <p>Tu carrito está vacío.</p>
                  </div>
                ) : (
                  cart.map((item) => {
                    const itemImg = normalizeMediaUrl(item.image);
                    return (
                      <div
                        key={item.id}
                        className="flex gap-4 items-center bg-brand-soft p-4 rounded-xl border border-slate-200"
                      >
                        {itemImg && (
                          <img src={itemImg} alt={item.name} className="w-16 h-16 object-contain" />
                        )}
                        <div className="flex-1">
                          <div className="flex items-center gap-2 mb-1">
                            <h4 className="font-bold text-sm line-clamp-1">{item.name}</h4>
                            {item.type === "PHYSICAL" ? (
                              <span className="shrink-0 inline-flex items-center gap-0.5 text-[10px] uppercase font-bold text-brand-green bg-brand-green/10 px-1.5 py-0.5 rounded border border-brand-green/30">
                                <Package className="w-3 h-3" /> Merch
                              </span>
                            ) : (
                              <span className="shrink-0 inline-flex items-center gap-0.5 text-[10px] uppercase font-bold text-brand-purple bg-brand-purple/10 px-1.5 py-0.5 rounded border border-brand-purple/30">
                                <Ticket className="w-3 h-3" /> Boletos
                              </span>
                            )}
                          </div>
                          <p className="text-brand-purple font-semibold">
                            {item.originalPrice && item.originalPrice > item.price && (
                              <span className="mr-2 text-xs text-slate-400 line-through">
                                ${item.originalPrice.toLocaleString("es-CL")}
                              </span>
                            )}
                            ${item.price.toLocaleString("es-CL")}
                          </p>
                          <div className="flex items-center gap-3 mt-2">
                            <button
                              onClick={() => updateQuantity(item.id, -1)}
                              className="p-1 bg-white border border-slate-200 rounded-md hover:bg-slate-100"
                            >
                              <Minus className="w-4 h-4" />
                            </button>
                            <span className="font-mono">{item.quantity}</span>
                            <button
                              onClick={() => updateQuantity(item.id, 1)}
                              disabled={
                                (item.type === "PHYSICAL" || item.isLimited) &&
                                item.quantity >= item.stock
                              }
                              className="p-1 bg-white border border-slate-200 rounded-md hover:bg-slate-100 disabled:opacity-40 disabled:cursor-not-allowed"
                            >
                              <Plus className="w-4 h-4" />
                            </button>
                          </div>
                          {(item.type === "PHYSICAL" || item.isLimited) && (
                            <p className="text-[10px] text-brand-muted mt-1.5">
                              Stock disponible: {item.stock}
                            </p>
                          )}
                        </div>
                        <button
                          onClick={() => removeFromCart(item.id)}
                          className="text-red-500 hover:text-red-600 p-2"
                        >
                          <Trash2 className="w-5 h-5" />
                        </button>
                      </div>
                    );
                  })
                )}
              </div>

              {cart.length > 0 && (
                <div className="p-6 border-t border-slate-200 bg-brand-soft">
                  <div className="flex justify-between items-center mb-6">
                    <span className="text-brand-muted">Total a pagar</span>
                    <span className="font-serif text-3xl font-bold text-brand-purple">
                      ${total.toLocaleString("es-CL")}
                    </span>
                  </div>

                  <div className="mb-4">
                    <label className="block text-xs text-brand-muted mb-2">
                      Correo electrónico <span className="text-brand-pink">*</span>
                    </label>
                    <input
                      type="email"
                      required
                      placeholder="tu@correo.com"
                      value={guestEmail}
                      onChange={(e) => setGuestEmail(e.target.value)}
                      className="w-full bg-white border border-slate-300 rounded-xl px-4 py-3 text-brand-ink focus:outline-none focus:border-brand-purple transition-colors"
                    />
                  </div>

                  <div className="mb-4">
                    <label className="block text-xs text-brand-muted mb-2">
                      Nombre completo <span className="text-brand-pink">*</span>
                    </label>
                    <input
                      type="text"
                      required
                      placeholder="Ej: María González"
                      value={buyerName}
                      onChange={handleNameChange}
                      maxLength={80}
                      minLength={2}
                      className="w-full bg-white border border-slate-300 rounded-xl px-4 py-3 text-brand-ink focus:outline-none focus:border-brand-purple transition-colors placeholder:text-slate-400"
                    />
                  </div>

                  <div className="mb-4">
                    <label className="block text-xs text-brand-muted mb-2">
                      Teléfono (9 dígitos) <span className="text-brand-pink">*</span>
                    </label>
                    <input
                      type="tel"
                      required
                      inputMode="numeric"
                      placeholder="912345678"
                      value={buyerPhone}
                      onChange={handlePhoneChange}
                      maxLength={PHONE_LENGTH}
                      className="w-full bg-white border border-slate-300 rounded-xl px-4 py-3 text-brand-ink focus:outline-none focus:border-brand-purple transition-colors placeholder:text-slate-400 font-mono"
                    />
                    {buyerPhone.length > 0 && buyerPhone.length !== PHONE_LENGTH && (
                      <p className="text-amber-600 text-xs mt-1">{buyerPhone.length}/9 dígitos</p>
                    )}
                  </div>

                  {hasPhysicalItems && (
                    <div className="mb-4 p-4 rounded-xl border border-brand-green/30 bg-white space-y-3">
                      <p className="text-sm font-bold text-brand-green flex items-center gap-2">
                        <Package className="w-4 h-4" />
                        Datos de envío (merchandising)
                      </p>
                      <p className="text-xs text-brand-muted">
                        Envío a todo Chile. Te contactaremos si hay dudas con la dirección.
                      </p>
                      <div>
                        <label className="block text-xs text-brand-muted mb-2">
                          Dirección (calle y número) <span className="text-brand-pink">*</span>
                        </label>
                        <input
                          type="text"
                          required
                          placeholder="Ej: Av. Providencia 1234"
                          value={shipping.address}
                          onChange={(e) => setShippingAddress(e.target.value)}
                          maxLength={120}
                          className="w-full bg-white border border-slate-300 rounded-xl px-4 py-3 text-brand-ink focus:outline-none focus:border-brand-purple transition-colors placeholder:text-slate-400"
                        />
                      </div>
                      <div className="grid grid-cols-2 gap-3">
                        <div>
                          <label className="block text-xs text-brand-muted mb-2">
                            Comuna <span className="text-brand-pink">*</span>
                          </label>
                          <input
                            type="text"
                            required
                            placeholder="Ej: Providencia"
                            value={shipping.comuna}
                            onChange={(e) => setShippingComuna(e.target.value)}
                            maxLength={60}
                            className="w-full bg-white border border-slate-300 rounded-xl px-4 py-3 text-brand-ink focus:outline-none focus:border-brand-purple transition-colors placeholder:text-slate-400"
                          />
                        </div>
                        <div>
                          <label className="block text-xs text-brand-muted mb-2">
                            Región <span className="text-brand-pink">*</span>
                          </label>
                          <select
                            required
                            value={shipping.region}
                            onChange={(e) => setShippingRegion(e.target.value)}
                            className="w-full bg-white border border-slate-300 rounded-xl px-4 py-3 text-brand-ink focus:outline-none focus:border-brand-purple transition-colors"
                          >
                            <option value="">Seleccionar…</option>
                            {CHILE_REGIONS.map((region) => (
                              <option key={region} value={region} className="bg-white">
                                {region}
                              </option>
                            ))}
                          </select>
                        </div>
                      </div>
                      <div>
                        <label className="block text-xs text-brand-muted mb-2">
                          Depto / referencias (opcional)
                        </label>
                        <input
                          type="text"
                          placeholder="Ej: Depto 502, portón verde"
                          value={shipping.notes}
                          onChange={(e) => setShippingNotes(e.target.value)}
                          maxLength={120}
                          className="w-full bg-white border border-slate-300 rounded-xl px-4 py-3 text-brand-ink focus:outline-none focus:border-brand-purple transition-colors placeholder:text-slate-400"
                        />
                      </div>
                    </div>
                  )}

                  <div className="space-y-2">
                    <p className="text-xs text-brand-muted uppercase tracking-wide">Medio de pago</p>
                    {!hasAnyPayment ? (
                      <p className="text-sm text-amber-700 bg-amber-50 border border-amber-200 rounded-xl px-4 py-3">
                        El pago online no está disponible por ahora. Usa «Compra por transferencia»
                        debajo de los packs.
                      </p>
                    ) : (
                      <div className="grid grid-cols-1 gap-2">
                        {mpEnabled && (
                          <button
                            type="button"
                            onClick={() => setPaymentMethod("mercadopago")}
                            className={`w-full text-left px-4 py-3 rounded-xl border transition-all ${
                              paymentMethod === "mercadopago"
                                ? "border-[#009ee3] bg-[#009ee3]/10 text-brand-ink"
                                : "border-slate-200 bg-white text-brand-ink hover:border-slate-400"
                            }`}
                          >
                            <span className="font-semibold block">Mercado Pago</span>
                            <span className="text-xs text-brand-muted">Tarjetas y saldo MP</span>
                          </button>
                        )}
                        {paykuEnabled && (
                          <button
                            type="button"
                            onClick={() => setPaymentMethod("payku")}
                            className={`w-full text-left px-4 py-3 rounded-xl border transition-all ${
                              paymentMethod === "payku"
                                ? "border-[#10b981] bg-[#10b981]/10 text-brand-ink"
                                : "border-slate-200 bg-white text-brand-ink hover:border-slate-400"
                            }`}
                          >
                            <span className="font-semibold block">Payku</span>
                            <span className="text-xs text-brand-muted">Webpay, transferencia y más</span>
                          </button>
                        )}
                      </div>
                    )}
                  </div>

                  <button
                    onClick={handleCheckout}
                    disabled={
                      isCheckoutLoading ||
                      !hasAnyPayment ||
                      !guestEmail?.trim() ||
                      buyerName.trim().length < 2 ||
                      buyerPhone.length !== PHONE_LENGTH ||
                      (hasPhysicalItems &&
                        (shipping.address.trim().length < 5 ||
                          !shipping.comuna.trim() ||
                          !shipping.region.trim()))
                    }
                    className={`w-full h-14 rounded-xl text-white font-bold text-lg transition-all flex items-center justify-center gap-2 disabled:opacity-50 ${
                      paymentMethod === "payku"
                        ? "bg-[#10b981] hover:bg-[#059669] hover:shadow-[0_0_20px_rgba(16,185,129,0.45)]"
                        : "bg-[#009ee3] hover:bg-[#0088cc] hover:shadow-[0_0_20px_rgba(0,158,227,0.5)]"
                    }`}
                  >
                    {isCheckoutLoading ? (
                      <Loader2 className="animate-spin w-6 h-6" />
                    ) : !hasAnyPayment ? (
                      "Pago online no disponible"
                    ) : (
                      <>
                        {paymentMethod === "payku" ? "Pagar con Payku" : "Pagar con Mercado Pago"}
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                          <path
                            d="M5 12h14M12 5l7 7-7 7"
                            stroke="white"
                            strokeWidth="2"
                            strokeLinecap="round"
                            strokeLinejoin="round"
                          />
                        </svg>
                      </>
                    )}
                  </button>
                </div>
              )}
            </motion.div>
          </>
        )}
      </AnimatePresence>
    </div>
  );
}
