"use client"

import Link from "next/link"
import { Heart, Menu, Search, ShoppingBag, X } from "lucide-react"
import { useState, useEffect } from "react"
import { useCart } from "@/hooks/use-cart"
import { useWishlist } from "@/hooks/use-wishlist"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Sheet, SheetContent, SheetTrigger } from "@/components/ui/sheet"
import { useMediaQuery } from "@/hooks/use-media-query"

export function SiteHeader() {
  const [isMenuOpen, setIsMenuOpen] = useState(false)
  const [isSearchOpen, setIsSearchOpen] = useState(false)
  const [searchQuery, setSearchQuery] = useState("")
  const [isScrolled, setIsScrolled] = useState(false)
  
  const { itemCount: cartCount } = useCart()
  const { itemCount: wishlistCount } = useWishlist()
  
  const isMobile = useMediaQuery("(max-width: 768px)")

  // Отслеживаем скролл для изменения стиля хедера
  useEffect(() => {
    const handleScroll = () => {
      const scrollPosition = window.scrollY
      setIsScrolled(scrollPosition > 50)
    }

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

  const handleSearchSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    // Перенаправляем на страницу каталога с поисковым запросом
    if (searchQuery.trim()) {
      window.location.href = `/catalog?search=${encodeURIComponent(searchQuery)}`
    }
    setIsSearchOpen(false) // Закрываем поиск после отправки
  }

  const toggleSearch = () => {
    setIsSearchOpen(!isSearchOpen)
    if (!isSearchOpen) {
      // Фокусируем поле ввода поиска, когда оно открыто
      setTimeout(() => {
        const searchInput = document.getElementById("search-input")
        if (searchInput) searchInput.focus()
      }, 10)
    }
  }

  return (
    <header className={cn(
      "sticky top-0 z-40 w-full transition-all duration-200",
      isScrolled 
        ? "bg-primary shadow-md py-2" 
        : "bg-tertiary/30 backdrop-blur-sm py-4"
    )}>
      <div className="container flex items-center justify-between">
        {/* Логотип - укороченный для мобильных */}
        <Link href="/" className={cn(
          "font-semibold text-base sm:text-xl flex-shrink-0 truncate max-w-[140px] sm:max-w-none",
          isScrolled ? "text-white" : "text-primary"
        )}>
          {isMobile ? "О.Д.У." : "ОДЕЖДА ДЛЯ УСПЕХА"}
        </Link>

        {/* Десктоп навигация */}
        <nav className="hidden md:flex items-center space-x-8">
          <Link 
            href="/catalog" 
            className={cn(
              "text-sm font-medium transition-colors",
              isScrolled ? "text-white hover:text-tertiary" : "text-primary hover:text-secondary"
            )}
          >
            КАТАЛОГ
          </Link>
          <Link 
            href="/collections" 
            className={cn(
              "text-sm font-medium transition-colors",
              isScrolled ? "text-white hover:text-tertiary" : "text-primary hover:text-secondary"
            )}
          >
            КОЛЛЕКЦИИ
          </Link>
          <Link 
            href="/about" 
            className={cn(
              "text-sm font-medium transition-colors",
              isScrolled ? "text-white hover:text-tertiary" : "text-primary hover:text-secondary"
            )}
          >
            О НАС
          </Link>
          <Link 
            href="/blog" 
            className={cn(
              "text-sm font-medium transition-colors",
              isScrolled ? "text-white hover:text-tertiary" : "text-primary hover:text-secondary"
            )}
          >
            БЛОГ
          </Link>
        </nav>

        {/* Иконки и мобильное меню */}
        <div className="flex items-center space-x-2 sm:space-x-4">
          {/* Поиск */}
          <div className="relative">
            <Button
              variant="ghost"
              size="icon"
              aria-label="Поиск"
              className={cn(
                "h-8 w-8 sm:h-10 sm:w-10",
                isScrolled ? "text-white hover:text-tertiary" : "text-primary hover:text-secondary"
              )}
              onClick={toggleSearch}
            >
              {isSearchOpen ? <X className="h-4 w-4 sm:h-5 sm:w-5" /> : <Search className="h-4 w-4 sm:h-5 sm:w-5" />}
              <span className="sr-only">Поиск</span>
            </Button>
            
            {isSearchOpen && (
              <div className="absolute right-0 top-full mt-2 bg-white shadow-lg rounded-md p-2 w-[250px] sm:w-[300px] z-50">
                <form onSubmit={handleSearchSubmit} className="flex items-center">
                  <input
                    id="search-input"
                    type="text"
                    placeholder="Поиск товаров..."
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    className="flex-1 py-1 sm:py-2 px-2 sm:px-3 text-sm border border-gray-200 rounded-l-md focus:outline-none"
                  />
                  <Button
                    type="submit"
                    variant="default"
                    className="rounded-l-none h-8 sm:h-10"
                    size="sm"
                  >
                    <Search className="h-3 w-3 sm:h-4 sm:w-4" />
                  </Button>
                </form>
              </div>
            )}
          </div>
          
          {/* Избранное - только десктоп и планшет */}
          <div className="hidden sm:block">
            <Link href="/wishlist" prefetch={false}>
              <Button 
                variant="ghost" 
                size="icon" 
                aria-label="Избранное" 
                className={cn(
                  "relative h-8 w-8 sm:h-10 sm:w-10",
                  isScrolled ? "text-white hover:text-tertiary" : "text-primary hover:text-secondary"
                )}
              >
                <Heart className="h-4 w-4 sm:h-5 sm:w-5" />
                <span className="sr-only">Избранное</span>
                {wishlistCount > 0 && (
                  <span className="absolute -top-1 -right-1 bg-tertiary text-primary text-xs rounded-full w-4 h-4 sm:w-5 sm:h-5 flex items-center justify-center">
                    {wishlistCount}
                  </span>
                )}
              </Button>
            </Link>
          </div>
          
          {/* Корзина */}
          <Link href="/cart" prefetch={false}>
            <Button 
              variant="ghost" 
              size="icon" 
              aria-label="Корзина" 
              className={cn(
                "relative h-8 w-8 sm:h-10 sm:w-10",
                isScrolled ? "text-white hover:text-tertiary" : "text-primary hover:text-secondary"
              )}
            >
              <ShoppingBag className="h-4 w-4 sm:h-5 sm:w-5" />
              <span className="sr-only">Корзина</span>
              {cartCount > 0 && (
                <span className="absolute -top-1 -right-1 bg-tertiary text-primary text-xs rounded-full w-4 h-4 sm:w-5 sm:h-5 flex items-center justify-center">
                  {cartCount}
                </span>
              )}
            </Button>
          </Link>
          
          {/* Мобильное меню */}
          <Sheet>
            <SheetTrigger asChild>
              <Button
                variant="ghost"
                size="icon"
                aria-label="Меню"
                className={cn(
                  "md:hidden h-8 w-8 sm:h-10 sm:w-10",
                  isScrolled ? "text-white hover:text-tertiary" : "text-primary hover:text-secondary"
                )}
              >
                <Menu className="h-4 w-4 sm:h-5 sm:w-5" />
                <span className="sr-only">Меню</span>
              </Button>
            </SheetTrigger>
            <SheetContent side="right" className="w-[250px] sm:w-[300px]">
              <nav className="flex flex-col space-y-4 mt-8">
                <Link
                  href="/catalog"
                  className="text-base font-medium py-2 hover:text-primary transition-colors"
                >
                  КАТАЛОГ
                </Link>
                <Link
                  href="/collections"
                  className="text-base font-medium py-2 hover:text-primary transition-colors"
                >
                  КОЛЛЕКЦИИ
                </Link>
                <Link
                  href="/about"
                  className="text-base font-medium py-2 hover:text-primary transition-colors"
                >
                  О НАС
                </Link>
                <Link
                  href="/blog"
                  className="text-base font-medium py-2 hover:text-primary transition-colors"
                >
                  БЛОГ
                </Link>
                <Link
                  href="/contact"
                  className="text-base font-medium py-2 hover:text-primary transition-colors"
                >
                  КОНТАКТЫ
                </Link>
                
                {/* Избранное - в мобильном меню */}
                <Link
                  href="/wishlist"
                  className="text-base font-medium py-2 hover:text-primary transition-colors sm:hidden flex items-center"
                >
                  <Heart className="h-4 w-4 mr-2" />
                  ИЗБРАННОЕ
                  {wishlistCount > 0 && (
                    <span className="ml-2 bg-primary text-white text-xs rounded-full w-4 h-4 flex items-center justify-center">
                      {wishlistCount}
                    </span>
                  )}
                </Link>
                
                <div className="border-t pt-4 mt-4">
                  <Link
                    href="/account"
                    className="text-base font-medium py-2 hover:text-primary transition-colors"
                  >
                    ЛИЧНЫЙ КАБИНЕТ
                  </Link>
                </div>
              </nav>
            </SheetContent>
          </Sheet>
        </div>
      </div>
    </header>
  )
} 