"use client"

import { useCallback, useEffect, useRef, useState } from "react"
import Link from "next/link"
import Image from "next/image"
import { useSede } from "@/lib/sede-context"
import { getLandingContent } from "@/lib/landing-content"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { ProductModal } from "@/components/product-modal"
import { DualCurrencyDisplay } from "@/components/dual-currency-display"
import { useCartStore } from "@/lib/cart-store"
import { toast } from "@/hooks/use-toast"
import { ToastAction } from "@/components/ui/toast"
import { useCarruselAutomatico } from "@/hooks/use-carrusel-automatico"
import { fetchPromosDestacadas } from "@/lib/promotions-client"
import {
  ChevronLeft,
  ChevronRight,
  Flame,
  Plus,
  SlidersHorizontal,
  Tag,
} from "lucide-react"
import type { ModifierGroupWithOptions } from "@/lib/modifier-types"

interface Campaign {
  id: string
  title: string
  description: string
  price: string | null
  badge: string | null
  image: string | null
  linkUrl: string | null
  ctaLabel: string | null
}

interface PromoProduct {
  id: string
  name: string
  description: string
  image: string
  price: string
  specialPrice: string | null
  isDailySpecial: boolean
  isWeeklySpecial: boolean
  modifierGroups?: ModifierGroupWithOptions[]
  categorySlug: string
  categoryName: string
  effectivePrice: number
  hasDiscount: boolean
  discountPercent: number
}

interface Props {
  /**
   * `dark` para la portada (fondo verde de la landing), `light` para el menú y
   * la pantalla de pedido, que van sobre blanco.
   */
  variant?: "dark" | "light"
  /** Cuántos productos mostrar en la tira. El resto se ve en el menú. */
  maxProducts?: number
  /** Oculta las tarjetas de campaña y deja solo la tira de productos. */
  soloProductos?: boolean
}

/**
 * Envoltura para las páginas públicas: la sede sale del contexto de la URL.
 */
export function PromocionesDestacadas(props: Props) {
  const { sede, sedeSlug } = useSede()
  if (!sedeSlug) return null
  return (
    <Vitrina
      {...props}
      sedeSlug={sedeSlug}
      locationId={sede?.id ?? null}
      menuHref={`/${sedeSlug}/menu`}
      campanaHref={(c) => c.linkUrl || `/${sedeSlug}/menu`}
    />
  )
}

/**
 * Envoltura para el room service (`/menu-hotel`), que vive fuera del
 * `SedeProvider` y se sirve siempre del Sport Bar. Las campañas enlazan al
 * propio menú del hotel (`/menu-hotel?categoria=...`) — mandar al huésped al
 * menú público lo saca del flujo de room service y de su carrito.
 */
export function PromocionesDestacadasHotel(props: Props) {
  return (
    <Vitrina
      {...props}
      sedeSlug="sport-bar"
      locationId={1}
      menuHref="/menu-hotel"
      campanaHref={(c) => {
        if (typeof c.linkUrl === "string") {
          try {
            const cat = new URL(c.linkUrl, "https://vipplaysportbar.com").searchParams.get("categoria")
            if (cat) return `/menu-hotel?categoria=${encodeURIComponent(cat)}`
          } catch {
            // linkUrl ilegible: se cae al menú completo del hotel
          }
        }
        return "/menu-hotel"
      }}
    />
  )
}

interface VitrinaProps extends Props {
  sedeSlug: string
  /** ID numérico de la sede para el carrito; null deshabilita el «Pedir». */
  locationId: number | null
  /** Adónde lleva «Ver el menú completo». */
  menuHref: string
  /** Adónde lleva cada tarjeta de campaña. */
  campanaHref: (c: Campaign) => string
}

