'use client';

import { useState, useEffect, useMemo } from 'react';
import { ShoppingCart, Search, Menu, X, ArrowRight, Heart, MessageCircle, Minus, Plus } from 'lucide-react';
import Link from 'next/link';
import Image from 'next/image';
import { useRouter } from 'next/navigation';
import { fetchCategories } from '@/lib/services/categories';
import { fetchProducts } from '@/lib/services/products';
import type { FrontendCategory, FrontendProductSummary } from '@/lib/types';
import { useCart } from '../context/CartContext';
import { useSettings } from '../context/SettingsContext';
import { useCurrency, ensureSupportedCurrency, type SupportedCurrency } from '../context/CurrencyContext';
import { WHATSAPP_DISPLAY, WHATSAPP_URL } from '@/lib/config/whatsapp';

export default function Header() {
  const [isMenuOpen, setIsMenuOpen] = useState(false);
  const router = useRouter();
  const { cartItems, getCartCount, updateQuantity, removeFromCart } = useCart();
  const cartCount = getCartCount();
  const [showTopBar, setShowTopBar] = useState(true);
  const [isSearchOpen, setIsSearchOpen] = useState(false);
  const [isCartOpen, setIsCartOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [searchResults, setSearchResults] = useState<FrontendProductSummary[]>([]);
  const [isSearching, setIsSearching] = useState(false);
  const [hasSearched, setHasSearched] = useState(false);
  const [menuCategories, setMenuCategories] = useState<FrontendCategory[]>([]);
  const [isLoadingCategories, setIsLoadingCategories] = useState(true);
  const { selectedCurrency, setSelectedCurrency, availableCurrencies, formatCurrency, convertPrice } = useCurrency();
  const settings = useSettings();

  useEffect(() => {
    let ticking = false;

    const handleScroll = () => {
      if (!ticking) {
        window.requestAnimationFrame(() => {
          const scrollPosition = window.scrollY;
          const scrollThreshold = 50; // Change this value to adjust when top bar hides

          const newShowTopBar = scrollPosition <= scrollThreshold;

          setShowTopBar((prev) => {
            if (prev !== newShowTopBar) {
              return newShowTopBar;
            }
            return prev;
          });

          ticking = false;
        });
        ticking = true;
      }
    };

    window.addEventListener('scroll', handleScroll, { passive: true });
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  useEffect(() => {
    let isMounted = true;

    async function loadCategories() {
      try {
        const data = await fetchCategories();
        if (isMounted) {
          setMenuCategories(data);
        }
      } catch (error) {
        console.error('Failed to load categories', error);
      } finally {
        if (isMounted) {
          setIsLoadingCategories(false);
        }
      }
    }

    void loadCategories();

    return () => {
      isMounted = false;
    };
  }, []);

  // Prevent body scroll when search or cart is open
  useEffect(() => {
    if (isSearchOpen || isCartOpen) {
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = 'unset';
    }
    return () => {
      document.body.style.overflow = 'unset';
    };
  }, [isSearchOpen, isCartOpen]);

  // Reset search state when closing search drawer
  useEffect(() => {
    if (!isSearchOpen) {
      setSearchQuery('');
      setSearchResults([]);
      setIsSearching(false);
      setHasSearched(false);
    }
  }, [isSearchOpen]);

  // Fetch search results when the query changes
  useEffect(() => {
    const trimmedQuery = searchQuery.trim();

    if (!isSearchOpen) {
      return;
    }

    if (trimmedQuery.length < 2) {
      setSearchResults([]);
      setIsSearching(false);
      setHasSearched(false);
      return;
    }

    let isActive = true;
    setIsSearching(true);

    fetchProducts({ search: trimmedQuery })
      .then((results) => {
        if (!isActive) return;
        setSearchResults(results.slice(0, 12));
        setHasSearched(true);
      })
      .catch((error) => {
        if (!isActive) return;
        console.error('Product search failed', error);
        setSearchResults([]);
        setHasSearched(true);
      })
      .finally(() => {
        if (isActive) {
          setIsSearching(false);
        }
      });

    return () => {
      isActive = false;
    };
  }, [searchQuery, isSearchOpen]);

  const mainMenuItems = menuCategories.length > 0 ? menuCategories : [];
  const siteName = settings.siteName || 'Bakht Apparel';

  const cartSubtotal = useMemo(() => {
    return cartItems.reduce((total, item) => {
      const currency = ensureSupportedCurrency(item.product.currency);
      return total + convertPrice(item.price, currency);
    }, 0);
  }, [cartItems, convertPrice]);

  const trimmedSearchQuery = searchQuery.trim();

  return (
    <>
      {/* Spacer to account for fixed header height */}
      <div className={`transition-all duration-300 ${showTopBar ? 'h-[100px]' : 'h-20'}`} />
      <header className="fixed top-0 left-0 right-0 z-50 bg-white shadow-sm">
      {/* Top Bar */}
      <div 
        className={`border-b border-gray-200 bg-gray-50 overflow-hidden transition-all duration-300 ease-in-out ${
          showTopBar ? 'max-h-20 opacity-100 translate-y-0' : 'max-h-0 opacity-0 -translate-y-full'
        }`}
      >
        <div className="container mx-auto px-4 py-2">
          <div className="flex items-center justify-between text-sm">
            <div className="flex items-center gap-3 mx-auto lg:mx-0">
              <span className="text-gray-600">Call/Whatsapp us at</span>
              <a
                href={WHATSAPP_URL}
                target="_blank"
                rel="noopener noreferrer"
                className="font-semibold text-gray-900 hover:text-gray-700"
              >
                {WHATSAPP_DISPLAY}
              </a>
            </div>
          </div>
        </div>
      </div>

      {/* Main Header */}
      <div className="container mx-auto px-4">
        <div className="flex items-center justify-between h-20">
          {/* Logo */}
          <Link href="/" className="flex items-center">
            <Image
              src="/assets/logos/Untitled-1-02.png"
              alt={siteName}
              width={140}
              height={60}
              className="h-5 md:h-10 w-auto object-contain"
              priority
              quality={90}
            />
            <span className="sr-only">{siteName}</span>
          </Link>

          {/* Desktop Navigation */}
          <nav className="hidden lg:flex flex-wrap items-center text-center justify-center" style={{ lineHeight: '1.9' }}>
            <div className="relative group mx-2">
              <Link
                href="/"
                className="text-sm font-normal text-black uppercase transition-colors"
              >
                Home
              </Link>
            </div>
            {mainMenuItems.map((category) => (
              <div key={category.id} className="relative group mx-2">
                <Link
                  href={`/${category.slug}`}
                  className="text-sm font-normal text-black uppercase transition-colors"
                >
                  {category.name}
                </Link>
              </div>
            ))}
            {isLoadingCategories && (
              <span className="text-xs text-gray-400 italic">Loading categories...</span>
            )}
          </nav>

          {/* Right Side Actions */}
          <div className="flex items-center gap-2 sm:gap-4">
            {/* Currency Dropdown - First */}
            <select
              value={selectedCurrency}
              onChange={(e) => setSelectedCurrency(e.target.value as SupportedCurrency)}
              className="hidden lg:block bg-transparent border-none text-sm font-medium cursor-pointer focus:outline-none text-gray-700 hover:text-gray-900 transition-colors"
            >
              {availableCurrencies.map((curr) => (
                <option key={curr} value={curr}>
                  {curr}
                </option>
              ))}
            </select>
            {/* Icons - Hide when search or cart is open */}
            {!isSearchOpen && !isCartOpen && (
              <>
                <button
                  onClick={() => setIsSearchOpen(true)}
                  className="p-2 sm:p-2 hover:bg-gray-100 rounded-full transition-colors"
                >
                  <Search className="w-5 h-5 text-gray-700" />
                </button>
                <button
                  onClick={() => setIsCartOpen(true)}
                  className="relative p-2 sm:p-2 hover:bg-gray-100 rounded-full transition-colors"
                >
                  <ShoppingCart className="w-5 h-5 text-gray-700" />
                  {cartCount > 0 && (
                    <span className="absolute top-0 right-0 bg-black text-white text-xs rounded-full w-5 h-5 flex items-center justify-center">
                      {cartCount}
                    </span>
                  )}
                </button>
                {/* Currency Dropdown - Mobile only, after cart */}
                <select
                  value={selectedCurrency}
                  onChange={(e) => setSelectedCurrency(e.target.value as SupportedCurrency)}
                  className="lg:hidden bg-transparent border-none text-sm font-medium cursor-pointer focus:outline-none text-gray-700 hover:text-gray-900 transition-colors"
                >
                  {availableCurrencies.map((curr) => (
                    <option key={curr} value={curr}>
                      {curr}
                    </option>
                  ))}
                </select>
              </>
            )}
            <button
              className="lg:hidden p-2 hover:bg-gray-100 rounded-full transition-colors"
              onClick={() => setIsMenuOpen(!isMenuOpen)}
            >
              {isMenuOpen ? (
                <X className="w-5 h-5 text-gray-700" />
              ) : (
                <Menu className="w-5 h-5 text-gray-700" />
              )}
            </button>
          </div>
        </div>
      </div>

      {/* Mobile Menu */}
      {isMenuOpen && (
        <div className="lg:hidden border-t border-gray-200 bg-white">
          <nav className="container mx-auto px-4 py-4">
            <div className="flex flex-col gap-4">
              <Link
                href="/"
                className="text-sm font-medium text-gray-700 hover:text-gray-900"
                onClick={() => setIsMenuOpen(false)}
              >
                Home
              </Link>
              {mainMenuItems.map((category) => (
                <Link
                  key={category.id}
                  href={`/${category.slug}`}
                  className="text-sm font-medium text-gray-700 hover:text-gray-900"
                  onClick={() => setIsMenuOpen(false)}
                >
                  {category.name}
                </Link>
              ))}
            </div>
          </nav>
        </div>
      )}

      {/* Search Side Sheet */}
      <>
        {/* Backdrop/Shade */}
        <div
          className={`fixed inset-0 bg-white/50 z-50 transition-opacity duration-300 ${
            isSearchOpen ? 'opacity-100' : 'opacity-0 pointer-events-none'
          }`}
          onClick={() => setIsSearchOpen(false)}
        />
        
        {/* Search Panel */}
        <div className={`fixed right-0 top-0 h-full w-full max-w-md bg-white z-50 shadow-2xl transform transition-transform duration-300 ease-in-out ${
          isSearchOpen ? 'translate-x-0' : 'translate-x-full'
        }`}>
            <div className="h-full flex flex-col">
              {/* Icons Row - Moved from Header */}
              <div className="flex items-center justify-end gap-2 p-4 border-b border-gray-200">
                <a 
                  href={WHATSAPP_URL}
                  target="_blank" 
                  rel="noopener noreferrer"
                  className="p-2 hover:bg-gray-100 rounded-full transition-colors"
                >
                  <MessageCircle className="w-5 h-5 text-gray-700" />
                </a>
                <button 
                  onClick={() => setIsSearchOpen(true)}
                  className="p-2 hover:bg-gray-100 rounded-full transition-colors"
                >
                  <Search className="w-5 h-5 text-gray-700" />
                </button>
                <Link href="/wishlist" className="p-2 hover:bg-gray-100 rounded-full transition-colors">
                  <Heart className="w-5 h-5 text-gray-700" />
                </Link>
                <button 
                  onClick={() => setIsCartOpen(true)}
                  className="relative p-2 hover:bg-gray-100 rounded-full transition-colors"
                >
                  <ShoppingCart className="w-5 h-5 text-gray-700" />
                  {cartCount > 0 && (
                    <span className="absolute top-0 right-0 bg-black text-white text-xs rounded-full w-5 h-5 flex items-center justify-center">
                      {cartCount}
                    </span>
                  )}
                </button>
              </div>

              {/* Close Button and Search Header */}
              <div className="flex items-center justify-between p-6 ">
              <h2 className="text-md font-semibold text-gray-900">Search</h2>
                <button
                  onClick={() => setIsSearchOpen(false)}
                  className="p-2 hover:bg-gray-100 rounded-full transition-colors"
                >
                  <X className="w-6 h-6 text-gray-700" />
                </button>
                
                
              </div>

              {/* Search Input */}
              <div className="p-6">
                <form
                  onSubmit={(e) => {
                    e.preventDefault();
                    const topResult = searchResults[0];
                    if (topResult?.slug) {
                      router.push(`/products/${topResult.slug}`);
                      setIsSearchOpen(false);
                    }
                  }}
                  className="relative"
                >
                  <input
                    type="text"
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    placeholder="Search store"
                    className="w-full text-lg border-0 border-b-2 border-gray-300 focus:border-gray-900 focus:outline-none pb-2 pr-10"
                    autoFocus
                  />
                  <button
                    type="submit"
                    className="absolute right-0 top-0 p-2 hover:opacity-70 transition-opacity"
                  >
                    <ArrowRight className="w-5 h-5 text-gray-700" />
                  </button>
                </form>
              </div>

              {/* Search Results */}
              <div className="px-6 pb-6 flex-1 overflow-y-auto">
                {trimmedSearchQuery.length < 2 ? (
                  <p className="text-sm text-gray-500">
                    Type at least two characters to search products by name, collection, or price.
                  </p>
                ) : isSearching ? (
                  <p className="text-sm text-gray-500">Searching&hellip;</p>
                ) : hasSearched && searchResults.length === 0 ? (
                  <p className="text-sm text-gray-500">No products match “{trimmedSearchQuery}”.</p>
                ) : (
                  <ul className="space-y-4">
                    {searchResults.map((product) => {
                      const href = product.slug ? `/products/${product.slug}` : `/products/${product.id}`;
                      const priceLabel = formatCurrency(product.price, {
                        fromCurrency: ensureSupportedCurrency(product.currency),
                      });
                      const categoryLabel = product.primaryCategory
                        ? product.primaryCategory.replace(/-/g, ' ').toUpperCase()
                        : product.categories[0]?.replace(/-/g, ' ').toUpperCase() ?? 'UNCLASSIFIED';

                      return (
                        <li key={product.slug ?? product.id}>
                          <Link
                            href={href}
                            className="flex gap-4 group"
                            onClick={() => setIsSearchOpen(false)}
                          >
                            <div className="relative w-20 h-28 shrink-0 overflow-hidden rounded border border-gray-100 bg-gray-50">
                              <Image
                                src={product.image}
                                alt={product.name}
                                fill
                                className="object-cover transition-transform duration-300 group-hover:scale-105"
                                sizes="80px"
                                loading="lazy"
                                quality={75}
                              />
                            </div>
                            <div className="flex-1 min-w-0">
                              <div className="flex items-center justify-between gap-3">
                                <h3 className="text-sm font-semibold text-gray-900 line-clamp-1">
                                  {product.name}
                                </h3>
                                <span className="text-sm font-medium text-gray-900 whitespace-nowrap">
                                  {priceLabel}
                                </span>
                              </div>
                              <p className="text-xs uppercase tracking-wide text-gray-500 mt-1">
                                {categoryLabel}
                              </p>
                              {product.shortDescription && (
                                <p className="text-xs text-gray-600 mt-2 line-clamp-2">
                                  {product.shortDescription}
                                </p>
                              )}
                              <span className="inline-flex items-center gap-1 text-xs text-gray-700 mt-3 group-hover:text-black transition-colors">
                                View product <ArrowRight className="w-3 h-3" />
                              </span>
                            </div>
                          </Link>
                        </li>
                      );
                    })}
                  </ul>
                )}
              </div>
            </div>
          </div>
      </>

      {/* Cart Side Sheet */}
      <>
        {/* Backdrop/Shade */}
        <div
          className={`fixed inset-0 bg-white/50 z-50 transition-opacity duration-300 ${
            isCartOpen ? 'opacity-100' : 'opacity-0 pointer-events-none'
          }`}
          onClick={() => setIsCartOpen(false)}
        />
        
        {/* Cart Panel */}
        <div className={`fixed right-0 top-0 h-full w-full max-w-md bg-white z-50 shadow-2xl transform transition-transform duration-300 ease-in-out ${
          isCartOpen ? 'translate-x-0' : 'translate-x-full'
        }`}>
          <div className="h-full flex flex-col">
            {/* Header */}
            <div className="flex items-center justify-between p-6 border-b border-gray-200">
              <div className=" text-center">
                <h2 className="text-sm font-medium text-gray-900">
                  There are {cartCount} item{cartCount !== 1 ? 's' : ''} in your cart.
                </h2>
              </div>
              <button
                onClick={() => setIsCartOpen(false)}
                className="p-2 hover:bg-gray-100 rounded-full transition-colors shrink-0"
              >
                <X className="w-5 h-5 text-black" />
              </button>
            </div>

            {/* Cart Items */}
            <div className="flex-1 overflow-y-auto">
              {cartItems.length === 0 ? (
                <div className="flex flex-col items-center justify-center h-full p-6 text-center">
                  <ShoppingCart className="w-16 h-16 text-gray-300 mb-4" />
                  <p className="text-gray-600 text-lg">Your cart is empty</p>
                  <Link 
                    href="/"
                    onClick={() => setIsCartOpen(false)}
                    className="mt-4 text-black hover:underline"
                  >
                    Continue Shopping
                  </Link>
                </div>
              ) : (
                <div className="p-6 space-y-6">
                  {cartItems.map((item) => {
                    // Calculate price per item (before quantity)
                    const pricePerItem = item.price / item.quantity;
                    const productCurrency = ensureSupportedCurrency(item.product.currency);
                    const fabricName = item.fabric === 'velvet' ? 'Velvet (As Shown)' : 
                                      item.fabric === 'pure-silk' ? 'Pure Raw Silk' : 
                                      item.fabric === 'korean-silk' ? 'Korean Raw Silk' : item.fabric;
                    
                    const dupattaNames: { [key: string]: string } = {
                      'plain-silk': 'Plain Medium Silk Dupatta',
                      'plain-organza': 'Plain Organza Dupatta',
                      'silk-sequin': 'Medium Silk Dupatta with Sequence Spray',
                      'organza-sequin': 'Organza Dupatta with Sequence Spray',
                    };
                    
                    const trouserNames: { [key: string]: string } = {
                      'satin': 'Satin Pants (As Shown)',
                      'korean-silk': 'Korean Raw Silk Pants',
                      'velvet': 'Velvet Pants',
                    };
                    
                    return (
                      <div key={item.id} className="flex gap-4 pb-6 border-b border-gray-200 last:border-0">
                        {/* Product Image */}
                        <div className="relative w-20 h-28 shrink-0 bg-gray-100">
                          <Image
                            src={item.product.image}
                            alt={item.product.name}
                            fill
                            className="object-cover"
                            sizes="80px"
                            loading="lazy"
                            quality={75}
                          />
                        </div>

                        {/* Product Details */}
                        <div className="flex-1 min-w-0">
                          <h3 className="text-sm font-semibold text-gray-900 mb-2">
                            {item.product.name}
                          </h3>
                          <div className="text-xs text-gray-600 space-y-1 mb-3">
                            <div>Size: {item.size}</div>
                            <div>Fabric Option: {fabricName}</div>
                            {item.dupatta && (
                              <div>Dupatta: {dupattaNames[item.dupatta] || item.dupatta}</div>
                            )}
                            {item.trousers && (
                              <div>Trousers: {trouserNames[item.trousers] || item.trousers}</div>
                            )}
                            {item.silkScarf && (
                              <div>Silk Scarf: Yes</div>
                            )}
                          </div>
                          <div className="text-sm font-semibold text-gray-900 mb-3">
                            {formatCurrency(pricePerItem, { fromCurrency: productCurrency })}
                          </div>

                          {/* Quantity Controls */}
                          <div className="flex items-center border border-gray-300 rounded-full overflow-hidden w-fit ">
                            <button
                              onClick={() => {
                                const newQuantity = item.quantity - 1;
                                if (newQuantity > 0) {
                                  updateQuantity(item.id, newQuantity);
                                } else {
                                  removeFromCart(item.id);
                                }
                              }}
                              className="w-9 h-7 flex items-center justify-center bg-white hover:bg-gray-50 transition-colors text-gray-900 border-r border-gray-300"
                              type="button"
                            >
                              <Minus className="w-3.5 h-3.5" strokeWidth={2.5} />
                            </button>
                            <span className="w-9 h-7 flex items-center justify-center bg-white text-sm font-medium text-gray-900 border-r border-gray-300">
                              {item.quantity}
                            </span>
                            <button
                              onClick={() => {
                                const newQuantity = item.quantity + 1;
                                updateQuantity(item.id, newQuantity);
                              }}
                              className="w-9 h-7 flex items-center justify-center bg-white hover:bg-gray-50 transition-colors text-gray-900"
                              type="button"
                            >
                              <Plus className="w-3.5 h-3.5" strokeWidth={2.5} />
                            </button>
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              )}
               {cartItems.length > 0 && (
              <div className="border-t border-gray-200 p-6 space-y-3">
                <div className="flex justify-between items-center">
                  <span className="text-sm font-semibold text-gray-900">SUB-TOTAL:</span>
                  <span className="text-base font-semibold text-gray-900 uppercase">
                    {formatCurrency(cartSubtotal, { fromCurrency: selectedCurrency })}
                  </span>
                </div>
                <p className="text-xs text-gray-600">Shipping is added at checkout</p>
                <Link
                  href="/cart"
                  onClick={() => setIsCartOpen(false)}
                  className="block w-full bg-linear-to-b from-gray-800 to-black text-white text-center py-3 text-sm font-semibold hover:from-gray-900 hover:to-gray-950 transition-all uppercase tracking-wide rounded-sm"
                >
                  GO TO CART
                </Link>
              </div>
            )}
            </div>

            {/* Cart Summary */}
           
          </div>
        </div>
      </>
    </header>
    </>
  );
}

