"use client"

import { useState, useRef, useEffect } from "react"
import Link from "next/link"
import Image from "next/image"
import { ChevronLeft, ChevronRight, Star, ShoppingCart, Heart, Eye } from "lucide-react"
import { useCart } from "@/context/CartContext"
import AddToCartButton from "./AddToCartButton"
import { products } from "@/lib/products"

export default function BestSellers() {
  const scrollRef = useRef(null)
  const [canScrollLeft, setCanScrollLeft] = useState(false)
  const [canScrollRight, setCanScrollRight] = useState(true)
  const { addToCart } = useCart()
  const [isVisible, setIsVisible] = useState(false)
  const [hoveredProduct, setHoveredProduct] = useState(null)

  const checkScrollButtons = () => {
    if (scrollRef.current) {
      const { scrollLeft, scrollWidth, clientWidth } = scrollRef.current
      setCanScrollLeft(scrollLeft > 0)
      setCanScrollRight(scrollLeft < scrollWidth - clientWidth - 10)
    }
  }

  const scroll = (direction) => {
    if (scrollRef.current) {
      const { clientWidth } = scrollRef.current
      const scrollAmount = direction === "left" ? -clientWidth / 2 : clientWidth / 2
      scrollRef.current.scrollBy({ left: scrollAmount, behavior: "smooth" })
      setTimeout(checkScrollButtons, 300)
    }
  }

  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setIsVisible(true)
        }
      },
      { threshold: 0.1 },
    )

    if (scrollRef.current) {
      observer.observe(scrollRef.current)
    }

    return () => {
      if (scrollRef.current) {
        observer.unobserve(scrollRef.current)
      }
    }
  }, [])



  return (
    <section className="py-20 relative overflow-hidden">
      {/* Background elements */}
      <div className="absolute inset-0 bg-gradient-to-br from-[#f0e7ff] to-[#ffffff]"></div>
      <div className="absolute top-0 left-0 w-full h-full bg-[url('/grid-pattern.png')] bg-center opacity-5"></div>
      <div className="absolute top-20 right-20 w-64 h-64 rounded-full bg-[#8a2be2] opacity-10 blur-[100px]"></div>
      <div className="absolute bottom-10 left-10 w-96 h-96 rounded-full bg-[#00e889] opacity-5 blur-[120px]"></div>

      {/* Decorative elements */}
      <div className="absolute top-40 left-10 w-20 h-20 rounded-full border-4 border-[#8a2be2] border-opacity-10"></div>
      <div className="absolute bottom-40 right-10 w-32 h-32 rounded-full border-8 border-[#8a2be2] border-opacity-5"></div>
      <div className="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-[800px] h-[800px] rounded-full border border-[#8a2be2] border-opacity-5"></div>

      <div className="container mx-auto px-4 relative z-10">
        <div className="text-center mb-12">
          <h2 className="text-4xl font-bold mb-4 inline-block relative">
            <span className="bg-clip-text text-transparent bg-gradient-to-r from-[#8a2be2] to-[#4c00b0]">
              Bestsellers
            </span>
            <div className="absolute -bottom-2 left-1/2 transform -translate-x-1/2 w-24 h-1 bg-gradient-to-r from-[#8a2be2] to-[#4c00b0] rounded-full"></div>
          </h2>
          <p className="text-gray-600 max-w-2xl mx-auto">
            Ontdek onze meest populaire producten die door klanten worden gewaardeerd om hun kwaliteit en effectiviteit.
          </p>
        </div>

        <div className="relative" onScroll={checkScrollButtons}>
          {/* Navigation buttons - Desktop */}
          <div className="hidden md:block">
            <button
              onClick={() => scroll("left")}
              disabled={!canScrollLeft}
              className={`absolute left-0 top-1/2 transform -translate-y-1/2 z-10 w-12 h-12 rounded-full flex items-center justify-center ${canScrollLeft
                ? "bg-white text-[#8a2be2] shadow-lg hover:bg-[#8a2be2] hover:text-white"
                : "bg-gray-100 text-gray-400 cursor-not-allowed"
                } transition-all duration-300`}
            >
              <ChevronLeft size={24} />
            </button>
            <button
              onClick={() => scroll("right")}
              disabled={!canScrollRight}
              className={`absolute right-0 top-1/2 transform -translate-y-1/2 z-10 w-12 h-12 rounded-full flex items-center justify-center ${canScrollRight
                ? "bg-white text-[#8a2be2] shadow-lg hover:bg-[#8a2be2] hover:text-white"
                : "bg-gray-100 text-gray-400 cursor-not-allowed"
                } transition-all duration-300`}
            >
              <ChevronRight size={24} />
            </button>
          </div>

          <div
            ref={scrollRef}
            className={`flex overflow-x-auto gap-6 pb-8 px-4 scrollbar-hide ${isVisible ? "animate-fade-in" : "opacity-0"}`}
            style={{ scrollbarWidth: "none", msOverflowStyle: "none" }}
          >
            {products.map((product, index) => (
              <div
                key={product.id}
                className="flex-none w-[300px] relative group"
                onMouseEnter={() => setHoveredProduct(product.id)}
                onMouseLeave={() => setHoveredProduct(null)}
              >
                <div
                  className="bg-white rounded-2xl overflow-hidden shadow-md hover:shadow-xl transition-all duration-500 border border-gray-100 h-full transform hover:-translate-y-2"
                  style={{ animationDelay: `${index * 0.1}s` }}
                >
                  <div className="relative">
                    <Link href={`/product/${product.slug.toLowerCase().split(" ").join("-")}`}>
                      <div className="relative h-64 w-full bg-[#f8fafc] overflow-hidden group-hover:bg-[#f5f0ff] transition-colors duration-300">
                        <Image
                          src={product.image || "/placeholder.svg"}
                          alt={product.name}
                          fill
                          sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
                          className="object-contain p-4 transform group-hover:scale-105 transition-transform duration-500"
                          loading="lazy"
                        />
                      </div>
                    </Link>

                    {/* Floating action buttons */}
                    <div
                      className={`absolute right-4 top-4 flex flex-col gap-2 transition-all duration-300 ${hoveredProduct === product.id ? "opacity-100 translate-x-0" : "opacity-0 translate-x-4"
                        }`}
                    >
                      <button className="w-10 h-10 rounded-full bg-white shadow-md flex items-center justify-center text-[#8a2be2] hover:bg-[#8a2be2] hover:text-white transition-colors">
                        <Heart size={18} />
                      </button>
                      <Link href={`/product/${product.slug.toLowerCase().split(" ").join("-")}`}>
                        <button className="w-10 h-10 rounded-full bg-white shadow-md flex items-center justify-center text-[#8a2be2] hover:bg-[#8a2be2] hover:text-white transition-colors">
                          <Eye size={18} />
                        </button>
                      </Link>
                    </div>

                    {/* Discount badge */}
                    {product.originalPrice && (
                      <div className="absolute top-4 left-4 bg-gradient-to-r from-[#8a2be2] to-[#4c00b0] text-white text-xs font-bold px-3 py-1.5 rounded-full">
                        -{Math.round(((product.originalPrice - product.price) / product.originalPrice) * 100)}%
                      </div>
                    )}
                  </div>

                  <div className="p-6">


                    <Link href={`/product/${product.slug.toLowerCase().split(" ").join("-")}`}>
                      <h3 className="font-medium text-gray-900 group-hover:text-[#8a2be2] transition-colors line-clamp-2 h-12 mb-2 text-lg">
                        {product.name}
                      </h3>
                    </Link>

                    <div className="flex items-center justify-between mt-4">
                      <div className="flex items-end">
                        {product.originalPrice && (
                          <span className="text-sm text-gray-500 line-through mr-2">
                            €{product.originalPrice.toFixed(2)}
                          </span>
                        )}
                        <span className="text-xl font-bold text-[#8a2be2]">€{product.price.toFixed(2)}</span>
                      </div>

                      <AddToCartButton
                        id={product?.id}
                        name={product?.name}
                        price={product?.price}
                        image={product?.image}
                        className="w-12 h-12 rounded-full bg-gradient-to-r from-[#8a2be2] to-[#4c00b0] hover:from-[#7b1fa2] hover:to-[#3b0086] text-white flex items-center justify-center shadow-md hover:shadow-lg transition-all duration-300"
                        iconOnly={true}
                        icon={<ShoppingCart size={18} />}
                      />
                    </div>
                  </div>
                </div>

                {/* Floating category tag */}
                <div className="absolute -bottom-3 left-1/2 transform -translate-x-1/2 bg-white px-4 py-1 rounded-full text-xs font-medium text-[#8a2be2] shadow-sm border border-gray-100">
                  {product.categories[0]}
                </div>
              </div>
            ))}
          </div>

          {/* Mobile scroll buttons */}
          <div className="md:hidden flex justify-center mt-6 space-x-3">
            <button
              onClick={() => scroll("left")}
              disabled={!canScrollLeft}
              className={`p-3 rounded-full ${canScrollLeft
                ? "bg-white text-[#8a2be2] shadow-md hover:bg-[#8a2be2] hover:text-white"
                : "bg-gray-100 text-gray-400 cursor-not-allowed"
                } transition-all duration-300`}
            >
              <ChevronLeft size={20} />
            </button>
            <button
              onClick={() => scroll("right")}
              disabled={!canScrollRight}
              className={`p-3 rounded-full ${canScrollRight
                ? "bg-white text-[#8a2be2] shadow-md hover:bg-[#8a2be2] hover:text-white"
                : "bg-gray-100 text-gray-400 cursor-not-allowed"
                } transition-all duration-300`}
            >
              <ChevronRight size={20} />
            </button>
          </div>
        </div>

        {/* View all button */}
        <div className="text-center mt-10">
          <Link href="/shop">
            <button className="px-8 py-3 bg-white border border-[#8a2be2] text-[#8a2be2] font-medium rounded-full hover:bg-[#8a2be2] hover:text-white transition-colors duration-300 shadow-sm hover:shadow-md">
              Bekijk alle producten
            </button>
          </Link>
        </div>
      </div>
    </section>
  )
}