function Vitrina({
  variant = "light",
  maxProducts = 12,
  soloProductos = false,
  sedeSlug,
  locationId,
  menuHref,
  campanaHref,
}: VitrinaProps) {
  const [campaigns, setCampaigns] = useState<Campaign[]>([])
  const [products, setProducts] = useState<PromoProduct[]>([])
  const [isLoading, setIsLoading] = useState(true)
  const [modalProduct, setModalProduct] = useState<PromoProduct | null>(null)

  const bannerRef = useRef<HTMLDivElement>(null)
  const stripRef = useRef<HTMLDivElement>(null)

  const addItem = useCartStore((s) => s.addItem)
  const clearCart = useCartStore((s) => s.clearCart)
  const canAddFromLocation = useCartStore((s) => s.canAddFromLocation)

  useEffect(() => {
    if (!sedeSlug) return
    let cancelado = false

    const cargar = async () => {
      setIsLoading(true)
      try {
        // Fetch compartido con cache corto: la vitrina se monta en portada,
        // menú y carrito, y el menú filtrado pide las mismas campañas.
        const data = await fetchPromosDestacadas(sedeSlug)
        if (cancelado) return
        setCampaigns(data.campaigns ?? [])
        setProducts(data.products ?? [])
      } catch (error) {
        console.error("Error cargando promociones destacadas:", error)
      } finally {
        if (!cancelado) setIsLoading(false)
      }
    }

    cargar()
    return () => {
      cancelado = true
    }
  }, [sedeSlug])

  // Los banners rotan al ritmo del carrusel de la portada (5 s). La tira de
  // productos va más lenta: son tarjetas que se leen, no titulares.
  const carruselBanner = useCarruselAutomatico(bannerRef, {
    intervalo: 5000,
    activo: !isLoading,
  })
  const carruselProductos = useCarruselAutomatico(stripRef, {
    intervalo: 7000,
    activo: !isLoading,
  })

  const desplazar = useCallback(
    (
      ref: React.RefObject<HTMLDivElement | null>,
      direccion: 1 | -1,
      pausar: () => void
    ) => {
      const nodo = ref.current
      if (!nodo) return
      pausar() // quien navega a mano manda: la rotación espera
      nodo.scrollBy({ left: direccion * nodo.clientWidth * 0.8, behavior: "smooth" })
    },
    []
  )

  /** Un producto con modificadores obligatorios no se puede pedir a ciegas. */
  const necesitaModal = (p: PromoProduct) =>
    Array.isArray(p.modifierGroups) && p.modifierGroups.length > 0

  const paraModal = (p: PromoProduct) => ({
    id: p.id,
    name: p.name,
    description: p.description,
    price: p.price,
    image: p.image,
    specialPrice: p.specialPrice,
    isDailySpecial: p.isDailySpecial,
    isWeeklySpecial: p.isWeeklySpecial,
    modifierGroups: p.modifierGroups,
  })

  const pedir = (p: PromoProduct) => {
    if (locationId == null) return

    if (necesitaModal(p)) {
      setModalProduct(p)
      return
    }

    const item = {
      id: p.id,
      name: p.name,
      description: p.description,
      price: p.price,
      image: p.image,
      specialPrice: p.specialPrice,
      isDailySpecial: p.isDailySpecial,
      isWeeklySpecial: p.isWeeklySpecial,
    }

    if (!canAddFromLocation(locationId)) {
      toast({
        title: "Carrito de otra sede",
        description:
          "Tu carrito tiene productos de otra sede. ¿Deseas vaciarlo y añadir este producto?",
        variant: "destructive",
        // El toast renderiza `action` tal cual: tiene que ser un elemento, no un
        // objeto {label, onClick} — pasarle un objeto plano rompe el render.
        action: (
          <ToastAction
            altText="Vaciar el carrito y añadir este producto"
            onClick={() => {
              clearCart()
              addItem(item, locationId)
              toast({ title: "Añadido al carrito", description: p.name })
            }}
          >
            Vaciar y añadir
          </ToastAction>
        ),
      })
      return
    }

    if (addItem(item, locationId)) {
      toast({ title: "Añadido al carrito", description: p.name })
    }
  }

  if (isLoading) return <VitrinaSkeleton variant={variant} />

  // Sin campañas cargadas en el panel, la portada cae al contenido estático de
  // siempre (Happy Hour, noche de UFC) para no quedarse sin sección.
  const estaticas: Campaign[] =
    campaigns.length > 0
      ? campaigns
      : (getLandingContent(sedeSlug)?.offers ?? []).map((o, i) => ({
          id: `estatica-${i}`,
          title: o.title,
          description: o.description,
          price: o.price ?? null,
          badge: o.badge ?? null,
          image: null,
          linkUrl: null,
          ctaLabel: null,
        }))

  if (estaticas.length === 0 && products.length === 0) return null

  const oscuro = variant === "dark"
  const visibles = products.slice(0, maxProducts)
  const mostrarCampanas = !soloProductos && estaticas.length > 0

  return (
    <section
      className={
        oscuro
          ? "py-14 bg-gradient-to-br from-verde-bosque to-verde-bosque/95"
          : "py-10 bg-transparent"
      }
      aria-labelledby="promos-titulo"
    >
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <header className="flex items-end justify-between gap-4 mb-6">
          <div>
            <span className="inline-flex items-center gap-2 text-naranja-vip font-semibold text-sm uppercase tracking-wide">
              <Flame className="h-4 w-4" />
              Promociones
            </span>
            <h2
              id="promos-titulo"
              className={`font-heading text-3xl sm:text-4xl mt-1 ${
                oscuro ? "text-white" : "text-verde-bosque"
              }`}
            >
              Aprovecha ahora
            </h2>
          </div>
          <Link
            href={menuHref}
            className={`hidden sm:inline text-sm font-medium underline-offset-4 hover:underline ${
              oscuro ? "text-crema/80 hover:text-white" : "text-verde-bosque/70 hover:text-verde-bosque"
            }`}
          >
            Ver el menú completo
          </Link>
        </header>

        {/* ── Tarjetas de campaña ─────────────────────────────────────────── */}
        {mostrarCampanas && (
          <div className="relative mb-10">
            {estaticas.length > 1 && (
              <FlechasCarrusel
                onPrev={() => desplazar(bannerRef, -1, carruselBanner.pausarUnRato)}
                onNext={() => desplazar(bannerRef, 1, carruselBanner.pausarUnRato)}
                etiqueta="campañas"
              />
            )}
            <div
              ref={bannerRef}
              className="flex gap-4 overflow-x-auto scrollbar-hide snap-x snap-mandatory scroll-smooth pb-2"
            >
              {estaticas.map((c) => (
                <TarjetaCampana key={c.id} campana={c} destino={campanaHref(c)} />
              ))}
            </div>

            {estaticas.length > 1 && (
              <Puntos
                cantidad={estaticas.length}
                activo={carruselBanner.indice}
                oscuro={oscuro}
                onIr={(i) => {
                  carruselBanner.pausarUnRato()
                  carruselBanner.irA(i)
                }}
              />
            )}
          </div>
        )}

        {/* ── Tira de productos en oferta ─────────────────────────────────── */}
        {visibles.length > 0 && (
          <div className="relative">
            {visibles.length > 2 && (
              <FlechasCarrusel
                onPrev={() => desplazar(stripRef, -1, carruselProductos.pausarUnRato)}
                onNext={() => desplazar(stripRef, 1, carruselProductos.pausarUnRato)}
                etiqueta="productos en promoción"
              />
            )}
            <div
              ref={stripRef}
              className="flex gap-4 overflow-x-auto scrollbar-hide snap-x scroll-smooth pb-2"
            >
              {visibles.map((p) => (
                <TarjetaProducto
                  key={p.id}
                  producto={p}
                  oscuro={oscuro}
                  conModificadores={necesitaModal(p)}
                  onPedir={() => pedir(p)}
                />
              ))}
            </div>
          </div>
        )}

        <div className="mt-6 sm:hidden">
          <Link href={menuHref}>
            <Button
              variant="outline"
              className={`w-full ${oscuro ? "text-white border-white/40 hover:bg-white/10" : ""}`}
            >
              Ver el menú completo
            </Button>
          </Link>
        </div>
      </div>

      {locationId != null && (
        <ProductModal
          product={modalProduct ? paraModal(modalProduct) : null}
          locationId={locationId}
          open={modalProduct !== null}
          onClose={() => setModalProduct(null)}
        />
      )}
    </section>
  )
}

