"use client"

import { useState, useEffect, useRef } from "react"
import Image from "next/image"
import Link from "next/link"
import { ChevronLeft, ChevronRight, Store, Star, ShoppingBag, BadgeCheck } from "lucide-react"

interface TopSeller {
  id: string
  shopName: string
  shopSlug: string | null
  shopLogo: string | null
  shopBanner: string | null
  shopBio: string | null
  totalProducts: number
  totalSales: number
  isVerified: boolean
}

export function TopSellersCarousel() {
  const [sellers, setSellers] = useState<TopSeller[]>([])
  const [scrollPos, setScrollPos] = useState(0)
  const scrollRef = useRef<HTMLDivElement>(null)
  const [canScrollLeft, setCanScrollLeft] = useState(false)
  const [canScrollRight, setCanScrollRight] = useState(true)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    fetch("/api/shop/top-sellers")
      .then((r) => r.json())
      .then((data) => {
        if (data.sellers?.length) {
          setSellers(data.sellers)
        }
      })
      .catch(() => {})
      .finally(() => setLoading(false))
  }, [])

  const updateScrollButtons = () => {
    const el = scrollRef.current
    if (!el) return
    setCanScrollLeft(el.scrollLeft > 0)
    setCanScrollRight(el.scrollLeft + el.clientWidth < el.scrollWidth - 4)
  }

  const scroll = (direction: "left" | "right") => {
    const el = scrollRef.current
    if (!el) return
    const cardWidth = 260
    const newPos = direction === "left"
      ? Math.max(0, el.scrollLeft - cardWidth - 16)
      : el.scrollLeft + cardWidth + 16
    el.scrollTo({ left: newPos, behavior: "smooth" })
    setTimeout(updateScrollButtons, 400)
  }

  if (loading || sellers.length === 0) return null

  return (
    <div className="mb-6">
      {/* Header */}
      <div className="flex items-center justify-between mb-3">
        <div className="flex items-center gap-2">
          <Star className="h-4 w-4 text-amber-500 fill-amber-500" />
          <h3 className="text-sm font-bold text-gray-900">Top Sellers</h3>
          <span className="text-[11px] text-gray-400 bg-gray-100 px-2 py-0.5 rounded-full">
            {sellers.length} shops
          </span>
        </div>
        <div className="flex gap-1">
          <button
            onClick={() => scroll("left")}
            disabled={!canScrollLeft}
            className="h-7 w-7 rounded-full flex items-center justify-center bg-white border border-gray-200 shadow-sm disabled:opacity-30 disabled:cursor-not-allowed hover:bg-gray-50 transition-colors"
          >
            <ChevronLeft className="h-3.5 w-3.5 text-gray-600" />
          </button>
          <button
            onClick={() => scroll("right")}
            disabled={!canScrollRight}
            className="h-7 w-7 rounded-full flex items-center justify-center bg-white border border-gray-200 shadow-sm disabled:opacity-30 disabled:cursor-not-allowed hover:bg-gray-50 transition-colors"
          >
            <ChevronRight className="h-3.5 w-3.5 text-gray-600" />
          </button>
        </div>
      </div>

      {/* Cards */}
      <div
        ref={scrollRef}
        onScroll={updateScrollButtons}
        className="flex gap-3 overflow-x-auto scrollbar-hide pb-2 snap-x snap-mandatory"
        style={{ scrollbarWidth: "none", msOverflowStyle: "none" }}
      >
        {sellers.map((seller) => (
          <Link
            key={seller.id}
            href={seller.shopSlug ? `/shop/${seller.shopSlug}` : "#"}
            className="snap-start shrink-0 w-[220px]"
          >
            <div className="group relative bg-white rounded-xl border border-gray-100 shadow-sm hover:shadow-md transition-all duration-300 overflow-hidden h-full">
              {/* Banner strip */}
              <div className="h-20 relative overflow-hidden">
                {seller.shopBanner ? (
                  <Image
                    src={seller.shopBanner}
                    alt=""
                    fill
                    className="object-cover group-hover:scale-105 transition-transform duration-500"
                  />
                ) : (
                  <div className="absolute inset-0 bg-gradient-to-br from-violet-400 via-purple-400 to-fuchsia-400">
                    <div className="absolute inset-0 opacity-20">
                      <div className="absolute -top-6 -right-6 w-20 h-20 bg-white rounded-full" />
                      <div className="absolute -bottom-4 -left-4 w-16 h-16 bg-white rounded-full" />
                    </div>
                  </div>
                )}
                {/* Gradient overlay at bottom of banner */}
                <div className="absolute inset-x-0 bottom-0 h-12 bg-gradient-to-t from-white to-transparent" />
              </div>

              {/* Logo — overlaps banner bottom */}
              <div className="relative -mt-8 mx-auto w-14 h-14 rounded-full border-[3px] border-white bg-white shadow-md overflow-hidden z-10">
                {seller.shopLogo ? (
                  <Image
                    src={seller.shopLogo}
                    alt={seller.shopName}
                    fill
                    className="object-cover"
                  />
                ) : (
                  <div className="w-full h-full bg-gradient-to-br from-violet-100 to-purple-100 flex items-center justify-center">
                    <Store className="h-6 w-6 text-purple-400" />
                  </div>
                )}
              </div>

              {/* Info */}
              <div className="px-3 pb-3 pt-1 text-center">
                <div className="flex items-center justify-center gap-1">
                  <h4 className="font-semibold text-sm text-gray-900 truncate max-w-[140px]">
                    {seller.shopName}
                  </h4>
                  {seller.isVerified && (
                    <BadgeCheck className="h-3.5 w-3.5 text-blue-500 shrink-0" />
                  )}
                </div>

                {/* Stats row */}
                <div className="flex items-center justify-center gap-3 mt-2">
                  <div className="flex items-center gap-1 text-[11px] text-gray-500">
                    <ShoppingBag className="h-3 w-3" />
                    <span>{seller.totalProducts}</span>
                  </div>
                  <div className="w-px h-3 bg-gray-200" />
                  <div className="flex items-center gap-1 text-[11px] text-gray-500">
                    <Star className="h-3 w-3" />
                    <span>{seller.totalSales} sold</span>
                  </div>
                </div>

                {/* Visit shop CTA */}
                <div className="mt-2 opacity-0 group-hover:opacity-100 transition-opacity duration-200">
                  <span className="text-[11px] font-medium text-purple-600 bg-purple-50 px-3 py-1 rounded-full">
                    Visit Shop →
                  </span>
                </div>
              </div>
            </div>
          </Link>
        ))}
      </div>
    </div>
  )
}
