"use client"

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

export default function ShopPage() {
  const [products, setProducts] = useState([])
  const [filteredProducts, setFilteredProducts] = useState([])
  const [searchQuery, setSearchQuery] = useState("")
  const [selectedCategory, setSelectedCategory] = useState("all")
  const [priceRange, setPriceRange] = useState([0, 300])
  const [sortBy, setSortBy] = useState("popularity")
  const [showFilters, setShowFilters] = useState(false)
  const [selectedTags, setSelectedTags] = useState([])
  const [isLoading, setIsLoading] = useState(true)
  const [visibleProducts, setVisibleProducts] = useState(12)
  const [activeView, setActiveView] = useState("grid") // grid or list

  // Get unique categories
  const [categories, setCategories] = useState(["all"])

  // Get unique tags
  const [allTags, setAllTags] = useState([])

  // Fetch products
  useEffect(() => {
    const fetchProducts = async () => {
      setIsLoading(true)
      try {
        const data = await getProducts()
        setProducts(data)

        // Extract unique categories
        const uniqueCategories = [
          "all",
          ...new Set(data.flatMap((product) => (product.categories ? product.categories : [product.category]))),
        ]
        setCategories(uniqueCategories)

        // Extract unique tags
        const tags = [
          ...new Set(
            data.flatMap(
              (product) =>
                product.keywords || ["medicijn", "gezondheid", "behandeling", "pijnstiller", "slaap", "angst"],
            ),
          ),
        ]
        setAllTags(tags)

        setIsLoading(false)
      } catch (error) {
        console.error("Error fetching products:", error)
        setIsLoading(false)
      }
    }

    fetchProducts()
  }, [])

  // Filter and sort products
  useEffect(() => {
    if (products.length === 0) return

    let result = [...products]

    // Filter by search query
    if (searchQuery) {
      result = result.filter(
        (product) =>
          product.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
          (product.description && product.description.toLowerCase().includes(searchQuery.toLowerCase())) ||
          (product.shortDescription && product.shortDescription.toLowerCase().includes(searchQuery.toLowerCase())),
      )
    }

    // Filter by category
    if (selectedCategory !== "all") {
      result = result.filter((product) => {
        if (product.categories) {
          return product.categories.some((cat) => cat.toLowerCase() === selectedCategory.toLowerCase())
        } else {
          return product.category.toLowerCase() === selectedCategory.toLowerCase()
        }
      })
    }

    // Filter by price range
    result = result.filter((product) => product.price >= priceRange[0] && product.price <= priceRange[1])

    // Filter by tags
    if (selectedTags.length > 0) {
      result = result.filter((product) => {
        const productTags = product.keywords || []
        return selectedTags.some((tag) => productTags.includes(tag))
      })
    }

    // Filter by availability
    result = result.filter((product) => product.available !== false)

    // Sort products
    switch (sortBy) {
      case "price-low":
        result.sort((a, b) => a.price - b.price)
        break
      case "price-high":
        result.sort((a, b) => b.price - a.price)
        break
      case "name":
        result.sort((a, b) => a.name.localeCompare(b.name))
        break
      case "newest":
        result.sort((a, b) => {
          if (a.updatedAt && b.updatedAt) {
            return new Date(b.updatedAt) - new Date(a.updatedAt)
          }
          return 0
        })
        break
      case "popularity":
      default:
        // Sort by popularity (using stock as a proxy for popularity)
        result.sort((a, b) => (b.stock || 0) - (a.stock || 0))
        break
    }

    setFilteredProducts(result)
  }, [products, searchQuery, selectedCategory, priceRange, sortBy, selectedTags])

  // Toggle tag selection
  const toggleTag = (tag) => {
    if (selectedTags.includes(tag)) {
      setSelectedTags(selectedTags.filter((t) => t !== tag))
    } else {
      setSelectedTags([...selectedTags, tag])
    }
  }

  // Reset all filters
  const resetFilters = () => {
    setSearchQuery("")
    setSelectedCategory("all")
    setPriceRange([0, 300])
    setSortBy("popularity")
    setSelectedTags([])
  }

  // Load more products
  const loadMoreProducts = () => {
    setVisibleProducts((prev) => prev + 8)
  }

  return (
    <div className="min-h-screen bg-gradient-to-b from-white to-gray-50">
      {/* Hero Banner */}
      <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-3xl mx-auto text-center">
            <h1 className="text-4xl md:text-5xl font-bold mb-6 text-white">
              Ontdek ons <span className="text-purple-300">assortiment</span>
            </h1>
            <p className="text-purple-100 text-lg mb-8 max-w-2xl mx-auto">
              Vind de medicijnen die je nodig hebt. Veilig, betrouwbaar en zonder recept. Discrete levering binnen 24
              uur.
            </p>

            {/* Search bar */}
            <div className="relative max-w-xl mx-auto">
              <input
                type="text"
                placeholder="Zoek naar medicijnen..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="w-full py-4 pl-14 pr-4 bg-white/90 backdrop-blur-sm rounded-full shadow-xl focus:outline-none focus:ring-2 focus:ring-purple-500 text-gray-800"
              />
              <Search className="absolute left-5 top-1/2 transform -translate-y-1/2 text-purple-600" size={22} />
              {searchQuery && (
                <button
                  onClick={() => setSearchQuery("")}
                  className="absolute right-5 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
                >
                  <X size={18} />
                </button>
              )}
            </div>

            {/* Quick category pills */}
            <div className="flex flex-wrap justify-center gap-3 mt-8">
              {categories.slice(0, 5).map((category, index) => (
                <button
                  key={index}
                  onClick={() => setSelectedCategory(category)}
                  className={`px-4 py-2 rounded-full text-sm font-medium transition-all duration-300 ${selectedCategory === category
                    ? "bg-purple-500 text-white shadow-lg"
                    : "bg-white/30 backdrop-blur-sm text-white hover:bg-white/50"
                    }`}
                >
                  {category.charAt(0).toUpperCase() + category.slice(1)}
                </button>
              ))}
            </div>
          </div>
        </div>
      </div>

      <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="bg-white rounded-2xl shadow-lg border border-gray-100 overflow-hidden sticky top-24">
              <div className="p-6 border-b border-gray-100">
                <h3 className="font-bold text-xl flex items-center text-gray-800">
                  <Filter size={18} className="mr-2 text-purple-600" />
                  Filters
                </h3>
                <p className="text-sm text-gray-500 mt-1">{filteredProducts.length} producten gevonden</p>
              </div>

              {/* Categories */}
              <div className="p-6 border-b border-gray-100">
                <h4 className="font-semibold mb-4 text-gray-700">Categorieën</h4>
                <div className="space-y-2 max-h-60 overflow-y-auto pr-2 custom-scrollbar">
                  {categories.map((category) => (
                    <button
                      key={category}
                      onClick={() => setSelectedCategory(category)}
                      className={`block w-full text-left px-3 py-2.5 rounded-lg transition-colors ${selectedCategory === category
                        ? "bg-purple-100 text-purple-700 font-medium"
                        : "hover:bg-gray-50 text-gray-600"
                        }`}
                    >
                      {category.charAt(0).toUpperCase() + category.slice(1)}
                      {selectedCategory === category && (
                        <span className="float-right text-purple-600">
                          <Check size={16} />
                        </span>
                      )}
                    </button>
                  ))}
                </div>
              </div>

              {/* Price Range */}
              <div className="p-6 border-b border-gray-100">
                <h4 className="font-semibold mb-4 text-gray-700">Prijsklasse</h4>
                <div className="px-2">
                  <div className="flex justify-between mb-2 text-sm text-gray-500">
                    <span>€{priceRange[0]}</span>
                    <span>€{priceRange[1]}</span>
                  </div>
                  <input
                    type="range"
                    min="0"
                    max="300"
                    value={priceRange[1]}
                    onChange={(e) => setPriceRange([priceRange[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={priceRange[1]}
                      value={priceRange[0]}
                      onChange={(e) => setPriceRange([Number(e.target.value), priceRange[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={priceRange[0]}
                      max="300"
                      value={priceRange[1]}
                      onChange={(e) => setPriceRange([priceRange[0], Number(e.target.value)])}
                      className="w-20 px-2 py-1 border border-gray-300 rounded-md text-sm"
                    />
                  </div>
                </div>
              </div>

              {/* Tags */}
              <div className="p-6">
                <h4 className="font-semibold mb-4 text-gray-700">Tags</h4>
                <div className="flex flex-wrap gap-2 max-h-60 overflow-y-auto pr-2 custom-scrollbar">
                  {allTags.map((tag) => (
                    <button
                      key={tag}
                      onClick={() => toggleTag(tag)}
                      className={`px-3 py-1.5 rounded-full text-sm transition-colors ${selectedTags.includes(tag)
                        ? "bg-purple-600 text-white"
                        : "bg-gray-100 text-gray-700 hover:bg-gray-200"
                        }`}
                    >
                      {tag}
                    </button>
                  ))}
                </div>

                {selectedTags.length > 0 && (
                  <button
                    onClick={() => setSelectedTags([])}
                    className="mt-4 text-sm text-purple-600 hover:text-purple-800 font-medium"
                  >
                    Wis geselecteerde tags
                  </button>
                )}
              </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 gap-3 sm:flex-row flex-col justify-between items-center mb-6">
            <button
              onClick={() => setShowFilters(!showFilters)}
              className="flex items-center gap-2 bg-white px-4 py-3 rounded-lg shadow-md border border-gray-200"
            >
              <SlidersHorizontal size={18} className="text-purple-600" />
              <span>Filters</span>
              <span className="bg-purple-100 text-purple-700 text-xs font-medium px-2 py-0.5 rounded-full ml-1">
                {filteredProducts.length}
              </span>
            </button>

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

          {/* Mobile Filters Drawer */}
          {showFilters && (
            <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={() => setShowFilters(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={() => setShowFilters(false)}
                      >
                        <X size={24} />
                      </button>
                    </div>

                    <div className="divide-y divide-gray-200 overflow-y-auto">
                      {/* Categories */}
                      <div className="p-6">
                        <h3 className="font-medium text-gray-900 mb-4">Categorieën</h3>
                        <div className="space-y-2">
                          {categories.map((category) => (
                            <button
                              key={category}
                              onClick={() => {
                                setSelectedCategory(category)
                                setShowFilters(false)
                              }}
                              className={`block w-full text-left px-3 py-2 rounded-lg transition-colors ${selectedCategory === category
                                ? "bg-purple-100 text-purple-700 font-medium"
                                : "hover:bg-gray-50 text-gray-600"
                                }`}
                            >
                              {category.charAt(0).toUpperCase() + category.slice(1)}
                            </button>
                          ))}
                        </div>
                      </div>

                      {/* Price Range */}
                      <div className="p-6">
                        <h3 className="font-medium text-gray-900 mb-4">Prijsklasse</h3>
                        <div className="px-2">
                          <div className="flex justify-between mb-2 text-sm text-gray-500">
                            <span>€{priceRange[0]}</span>
                            <span>€{priceRange[1]}</span>
                          </div>
                          <input
                            type="range"
                            min="0"
                            max="300"
                            value={priceRange[1]}
                            onChange={(e) => setPriceRange([priceRange[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={priceRange[1]}
                              value={priceRange[0]}
                              onChange={(e) => setPriceRange([Number(e.target.value), priceRange[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={priceRange[0]}
                              max="300"
                              value={priceRange[1]}
                              onChange={(e) => setPriceRange([priceRange[0], Number(e.target.value)])}
                              className="w-20 px-2 py-1 border border-gray-300 rounded-md text-sm"
                            />
                          </div>
                        </div>
                      </div>

                      {/* Tags */}
                      <div className="p-6">
                        <h3 className="font-medium text-gray-900 mb-4">Tags</h3>
                        <div className="flex flex-wrap gap-2">
                          {allTags.map((tag) => (
                            <button
                              key={tag}
                              onClick={() => toggleTag(tag)}
                              className={`px-3 py-1.5 rounded-full text-sm transition-colors ${selectedTags.includes(tag)
                                ? "bg-purple-600 text-white"
                                : "bg-gray-100 text-gray-700 hover:bg-gray-200"
                                }`}
                            >
                              {tag}
                            </button>
                          ))}
                        </div>
                      </div>

                      {/* Sort */}
                      <div className="p-6">
                        <h3 className="font-medium text-gray-900 mb-4">Sorteren</h3>
                        <select
                          value={sortBy}
                          onChange={(e) => setSortBy(e.target.value)}
                          className="w-full bg-white border border-gray-300 rounded-lg py-2 px-4 text-gray-700 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                        >
                          <option value="popularity">Populair</option>
                          <option value="price-low">Prijs: laag naar hoog</option>
                          <option value="price-high">Prijs: hoog naar laag</option>
                          <option value="name">Naam</option>
                          <option value="newest">Nieuwste</option>
                        </select>
                      </div>
                    </div>

                    <div className="p-6 border-t border-gray-200">
                      <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={() => setShowFilters(false)}
                        >
                          Toepassen
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* Main Content */}
          <div className="flex-1">
            {/* Desktop Sort and View Toggle */}
            <div className="hidden lg:flex justify-between items-center mb-6">
              <div className="flex items-center">
                <span className="text-gray-600 mr-3">Weergave:</span>
                <div className="flex border border-gray-200 rounded-lg overflow-hidden">
                  <button
                    onClick={() => setActiveView("grid")}
                    className={`px-3 py-2 ${activeView === "grid" ? "bg-purple-100 text-purple-700" : "bg-white text-gray-600"}`}
                  >
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      width="20"
                      height="20"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      strokeWidth="2"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                    >
                      <rect x="3" y="3" width="7" height="7"></rect>
                      <rect x="14" y="3" width="7" height="7"></rect>
                      <rect x="3" y="14" width="7" height="7"></rect>
                      <rect x="14" y="14" width="7" height="7"></rect>
                    </svg>
                  </button>
                  <button
                    onClick={() => setActiveView("list")}
                    className={`px-3 py-2 ${activeView === "list" ? "bg-purple-100 text-purple-700" : "bg-white text-gray-600"}`}
                  >
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      width="20"
                      height="20"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      strokeWidth="2"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                    >
                      <line x1="8" y1="6" x2="21" y2="6"></line>
                      <line x1="8" y1="12" x2="21" y2="12"></line>
                      <line x1="8" y1="18" x2="21" y2="18"></line>
                      <line x1="3" y1="6" x2="3.01" y2="6"></line>
                      <line x1="3" y1="12" x2="3.01" y2="12"></line>
                      <line x1="3" y1="18" x2="3.01" y2="18"></line>
                    </svg>
                  </button>
                </div>
              </div>

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

            {/* Active Filters */}
            {(searchQuery ||
              selectedCategory !== "all" ||
              selectedTags.length > 0 ||
              priceRange[0] > 0 ||
              priceRange[1] < 300) && (
                <div className="flex  sm:flex-row flex-col 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>

                  {searchQuery && (
                    <div className="bg-white px-3 py-1.5 rounded-full text-sm flex items-center shadow-sm border border-gray-100">
                      <span className="text-gray-600">
                        Zoekterm: <span className="font-medium">{searchQuery}</span>
                      </span>
                      <button onClick={() => setSearchQuery("")} className="ml-2 text-gray-400 hover:text-gray-600">
                        <X size={14} />
                      </button>
                    </div>
                  )}

                  {selectedCategory !== "all" && (
                    <div className="bg-white px-3 py-1.5 rounded-full text-sm flex items-center shadow-sm border border-gray-100">
                      <span className="text-gray-600">
                        Categorie: <span className="font-medium">{selectedCategory}</span>
                      </span>
                      <button
                        onClick={() => setSelectedCategory("all")}
                        className="ml-2 text-gray-400 hover:text-gray-600"
                      >
                        <X size={14} />
                      </button>
                    </div>
                  )}

                  {(priceRange[0] > 0 || priceRange[1] < 300) && (
                    <div className="bg-white px-3 py-1.5 rounded-full text-sm flex items-center shadow-sm border border-gray-100">
                      <span className="text-gray-600">
                        Prijs:{" "}
                        <span className="font-medium">
                          €{priceRange[0]} - €{priceRange[1]}
                        </span>
                      </span>
                      <button onClick={() => setPriceRange([0, 300])} className="ml-2 text-gray-400 hover:text-gray-600">
                        <X size={14} />
                      </button>
                    </div>
                  )}

                  {selectedTags.map((tag) => (
                    <div
                      key={tag}
                      className="bg-white px-3 py-1.5 rounded-full text-sm flex items-center shadow-sm border border-gray-100"
                    >
                      <span className="text-gray-600">
                        Tag: <span className="font-medium">{tag}</span>
                      </span>
                      <button onClick={() => toggleTag(tag)} className="ml-2 text-gray-400 hover:text-gray-600">
                        <X size={14} />
                      </button>
                    </div>
                  ))}

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

            {/* Loading State */}
            {isLoading ? (
              <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-md 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>
            ) : (
              <>
                {filteredProducts.length === 0 ? (
                  <div className="bg-white rounded-2xl shadow-md p-8 text-center">
                    <div className="mb-4 text-gray-400">
                      <Search size={48} className="mx-auto" />
                    </div>
                    <h3 className="text-xl font-semibold mb-2">Geen producten gevonden</h3>
                    <p className="text-gray-600 mb-4">
                      We konden geen producten vinden die overeenkomen met je zoekcriteria.
                    </p>
                    <button onClick={resetFilters} className="text-purple-600 font-medium hover:underline">
                      Reset alle filters
                    </button>
                  </div>
                ) : (
                  <>
                    {/* Grid View */}
                    {activeView === "grid" && (
                      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
                        {filteredProducts.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-500 border border-gray-100 hover:border-purple-200 relative"
                            style={{ animationDelay: `${index * 0.05}s` }}
                          >

                            {/* 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>

                            {/* Product image */}
                            <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"
                                />
                              </div>
                            </Link>

                            {/* Product info */}
                            <div className="p-5">
                              <div className="mb-2">
                                <span className="text-xs font-medium text-purple-600 bg-purple-50 px-2 py-1 rounded-full">
                                  {product.category}
                                </span>
                              </div>

                              <Link href={`/product/${product.slug}`}>
                                <h3 className="font-semibold text-lg mb-1 text-gray-800 group-hover:text-purple-700 transition-colors duration-300 line-clamp-2 h-14">
                                  {product.name}
                                </h3>
                              </Link>

                              {/* Price and Add to Cart */}
                              <div className="flex flex-col gap-4 mt-4">
                                <div>
                                  {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="font-bold text-lg text-purple-700">
                                        €{product.price.toFixed(2)}
                                      </span>
                                    </div>
                                  ) : (
                                    <span className="font-bold text-lg text-purple-700">
                                      €{product.price.toFixed(2)}
                                    </span>
                                  )}
                                </div>

                                <AddToCartButton
                                  id={product?.id}
                                  name={product?.name}
                                  price={product?.price}
                                  image={product?.image}
                                  className="bg-purple-600 hover:bg-purple-700 text-white p-2 rounded-full shadow-md transition-colors"
                                >
                                </AddToCartButton>
                              </div>

                              {/* Stock indicator */}
                              <div className="mt-3 flex items-center">
                                <div
                                  className={`h-2 w-2 rounded-full mr-2 bg-green-500`}
                                ></div>
                                <span className="text-xs text-gray-500">
                                  Op voorraad
                                </span>
                              </div>
                            </div>
                          </div>
                        ))}
                      </div>
                    )}

                    {/* List View */}
                    {activeView === "list" && (
                      <div className="space-y-6">
                        {filteredProducts.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-500 border border-gray-100 hover:border-purple-200 relative flex flex-col md:flex-row"
                            style={{ animationDelay: `${index * 0.05}s` }}
                          >
                            {/* Discount badge */}
                            {product.originalPrice && product.originalPrice > product.price && (
                              <div className="absolute top-4 left-4 z-10 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>
                            )}

                            {/* Product image */}
                            <Link href={`/product/${product.slug}`} className="md:w-1/4 flex-shrink-0">
                              <div className="relative h-56 md:h-full 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, 25vw"
                                  className="object-contain p-4 z-10 transform group-hover:scale-110 transition-transform duration-500"
                                />
                              </div>
                            </Link>

                            {/* Product info */}
                            <div className="p-5 flex-1 flex flex-col">
                              <div className="mb-2">
                                <span className="text-xs font-medium text-purple-600 bg-purple-50 px-2 py-1 rounded-full">
                                  {product.category}
                                </span>
                                {product.stock < 30 && (
                                  <span className="ml-2 text-xs font-medium text-amber-600 bg-amber-50 px-2 py-1 rounded-full">
                                    Nog {product.stock} op voorraad
                                  </span>
                                )}
                              </div>

                              <Link href={`/product/${product.slug}`}>
                                <h3 className="font-semibold text-xl mb-2 text-gray-800 group-hover:text-purple-700 transition-colors duration-300">
                                  {product.name}
                                </h3>
                              </Link>

                              {/* Rating */}
                              <div className="flex items-center mb-3">
                                <div className="flex items-center text-amber-400">
                                  <Star size={16} fill="#F59E0B" />
                                  <Star size={16} fill="#F59E0B" />
                                  <Star size={16} fill="#F59E0B" />
                                  <Star size={16} fill="#F59E0B" />
                                  <Star size={16} fill="#F59E0B" className="text-gray-300" strokeWidth={0} />
                                </div>
                                <span className="text-xs text-gray-500 ml-1">(4.8)</span>
                              </div>

                              {/* Short description */}
                              <div className="text-sm text-gray-600 mb-4 flex-grow">
                                {product.shortDescription ? (
                                  <div dangerouslySetInnerHTML={{ __html: product.shortDescription }} />
                                ) : (
                                  <p>
                                    Een hoogwaardige medicatie voor optimale resultaten. Bestel nu voor snelle levering.
                                  </p>
                                )}
                              </div>

                              {/* Price and Add to Cart */}
                              <div className="flex items-center justify-between mt-auto">
                                <div>
                                  {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="font-bold text-2xl text-purple-700">
                                        €{product.price.toFixed(2)}
                                      </span>
                                    </div>
                                  ) : (
                                    <span className="font-bold text-2xl text-purple-700">
                                      €{product.price.toFixed(2)}
                                    </span>
                                  )}
                                </div>

                                <div className="flex gap-3">
                                  <button className="p-2 rounded-full border border-gray-200 hover:bg-gray-50 transition-colors">
                                    <Heart size={20} className="text-gray-600" />
                                  </button>
                                  <AddToCartButton
                                    id={product?.id}
                                    name={product?.name}
                                    price={product?.price}
                                    image={product?.image}
                                    className="bg-purple-600 hover:bg-purple-700 text-white px-4 py-2 rounded-lg shadow-md transition-colors flex items-center gap-2"
                                  >
                                    <ShoppingCart size={18} />
                                    <span>In winkelwagen</span>
                                  </AddToCartButton>
                                </div>
                              </div>
                            </div>
                          </div>
                        ))}
                      </div>
                    )}

                    {/* Load More Button */}
                    {filteredProducts.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>
  )
}