/* ────────────────────────────── piezas ────────────────────────────── */

function TarjetaCampana({ campana, destino }: { campana: Campaign; destino: string }) {
  return (
    <Link
      href={destino}
      className="group relative snap-start shrink-0 w-[86%] sm:w-[70%] lg:w-[48%] rounded-2xl overflow-hidden shadow-lg focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-naranja-vip"
    >
      <div className="relative aspect-[16/9] sm:aspect-[21/9] bg-verde-bosque">
        {campana.image ? (
          <>
            <Image
              src={campana.image}
              alt=""
              fill
              sizes="(max-width: 640px) 86vw, (max-width: 1024px) 70vw, 48vw"
              className="object-cover transition-transform duration-500 group-hover:scale-105"
              unoptimized
            />
            <div className="absolute inset-0 bg-gradient-to-r from-black/85 via-black/60 to-black/10" />
          </>
        ) : (
          // Campaña sin foto (contenido estático): se sostiene con el color de marca.
          <div className="absolute inset-0 bg-gradient-to-br from-verde-bosque via-verde-bosque to-naranja-vip/60" />
        )}

        <div className="absolute inset-0 p-5 sm:p-6 flex flex-col justify-center max-w-[78%]">
          {campana.badge && (
            <Badge className="self-start mb-2 bg-naranja-vip text-white border-0 font-semibold">
              {campana.badge}
            </Badge>
          )}
          <h3 className="font-heading text-xl sm:text-2xl lg:text-3xl text-white leading-tight">
            {campana.title}
          </h3>
          <p className="text-crema/85 text-xs sm:text-sm mt-1.5 line-clamp-2">
            {campana.description}
          </p>
          <div className="flex items-center gap-3 mt-3">
            {campana.price && (
              <span className="text-2xl sm:text-3xl font-bold text-verde-neon drop-shadow">
                {campana.price}
              </span>
            )}
            <span className="inline-flex items-center gap-1 text-xs sm:text-sm font-semibold text-white bg-white/15 backdrop-blur px-3 py-1.5 rounded-full group-hover:bg-naranja-vip transition-colors">
              {campana.ctaLabel || "Ver más"}
              <ChevronRight className="h-3.5 w-3.5" />
            </span>
          </div>
        </div>
      </div>
    </Link>
  )
}

