"use client"

import { useEffect, useRef, useState } from "react"
import Link from "next/link"
import { Search, User, ShoppingBag, Menu, X } from "lucide-react"
import { useCart } from "@/context/CartContext"
import { useRouter, usePathname } from "next/navigation"
import { useAuth } from "@/context/AuthContext"

export default function Header() {
  const [isMenuOpen, setIsMenuOpen] = useState(false)
  const [isScrolled, setIsScrolled] = useState(false)
  const { cart } = useCart()
  const { user, loading } = useAuth()
  const pathname = usePathname()
  const router = useRouter()
  const menuRef = useRef(null)

  const cartTotal = cart.reduce((total, item) => total + item.price * item.quantity, 0).toFixed(2)
  const cartCount = cart.reduce((count, item) => count + item.quantity, 0)

  // Function to determine if a link is active
  const isActive = (path) => {
    return pathname === path
  }

  // Get the active class based on whether the link is active
  const getLinkClass = (path) => {
    return isActive(path)
      ? "text-[#1eaaff] font-medium relative after:content-[''] after:absolute after:bottom-[-4px] after:left-0 after:w-full after:h-[2px] after:bg-[#1eaaff]"
      : "text-gray-700 hover:text-[#1eaaff] font-medium transition-colors duration-300"
  }

  const [searchText, setSearchText] = useState("")

  const handleSearch = (e) => {
    e.preventDefault()
    if (searchText.trim()) {
      router.push(`/search?query=${encodeURIComponent(searchText)}`)
      setSearchText("")
      setIsMenuOpen(false)
    }
  }

  useEffect(() => {
    const handleClickOutside = (event) => {
      if (menuRef.current && !menuRef.current.contains(event.target)) {
        setIsMenuOpen(false)
      }
    }

    if (isMenuOpen) {
      document.addEventListener("mousedown", handleClickOutside)
    }

    return () => {
      document.removeEventListener("mousedown", handleClickOutside)
    }
  }, [isMenuOpen])

  useEffect(() => {
    const handleScroll = () => {
      if (window.scrollY > 10) {
        setIsScrolled(true)
      } else {
        setIsScrolled(false)
      }
    }

    window.addEventListener("scroll", handleScroll)
    return () => {
      window.removeEventListener("scroll", handleScroll)
    }
  }, [])

  return (
    <header
      className={`sticky top-0 z-50 transition-all duration-300 ${isScrolled ? "bg-white/90 backdrop-blur-md shadow-md" : "bg-white"}`}
    >
      <div className="container mx-auto px-4 py-4">
        <div className="flex items-center justify-between">
          {/* Logo */}
          <Link href="/" className="flex items-center">
            <div className="relative h-10 w-44">
              <span className="text-2xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-[#1eaaff] to-[#00e889]">
                Geenrecept
              </span>
            </div>
          </Link>

          {/* Search Bar - Desktop */}
          <form onSubmit={handleSearch} className="hidden md:flex flex-1 max-w-xl mx-6">
            <div className="relative w-full group">
              <input
                type="text"
                placeholder="Zoeken..."
                value={searchText}
                onChange={(e) => setSearchText(e.target.value)}
                className="w-full py-2 pl-4 pr-10 border border-gray-300 rounded-full focus:outline-none focus:ring-2 focus:ring-[#1eaaff] focus:border-transparent transition-all duration-300 bg-gray-50 group-hover:bg-white"
              />
              <button
                type="submit"
                className="absolute right-0 top-0 h-full px-3 text-gray-500 hover:text-[#1eaaff] transition-colors duration-300"
              >
                <Search size={20} />
              </button>
            </div>
          </form>

          {/* User Actions - Desktop */}
          <div className="hidden md:flex items-center space-x-6">
            {user?.role === "admin" ? (
              <Link
                href="/admin"
                className={`flex items-center text-sm font-medium ${isActive("/admin")
                  ? "text-[#1eaaff]"
                  : "text-gray-700 hover:text-[#1eaaff] transition-colors duration-300"
                  }`}
              >
                <User size={20} className="mr-1" />
                <span>Beheerpaneel</span>
              </Link>
            ) : (
              user?.role === "customer" && (
                <Link
                  href="/dashboard"
                  className={`flex items-center text-sm font-medium ${isActive("/dashboard")
                    ? "text-[#1eaaff]"
                    : "text-gray-700 hover:text-[#1eaaff] transition-colors duration-300"
                    }`}
                >
                  <User size={20} className="mr-1" />
                  <span>Mijn account</span>
                </Link>
              )
            )}

            {!user && (
              <Link
                href="/login"
                className={`flex items-center text-sm font-medium ${isActive("/login")
                  ? "text-[#1eaaff]"
                  : "text-gray-700 hover:text-[#1eaaff] transition-colors duration-300"
                  }`}
              >
                <User size={20} className="mr-1" />
                <span>Inloggen / Registreren</span>
              </Link>
            )}

            <Link
              href="/cart"
              className={`flex items-center text-sm font-medium relative ${isActive("/cart")
                ? "text-[#1eaaff]"
                : "text-gray-700 hover:text-[#1eaaff] transition-colors duration-300"
                }`}
            >
              <div className="relative">
                <ShoppingBag size={20} className="mr-1" />
                {cartCount > 0 && (
                  <span className="absolute -top-2 -right-2 bg-[#1eaaff] text-white text-xs rounded-full h-5 w-5 flex items-center justify-center animate-pulse-slow">
                    {cartCount}
                  </span>
                )}
              </div>
            </Link>
          </div>

          {/* Mobile Menu Button */}
          <div className="flex items-center gap-2 md:hidden">
            <Link
              href="/cart"
              className={`flex items-center text-[10px] font-medium relative ${isActive("/cart") ? "text-[#1eaaff]" : "text-gray-700 hover:text-[#1eaaff]"
                }`}
            >
              <div className="relative">
                <ShoppingBag size={20} className="" />
                {cartCount > 0 && (
                  <span className="absolute -top-2 -right-1 bg-[#1eaaff] text-white text-[10px] rounded-full h-4 w-4 flex items-center justify-center animate-pulse-slow">
                    {cartCount}
                  </span>
                )}
              </div>
            </Link>
            <button
              className="text-gray-700 hover:text-[#1eaaff] transition-colors duration-300"
              onClick={() => setIsMenuOpen(!isMenuOpen)}
            >
              {isMenuOpen ? <X size={24} /> : <Menu size={24} />}
            </button>
          </div>
        </div>

        {/* Mobile Search */}
        <form onSubmit={handleSearch} className="mt-4 md:hidden">
          <div className="relative w-full">
            <input
              type="text"
              placeholder="Zoeken..."
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              className="w-full py-2 pl-4 pr-10 border border-gray-300 rounded-full focus:outline-none focus:ring-2 focus:ring-[#1eaaff] focus:border-transparent bg-gray-50"
            />
            <button
              type="submit"
              className="absolute right-0 top-0 h-full px-3 text-gray-500 hover:text-[#1eaaff] transition-colors duration-300"
            >
              <Search size={20} />
            </button>
          </div>
        </form>

        {/* Mobile Menu */}
        {isMenuOpen && (
          <div ref={menuRef} className="md:hidden mt-4 pb-4 animate-fade-in">
            <nav className="flex flex-col space-y-4" onClick={() => setIsMenuOpen(false)}>
              <Link href="/shop" className={getLinkClass("/shop")}>
                Winkel
              </Link>
              <Link href="/category/medicijnen" className={getLinkClass("/medicijnen")}>
                Medicijnen
              </Link>
              <Link href="/over-ons" className={getLinkClass("/over-ons")}>
                Over ons
              </Link>
              <Link href="/faq" className={getLinkClass("/faq")}>
                Veelgestelde vragen
              </Link>
              <Link href="/blog" className={getLinkClass("/blog")}>
                Blog
              </Link>
              <Link href="/contact" className={getLinkClass("/contact")}>
                Contact
              </Link>
            </nav>
            <div className="mt-4 flex flex-col space-y-4">
              {user?.role === "admin" ? (
                <Link
                  href="/admin"
                  className={`flex items-center text-sm font-medium ${isActive("/admin") ? "text-[#1eaaff]" : "text-gray-700 hover:text-[#1eaaff]"
                    }`}
                >
                  <User size={20} className="mr-1" />
                  <span>Beheerpaneel</span>
                </Link>
              ) : (
                user?.role === "customer" && (
                  <Link
                    href="/dashboard"
                    className={`flex items-center text-sm font-medium ${isActive("/dashboard") ? "text-[#1eaaff]" : "text-gray-700 hover:text-[#1eaaff]"
                      }`}
                  >
                    <User size={20} className="mr-1" />
                    <span>Mijn account</span>
                  </Link>
                )
              )}

              {!user && (
                <Link
                  onClick={() => setIsMenuOpen(false)}
                  href="/login"
                  className={`flex items-center text-sm font-medium ${isActive("/login") ? "text-[#1eaaff]" : "text-gray-700 hover:text-[#1eaaff]"
                    }`}
                >
                  <User size={20} className="mr-1" />
                  <span>Inloggen / Registreren</span>
                </Link>
              )}
              <Link
                onClick={() => setIsMenuOpen(false)}
                href="/cart"
                className={`flex items-center ${isActive("/cart") ? "text-[#1eaaff]" : "text-gray-700 hover:text-[#1eaaff]"
                  } font-medium`}
              >
                <ShoppingBag size={20} className="mr-2" />
                <span>
                  Winkelwagen ({cartCount})
                </span>
              </Link>
            </div>
          </div>
        )}
      </div>

      {/* Navigation - Desktop */}
      <nav className="hidden md:block border-t border-gray-200">
        <div className="container mx-auto px-4">
          <ul className="flex items-center space-x-8 py-4 text-sm lg:text-base">
            <li>
              <Link href="/shop" className={`py-3 ${getLinkClass("/shop")}`}>
                Winkel
              </Link>
            </li>

            <li>
              <Link href="/category/medicijnen" className={getLinkClass("/medicijnen")}>
                Medicijnen
              </Link>
            </li>

            <li>
              <Link href="/over-ons" className={`py-3 ${getLinkClass("/over-ons")}`}>
                Over ons
              </Link>
            </li>
            <li>
              <Link href="/faq" className={`py-3 ${getLinkClass("/faq")}`}>
                Veelgestelde vragen
              </Link>
            </li>
            <li>
              <Link href="/blog" className={`py-3 ${getLinkClass("/blog")}`}>
                Blog
              </Link>
            </li>
            <li>
              <Link href="/contact" className={`py-3 ${getLinkClass("/contact")}`}>
                Contact
              </Link>
            </li>
          </ul>
        </div>
      </nav>
    </header>
  )
}
