"use client"

import { useState, useRef, useCallback, useEffect } from "react"
import { ChevronLeft, ChevronRight } from "lucide-react"
import type { HospitalityImpactData } from "@/lib/strapi/types"
import FallbackImage from "./FallbackImage"

export default function HospitalityImpact({ data }: { data: HospitalityImpactData }) {
  const scrollRef = useRef<HTMLDivElement>(null)
  const mobileScrollRef = useRef<HTMLDivElement>(null)
  const [activePage, setActivePage] = useState(0)
  const [mobilePage, setMobilePage] = useState(0)
  const totalCards = data.stats.length
  const totalPages = Math.max(1, totalCards - 2)

  const scroll = useCallback(
    (direction: "left" | "right") => {
      if (!scrollRef.current) return
      const cardWidth = scrollRef.current.querySelector<HTMLElement>("[data-stat-card]")?.offsetWidth || 416
      const gap = 24
      scrollRef.current.scrollBy({
        left: direction === "right" ? cardWidth + gap : -(cardWidth + gap),
        behavior: "smooth",
      })
      setActivePage((prev) =>
        direction === "right" ? Math.min(prev + 1, totalPages - 1) : Math.max(prev - 1, 0),
      )
    },
    [totalPages],
  )

  const scrollMobile = useCallback((direction: "left" | "right") => {
    if (!mobileScrollRef.current) return
    const card = mobileScrollRef.current.querySelector<HTMLElement>("[data-stat-card-mobile]")
    const cardWidth = card?.offsetWidth || 280
    mobileScrollRef.current.scrollBy({
      left: direction === "right" ? cardWidth + 16 : -(cardWidth + 16),
      behavior: "smooth",
    })
  }, [])

  const handleMobileScroll = useCallback(() => {
    if (!mobileScrollRef.current) return
    const { scrollLeft } = mobileScrollRef.current
    const card = mobileScrollRef.current.querySelector<HTMLElement>("[data-stat-card-mobile]")
    const cardWidth = card?.offsetWidth || 280
    const page = Math.round(scrollLeft / (cardWidth + 16))
    setMobilePage(Math.min(page, totalCards - 1))
  }, [totalCards])

  useEffect(() => {
    const el = mobileScrollRef.current
    if (!el) return
    el.addEventListener("scroll", handleMobileScroll, { passive: true })
    return () => el.removeEventListener("scroll", handleMobileScroll)
  }, [handleMobileScroll])

  if (totalCards === 0) return null

  return (
    <section className="w-full pt-[40px] md:pt-[80px] pb-[40px] md:pb-[80px] overflow-hidden">
      <div className="max-w-[1297px] mx-auto px-5 md:px-0 mb-6 md:mb-[56px]">
        <div className="flex flex-col md:flex-row md:items-start md:justify-between gap-5 md:gap-6">
          <div className="inline-flex items-center gap-2 px-6 py-3 bg-[#ebebeb] rounded-[66px] self-start">
            <FallbackImage src={data.badgeIcon} alt="" loading="lazy" className="w-[17px] h-4" />
            <span className="font-heading text-black text-[16px] leading-none uppercase whitespace-nowrap">
              {data.badge}
            </span>
          </div>

          <div className="w-full md:w-[417px]">
            <p className="text-[#102443]/60 text-[16px] leading-[1.5] font-medium">
              {data.description}
            </p>
            <div className="mt-4 md:mt-6 border-b border-[rgba(16,36,67,0.2)]" />
          </div>
        </div>
      </div>

      <div className="flex flex-col gap-6">
        <div
          ref={scrollRef}
          className="hidden md:flex gap-6 overflow-x-auto scrollbar-hide md:pl-[max(20px,calc((100vw-1297px)/2))] pr-0"
        >
          {data.stats.map((stat, index) => (
            <div
              key={index}
              data-stat-card
              className="flex-shrink-0 w-[416px] h-[299px] rounded-[16px] overflow-hidden border border-[rgba(229,231,235,0.5)] relative flex flex-col justify-end"
              style={{
                background:
                  "radial-gradient(ellipse at 42% 84%, rgba(255,232,233,0) 0%, rgba(255,232,233,1) 100%), linear-gradient(90deg, #fff 0%, #fff 100%)",
              }}
            >
              <FallbackImage
                src={stat.vector}
                fallbackSrc="/assets/hospitality/stats-vector-3.svg"
                alt=""
                loading="lazy"
                className="absolute top-[-1px] right-0 w-[103px] h-[101px] object-contain object-right-top pointer-events-none"
                aria-hidden="true"
              />

              <div className="relative z-10 px-6 pb-6 pt-6 flex flex-col gap-2">
                <span className="font-accent text-[#2a3036] text-[96px] leading-none">
                  {stat.number}
                </span>
                <span className="font-accent text-[#2a3036] text-[32px] leading-normal">
                  {stat.label}
                </span>
                <p className="text-[#2a3036]/80 text-[16px] leading-[18px]">
                  {stat.description}
                </p>
              </div>
            </div>
          ))}
        </div>

        <div className="md:hidden px-5 -mr-5">
          <div
            ref={mobileScrollRef}
            className="flex gap-4 overflow-x-auto scrollbar-hide snap-x snap-mandatory scroll-smooth"
          >
            {data.stats.map((stat, index) => (
              <div
                key={index}
                data-stat-card-mobile
                className="flex-shrink-0 w-[80vw] h-[224px] rounded-[16px] overflow-hidden relative flex flex-col justify-end snap-start"
                style={{
                  background:
                    "radial-gradient(ellipse at 42% 84%, rgba(255,232,233,0) 0%, rgba(255,232,233,1) 100%)",
                }}
              >
                <FallbackImage
                  src={stat.vector}
                  fallbackSrc="/assets/hospitality/stats-vector-3.svg"
                  alt=""
                  loading="lazy"
                  className="absolute top-0 right-0 w-[103px] h-[101px] object-contain object-right-top pointer-events-none"
                  aria-hidden="true"
                />
                <div className="relative z-10 px-4 pb-4 pt-4 flex flex-col gap-2">
                  <div className="flex flex-col">
                    <span className="font-accent text-[#2a3036] text-[64px] leading-none">
                      {stat.number}
                    </span>
                    <span className="font-accent text-[#2a3036] text-[28px] leading-normal">
                      {stat.label}
                    </span>
                  </div>
                  <p className="text-[#4a5565] text-[14px] leading-[18px]">
                    {stat.description}
                  </p>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="flex items-center justify-end max-w-[1297px] mx-auto w-full px-5 md:px-0">
          <div className="flex gap-[13px] md:gap-2">
            <button
              onClick={() => {
                scroll("left")
                scrollMobile("left")
              }}
              disabled={activePage === 0 && mobilePage === 0}
              className={`w-[44px] h-[44px] md:w-[60px] md:h-[58px] rounded-[66px] border-2 border-[#d20010] flex items-center justify-center transition-opacity ${activePage === 0 ? "opacity-30 cursor-not-allowed md:opacity-30" : "opacity-50 hover:opacity-100"
                }`}
              aria-label="Previous"
            >
              <ChevronLeft size={24} className="text-[#d20010]" />
            </button>
            <button
              onClick={() => {
                scroll("right")
                scrollMobile("right")
              }}
              disabled={activePage >= totalPages - 1 && mobilePage >= totalCards - 1}
              className={`w-[44px] h-[44px] md:w-[60px] md:h-[58px] rounded-[66px] border-2 border-[#d20010] flex items-center justify-center transition-opacity ${activePage >= totalPages - 1 ? "opacity-30 cursor-not-allowed md:opacity-30" : "hover:opacity-80"
                }`}
              aria-label="Next"
            >
              <ChevronRight size={24} className="text-[#d20010]" />
            </button>
          </div>
        </div>
      </div>
    </section>
  )
}