function TarjetaProducto({
  producto,
  oscuro,
  conModificadores,
  onPedir,
}: {
  producto: PromoProduct
  oscuro: boolean
  conModificadores: boolean
  onPedir: () => void
}) {
  return (
    <article
      className={`snap-start shrink-0 w-[62%] sm:w-[40%] md:w-[30%] lg:w-[23%] rounded-xl overflow-hidden shadow-md flex flex-col ${
        oscuro ? "bg-white/10 backdrop-blur-sm border border-white/20" : "bg-card"
      }`}
    >
      <div className="relative aspect-[4/3] bg-muted overflow-hidden">
        {producto.image && (
          <Image
            src={producto.image}
            alt={producto.name}
            fill
            sizes="(max-width: 640px) 62vw, (max-width: 768px) 40vw, 23vw"
            className="object-cover"
            unoptimized
          />
        )}
        {producto.hasDiscount && (
          <span className="absolute top-2 left-2 bg-naranja-vip text-white text-xs font-bold px-2 py-1 rounded-full shadow">
            −{producto.discountPercent}%
          </span>
        )}
        {!producto.hasDiscount && (
          <span className="absolute top-2 left-2 inline-flex items-center gap-1 bg-verde-neon text-verde-bosque text-[11px] font-bold px-2 py-1 rounded-full shadow">
            <Tag className="h-3 w-3" />
            Promoción
          </span>
        )}
      </div>

      <div className="p-3 flex flex-col gap-2 flex-1">
        <h3
          className={`font-semibold text-sm leading-snug line-clamp-2 ${
            oscuro ? "text-white" : "text-foreground"
          }`}
        >
          {producto.name}
        </h3>

        <div className="mt-auto">
          <div className="flex items-baseline gap-2">
            <span className={`text-lg font-bold ${oscuro ? "text-verde-neon" : "text-verde-bosque"}`}>
              ${producto.effectivePrice.toFixed(2)}
            </span>
            {producto.hasDiscount && (
              <span
                className={`text-xs line-through ${
                  oscuro ? "text-crema/60" : "text-muted-foreground"
                }`}
              >
                ${Number(producto.price).toFixed(2)}
              </span>
            )}
          </div>
          {/* El precio en dólares ya está arriba; acá solo el equivalente en bolívares. */}
          <DualCurrencyDisplay
            amountUSD={producto.effectivePrice}
            size="xs"
            primaryCurrency="VES"
            showBothAlways={false}
            className="mt-0.5"
          />

          <Button
            size="sm"
            onClick={onPedir}
            className="w-full mt-2 bg-naranja-vip hover:bg-naranja-vip/90 text-white"
          >
            {conModificadores ? (
              <>
                <SlidersHorizontal className="h-4 w-4 mr-1" />
                Elegir
              </>
            ) : (
              <>
                <Plus className="h-4 w-4 mr-1" />
                Pedir
              </>
            )}
          </Button>
        </div>
      </div>
    </article>
  )
}

