"use client"

import { useState, useEffect } from "react"
import Image from "next/image"
import Link from "next/link"
import { ChevronDown, Filter, Star, X, SlidersHorizontal, Check, ShoppingCart, Heart } from "lucide-react"
import { useCart } from "@/context/CartContext"
import AddToCartButton from "./AddToCartButton"
import { getProducts } from "@/lib/products"

export default function CategoryPage({ slug }) {
  const [products, setProducts] = useState([])
  const [loading, setLoading] = useState(true)
  const [filters, setFilters] = useState({
    price: [0, 300],
    sort: "popular",
  })
  const [mobileFiltersOpen, setMobileFiltersOpen] = useState(false)
  const [activeFilters, setActiveFilters] = useState([])
  const [isVisible, setIsVisible] = useState(false)
  const { addToCart } = useCart()
  const [visibleProducts, setVisibleProducts] = useState(9)

  // Fetch products
  useEffect(() => {
    const fetchProducts = async () => {
      setLoading(true)
      try {
        const allProducts = await getProducts()

        // Filter products based on category slug
        const filteredProducts = allProducts.filter((product) => {
          // Check in both category and categories array
          if (product.category && product.category.toLowerCase() === slug.toLowerCase()) {
            return true
          }

          if (product.categories && Array.isArray(product.categories)) {
            return product.categories.some((cat) => cat.toLowerCase() === slug.toLowerCase())
          }

          return false
        })

        setProducts(filteredProducts)
        setLoading(false)
        setIsVisible(true)
      } catch (error) {
        console.error("Error fetching products:", error)
        setLoading(false)
      }
    }

    fetchProducts()
  }, [slug])

  const toggleFilter = (filter) => {
    if (activeFilters.includes(filter)) {
      setActiveFilters(activeFilters.filter((f) => f !== filter))
    } else {
      setActiveFilters([...activeFilters, filter])
    }
  }

  const handleSortChange = (e) => {
    setFilters({ ...filters, sort: e.target.value })

    // Sort products based on selection
    const sortedProducts = [...products]
    if (e.target.value === "price-low") {
      sortedProducts.sort((a, b) => a.price - b.price)
    } else if (e.target.value === "price-high") {
      sortedProducts.sort((a, b) => b.price - a.price)
    } else if (e.target.value === "newest") {
      sortedProducts.sort((a, b) => {
        if (a.updatedAt && b.updatedAt) {
          return new Date(b.updatedAt) - new Date(a.updatedAt)
        }
        return 0
      })
    } else if (e.target.value === "name") {
      sortedProducts.sort((a, b) => a.name.localeCompare(b.name))
    }

    setProducts(sortedProducts)
  }

  const loadMoreProducts = () => {
    setVisibleProducts((prev) => prev + 6)
  }

  const resetFilters = () => {
    setFilters({ price: [0, 300], sort: "popular" })
    setActiveFilters([])
  }

  const categoryTitle = slug.charAt(0).toUpperCase() + slug.slice(1).replace(/-/g, " ")

  return (
    <div className="min-h-screen bg-gradient-to-b from-white to-gray-50">
      {/* Category Header */}
      <div className="relative overflow-hidden bg-gradient-to-r from-purple-900 to-indigo-800 py-20">
        <div className="absolute inset-0 bg-[url('/grid-pattern.png')] bg-repeat opacity-10"></div>
        <div className="absolute top-0 right-0 w-96 h-96 rounded-full bg-purple-600 opacity-20 blur-[100px]"></div>
        <div className="absolute bottom-0 left-0 w-64 h-64 rounded-full bg-indigo-500 opacity-20 blur-[80px]"></div>

        {/* Animated shapes */}
        <div className="absolute top-20 left-10 w-20 h-20 rounded-full bg-purple-400 opacity-20 animate-float"></div>
        <div className="absolute bottom-10 right-20 w-16 h-16 rounded-full bg-indigo-400 opacity-20 animate-float-delayed"></div>
        <div className="absolute top-40 right-40 w-12 h-12 rounded-full bg-pink-400 opacity-20 animate-float-slow"></div>

        <div className="container mx-auto px-4 relative z-10">
          <div className="max-w-4xl mx-auto text-center">
            <h1 className="text-4xl md:text-5xl font-bold mb-4 text-white">{categoryTitle}</h1>
            <p className="text-purple-100 text-lg max-w-2xl mx-auto">
              Ontdek onze selectie van hoogwaardige {categoryTitle.toLowerCase()} producten. Veilig en discreet geleverd
              binnen 1-3 werkdagen.
            </p>

            <div className="flex flex-wrap justify-center gap-3 mt-6">
              {["Betrouwbaar", "Discreet", "Snelle levering", "Kwaliteitsgarantie"].map((tag, index) => (
                <span
                  key={index}
                  className="px-4 py-2 bg-white/10 backdrop-blur-sm rounded-full text-sm font-medium text-white shadow-sm border border-white/20"
                >
                  {tag}
                </span>
              ))}
            </div>
          </div>
        </div>
      </div>

      {/* Filters and Products */}
      <div className="container mx-auto px-4 py-12">
        <div className="flex flex-col lg:flex-row gap-8">
          {/* Filters - Desktop */}
          <div className="hidden lg:block w-72 flex-shrink-0">
            <div className="sticky top-24 bg-white rounded-2xl shadow-lg border border-gray-100 overflow-hidden">
              <div className="p-6 border-b border-gray-100">
                <h2 className="font-bold text-xl flex items-center text-gray-800">
                  <Filter size={18} className="mr-2 text-purple-600" />
                  Filters
                </h2>
                <p className="text-sm text-gray-500 mt-1">{products.length} producten gevonden</p>
              </div>

              <div className="p-6 border-b border-gray-100">
                <div className="flex justify-between items-center mb-4">
                  <h3 className="font-medium text-gray-900">Prijs</h3>
                  <ChevronDown size={16} className="text-gray-400" />
                </div>

                <div className="space-y-3">
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-gray-500">€{filters.price[0]}</span>
                    <span className="text-sm text-gray-500">€{filters.price[1]}</span>
                  </div>

                  <input
                    type="range"
                    min="0"
                    max="300"
                    value={filters.price[1]}
                    onChange={(e) =>
                      setFilters({ ...filters, price: [filters.price[0], Number.parseInt(e.target.value)] })
                    }
                    className="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer accent-purple-600"
                  />

                  <div className="mt-6 flex items-center">
                    <input
                      type="number"
                      min="0"
                      max={filters.price[1]}
                      value={filters.price[0]}
                      onChange={(e) => setFilters({ ...filters, price: [Number(e.target.value), filters.price[1]] })}
                      className="w-20 px-2 py-1 border border-gray-300 rounded-md text-sm"
                    />
                    <span className="mx-2 text-gray-500">tot</span>
                    <input
                      type="number"
                      min={filters.price[0]}
                      max="300"
                      value={filters.price[1]}
                      onChange={(e) => setFilters({ ...filters, price: [filters.price[0], Number(e.target.value)] })}
                      className="w-20 px-2 py-1 border border-gray-300 rounded-md text-sm"
                    />
                  </div>
                </div>
              </div>

              <div className="p-6">
                <div className="flex justify-between items-center mb-4">
                  <h3 className="font-medium text-gray-900">Beschikbaarheid</h3>
                  <ChevronDown size={16} className="text-gray-400" />
                </div>

                <div className="space-y-3">
                  {["Op voorraad", "Aanbieding", "Nieuw"].map((option, index) => (
                    <div key={index} className="flex items-center">
                      <button
                        className={`w-5 h-5 rounded flex items-center justify-center ${activeFilters.includes(option) ? "bg-purple-600 text-white" : "border border-gray-300"
                          }`}
                        onClick={() => toggleFilter(option)}
                      >
                        {activeFilters.includes(option) && <Check size={14} />}
                      </button>
                      <span className="ml-3 text-sm text-gray-700">{option}</span>
                    </div>
                  ))}
                </div>
              </div>

              {/* Reset Filters */}
              <div className="p-6 border-t border-gray-100 bg-gray-50">
                <button
                  onClick={resetFilters}
                  className="w-full py-2.5 bg-white border border-gray-200 rounded-lg text-gray-700 font-medium hover:bg-gray-50 transition-colors"
                >
                  Alle filters wissen
                </button>
              </div>
            </div>
          </div>

          {/* Mobile Filters Button */}
          <div className="lg:hidden flex justify-between items-center mb-6">
            <button
              className="flex items-center px-4 py-2 bg-white rounded-lg shadow-sm border border-gray-200 text-gray-700"
              onClick={() => setMobileFiltersOpen(true)}
            >
              <SlidersHorizontal size={18} className="mr-2 text-purple-600" />
              Filters
              <span className="bg-purple-100 text-purple-700 text-xs font-medium px-2 py-0.5 rounded-full ml-2">
                {products.length}
              </span>
            </button>

            <div className="relative">
              <select
                value={filters.sort}
                onChange={handleSortChange}
                className="appearance-none bg-white border border-gray-200 rounded-lg py-2 pl-4 pr-10 text-sm text-gray-700 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent"
              >
                <option value="popular">Populair</option>
                <option value="price-low">Prijs: laag naar hoog</option>
                <option value="price-high">Prijs: hoog naar laag</option>
                <option value="newest">Nieuwste</option>
                <option value="name">Naam</option>
              </select>
              <ChevronDown
                size={16}
                className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 pointer-events-none"
              />
            </div>
          </div>

          {/* Mobile Filters Drawer */}
          {mobileFiltersOpen && (
            <div className="fixed inset-0 z-50 overflow-hidden lg:hidden">
              <div
                className="absolute inset-0 bg-gray-500 bg-opacity-75 transition-opacity"
                onClick={() => setMobileFiltersOpen(false)}
              ></div>

              <div className="fixed inset-y-0 right-0 max-w-full flex">
                <div className="relative w-screen max-w-md">
                  <div className="h-full flex flex-col bg-white shadow-xl overflow-y-auto">
                    <div className="flex items-center justify-between px-4 py-5 border-b border-gray-200">
                      <h2 className="text-lg font-medium text-gray-900">Filters</h2>
                      <button
                        className="rounded-md text-gray-400 hover:text-gray-500 focus:outline-none"
                        onClick={() => setMobileFiltersOpen(false)}
                      >
                        <X size={24} />
                      </button>
                    </div>

                    <div className="p-6 border-b border-gray-200">
                      <h3 className="font-medium text-gray-900 mb-4">Prijs</h3>
                      <div className="space-y-3">
                        <div className="flex items-center justify-between">
                          <span className="text-sm text-gray-500">€{filters.price[0]}</span>
                          <span className="text-sm text-gray-500">€{filters.price[1]}</span>
                        </div>

                        <input
                          type="range"
                          min="0"
                          max="300"
                          value={filters.price[1]}
                          onChange={(e) =>
                            setFilters({ ...filters, price: [filters.price[0], Number.parseInt(e.target.value)] })
                          }
                          className="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer accent-purple-600"
                        />

                        <div className="mt-6 flex items-center">
                          <input
                            type="number"
                            min="0"
                            max={filters.price[1]}
                            value={filters.price[0]}
                            onChange={(e) =>
                              setFilters({ ...filters, price: [Number(e.target.value), filters.price[1]] })
                            }
                            className="w-20 px-2 py-1 border border-gray-300 rounded-md text-sm"
                          />
                          <span className="mx-2 text-gray-500">tot</span>
                          <input
                            type="number"
                            min={filters.price[0]}
                            max="300"
                            value={filters.price[1]}
                            onChange={(e) =>
                              setFilters({ ...filters, price: [filters.price[0], Number(e.target.value)] })
                            }
                            className="w-20 px-2 py-1 border border-gray-300 rounded-md text-sm"
                          />
                        </div>
                      </div>
                    </div>

                    <div className="p-6 border-b border-gray-200">
                      <h3 className="font-medium text-gray-900 mb-4">Beschikbaarheid</h3>
                      <div className="space-y-4">
                        {["Op voorraad", "Aanbieding", "Nieuw"].map((option, index) => (
                          <div key={index} className="flex items-center">
                            <button
                              className={`w-5 h-5 rounded flex items-center justify-center ${activeFilters.includes(option) ? "bg-purple-600 text-white" : "border border-gray-300"
                                }`}
                              onClick={() => toggleFilter(option)}
                            >
                              {activeFilters.includes(option) && <Check size={14} />}
                            </button>
                            <span className="ml-3 text-sm text-gray-700">{option}</span>
                          </div>
                        ))}
                      </div>
                    </div>

                    <div className="p-6 border-b border-gray-200">
                      <h3 className="font-medium text-gray-900 mb-4">Sorteren</h3>
                      <select
                        value={filters.sort}
                        onChange={handleSortChange}
                        className="w-full bg-white border border-gray-200 rounded-lg py-2 px-4 text-sm text-gray-700 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                      >
                        <option value="popular">Populair</option>
                        <option value="price-low">Prijs: laag naar hoog</option>
                        <option value="price-high">Prijs: hoog naar laag</option>
                        <option value="newest">Nieuwste</option>
                        <option value="name">Naam</option>
                      </select>
                    </div>

                    <div className="p-6">
                      <div className="flex space-x-3">
                        <button
                          onClick={resetFilters}
                          className="flex-1 py-2.5 bg-white border border-gray-300 rounded-lg text-gray-700 font-medium hover:bg-gray-50"
                        >
                          Wis filters
                        </button>
                        <button
                          className="flex-1 py-2.5 bg-purple-600 text-white font-medium rounded-lg shadow-md hover:bg-purple-700 transition-colors"
                          onClick={() => setMobileFiltersOpen(false)}
                        >
                          Toepassen
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* Products Grid */}
          <div className="flex-1">
            {/* Desktop Sort */}
            <div className="hidden lg:flex justify-between items-center mb-6">
              <p className="text-gray-600">{products.length} producten gevonden</p>

              <div className="relative">
                <select
                  value={filters.sort}
                  onChange={handleSortChange}
                  className="appearance-none bg-white border border-gray-200 rounded-lg py-2.5 pl-4 pr-10 text-sm text-gray-700 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                >
                  <option value="popular">Populair</option>
                  <option value="price-low">Prijs: laag naar hoog</option>
                  <option value="price-high">Prijs: hoog naar laag</option>
                  <option value="newest">Nieuwste</option>
                  <option value="name">Naam</option>
                </select>
                <ChevronDown
                  size={16}
                  className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 pointer-events-none"
                />
              </div>
            </div>

            {/* Loading State */}
            {loading ? (
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
                {[1, 2, 3, 4, 5, 6].map((item) => (
                  <div
                    key={item}
                    className="bg-white rounded-2xl overflow-hidden shadow-sm border border-gray-100 animate-pulse"
                  >
                    <div className="h-56 bg-gray-200"></div>
                    <div className="p-5 space-y-3">
                      <div className="h-4 bg-gray-200 rounded w-3/4"></div>
                      <div className="h-4 bg-gray-200 rounded w-1/2"></div>
                      <div className="h-6 bg-gray-200 rounded w-1/4 mt-2"></div>
                      <div className="h-10 bg-gray-200 rounded mt-4"></div>
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <>
                {/* Active Filters */}
                {activeFilters.length > 0 && (
                  <div className="flex flex-wrap gap-2 mb-6 bg-gray-50 p-4 rounded-xl">
                    <span className="text-sm text-gray-500 mr-2 self-center">Actieve filters:</span>

                    {activeFilters.map((filter, index) => (
                      <div
                        key={index}
                        className="flex items-center px-3 py-1.5 bg-white rounded-full text-sm text-gray-700 shadow-sm border border-gray-100"
                      >
                        <span>{filter}</span>
                        <button className="ml-2 text-gray-400 hover:text-gray-600" onClick={() => toggleFilter(filter)}>
                          <X size={14} />
                        </button>
                      </div>
                    ))}

                    <button
                      className="text-sm text-purple-600 hover:text-purple-800 font-medium ml-auto"
                      onClick={() => setActiveFilters([])}
                    >
                      Wis filters
                    </button>
                  </div>
                )}

                {/* Products */}
                {products.filter((product) => product.price <= filters.price[1] && product.price >= filters.price[0])
                  .length === 0 ? (
                  <div className="text-center py-12 bg-white rounded-2xl shadow-md">
                    <div className="mx-auto w-24 h-24 bg-gray-100 rounded-full flex items-center justify-center mb-4">
                      <Filter size={32} className="text-gray-400" />
                    </div>
                    <h3 className="text-lg font-medium text-gray-900 mb-2">Geen producten gevonden</h3>
                    <p className="text-gray-500 mb-6">Probeer andere filters of zoek opnieuw.</p>
                    <button
                      className="px-4 py-2 bg-purple-600 text-white font-medium rounded-lg shadow-md hover:bg-purple-700 transition-colors"
                      onClick={resetFilters}
                    >
                      Wis alle filters
                    </button>
                  </div>
                ) : (
                  <div
                    className={`grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6 ${isVisible ? "animate-fade-in" : "opacity-0"
                      }`}
                  >
                    {products
                      .filter((product) => product.price <= filters.price[1] && product.price >= filters.price[0])
                      .slice(0, visibleProducts)
                      .map((product, index) => (
                        <div
                          key={product.id}
                          className="group bg-white rounded-2xl overflow-hidden shadow-md hover:shadow-xl transition-all duration-300 border border-gray-100 hover:border-purple-200 relative"
                          style={{ animationDelay: `${index * 0.1}s` }}
                        >
                          {/* Discount badge */}
                          {product.originalPrice && product.originalPrice > product.price && (
                            <div className="absolute top-4 left-4 z-50 bg-red-500 text-white text-xs font-bold px-2 py-1 rounded-full">
                              -{Math.round(((product.originalPrice - product.price) / product.originalPrice) * 100)}%
                            </div>
                          )}


                          {/* Quick actions */}
                          <div className="absolute right-4 top-20 z-50 flex flex-col gap-2 opacity-0 group-hover:opacity-100 transition-opacity duration-300">
                            <button className="bg-white p-2 rounded-full shadow-md hover:bg-gray-50 transition-colors">
                              <Heart size={18} className="text-gray-600" />
                            </button>
                            <button className="bg-white p-2 rounded-full shadow-md hover:bg-gray-50 transition-colors">
                              <ShoppingCart size={18} className="text-gray-600" />
                            </button>
                          </div>

                          <Link href={`/product/${product.slug}`}>
                            <div className="relative h-56 bg-gray-50 overflow-hidden group-hover:bg-purple-50 transition-colors duration-300">
                              <div className="absolute inset-0 bg-gradient-to-br from-white/60 via-transparent to-transparent z-0"></div>
                              <Image
                                src={product.image || "/placeholder.svg?height=300&width=300&query=medicine"}
                                alt={product.name}
                                fill
                                sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
                                className="object-contain p-4 z-10 transform group-hover:scale-110 transition-transform duration-500"
                                loading="lazy"
                              />
                            </div>

                            <div className="p-5">
                              <h3 className="font-medium text-lg text-gray-900 group-hover:text-purple-700 transition-colors line-clamp-2 h-14 mb-2">
                                {product.name}
                              </h3>

                              <div className="flex items-end">
                                {product.originalPrice && product.originalPrice > product.price ? (
                                  <div className="flex items-center gap-2">
                                    <span className="text-gray-400 line-through text-sm">
                                      €{product.originalPrice.toFixed(2)}
                                    </span>
                                    <span className="text-lg font-bold text-purple-700">
                                      €{product.price.toFixed(2)}
                                    </span>
                                  </div>
                                ) : (
                                  <span className="text-lg font-bold text-purple-700">€{product.price.toFixed(2)}</span>
                                )}
                              </div>
                            </div>
                          </Link>

                          <div className="px-5 pb-5">
                            <AddToCartButton
                              id={product?.id}
                              name={product?.name}
                              price={product?.price}
                              image={product?.image}
                              className="w-full py-2.5 bg-purple-600 hover:bg-purple-700 text-white font-medium rounded-lg transition-all duration-300 shadow-md hover:shadow-lg flex items-center justify-center gap-2"
                            >
                              <ShoppingCart size={18} />
                              <span>In winkelwagen</span>
                            </AddToCartButton>
                          </div>
                        </div>
                      ))}
                  </div>
                )}

                {/* Load More Button */}
                {products.filter((product) => product.price <= filters.price[1] && product.price >= filters.price[0])
                  .length > visibleProducts && (
                    <div className="mt-10 text-center">
                      <button
                        onClick={loadMoreProducts}
                        className="px-6 py-3 bg-white border border-purple-200 rounded-xl text-purple-700 font-medium hover:bg-purple-50 transition-colors shadow-sm"
                      >
                        Meer producten laden
                      </button>
                    </div>
                  )}
              </>
            )}
          </div>
        </div>
      </div>
    </div>
  )
}