function Puntos({
  cantidad,
  activo,
  oscuro,
  onIr,
}: {
  cantidad: number
  activo: number
  oscuro: boolean
  onIr: (i: number) => void
}) {
  return (
    <div className="flex justify-center gap-2 mt-3">
      {Array.from({ length: cantidad }).map((_, i) => (
        <button
          key={i}
          type="button"
          onClick={() => onIr(i)}
          aria-label={`Ir a la promoción ${i + 1} de ${cantidad}`}
          aria-current={i === activo}
          className={`h-2 rounded-full transition-all ${
            i === activo
              ? "w-6 bg-naranja-vip"
              : oscuro
                ? "w-2 bg-white/40 hover:bg-white/70"
                : "w-2 bg-verde-bosque/25 hover:bg-verde-bosque/50"
          }`}
        />
      ))}
    </div>
  )
}

function FlechasCarrusel({
  onPrev,
  onNext,
  etiqueta,
}: {
  onPrev: () => void
  onNext: () => void
  etiqueta: string
}) {
  const base =
    "hidden lg:flex absolute top-1/2 -translate-y-1/2 z-10 h-10 w-10 items-center justify-center rounded-full bg-white/90 text-verde-bosque shadow-lg hover:bg-white transition-colors"
  return (
    <>
      <button type="button" onClick={onPrev} className={`${base} -left-4`} aria-label={`Anterior: ${etiqueta}`}>
        <ChevronLeft className="h-5 w-5" />
      </button>
      <button type="button" onClick={onNext} className={`${base} -right-4`} aria-label={`Siguiente: ${etiqueta}`}>
        <ChevronRight className="h-5 w-5" />
      </button>
    </>
  )
}

function VitrinaSkeleton({ variant }: { variant: "dark" | "light" }) {
  const oscuro = variant === "dark"
  return (
    <section className={oscuro ? "py-14 bg-verde-bosque" : "py-10"}>
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className={`h-8 w-52 rounded mb-6 ${oscuro ? "bg-white/15" : "bg-muted"}`} />
        <div className="flex gap-4 overflow-hidden">
          {[0, 1].map((i) => (
            <div
              key={i}
              className={`shrink-0 w-[86%] lg:w-[48%] aspect-[16/9] sm:aspect-[21/9] rounded-2xl ${
                oscuro ? "bg-white/10" : "bg-muted"
              } animate-pulse`}
            />
          ))}
        </div>
      </div>
    </section>
  )
}
