import React, { useState, useEffect, useRef } from 'react';
import { ShoppingCart, Search, User, ShieldCheck, Menu, X, LogOut, Package, Zap, ChevronDown, Sparkles, BookOpen, Shield } from 'lucide-react';
import { useAuth } from '../context/AuthContext';
import { useCart } from '../context/CartContext';
import { toPersianDigits, formatPrice } from '../utils/formatters';
import type { Category, Product } from '../types';
import { api } from '../services/api';
import wireguardMark from '../assets/images/wireguard-zana-mark.svg';

interface HeaderProps {
  currentView: string;
  onNavigate: (view: string, data?: any) => void;
  categories: Category[];
}

export const Header: React.FC<HeaderProps> = ({ currentView, onNavigate, categories }) => {
  const { user, isAdmin, logout, openAuthModal } = useAuth();
  const { itemCount, subtotal, setIsCartOpen } = useCart();
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
  const [isUserDropdownOpen, setIsUserDropdownOpen] = useState(false);
  const [isCategoryDropdownOpen, setIsCategoryDropdownOpen] = useState(false);

  // Search state
  const [searchQuery, setSearchQuery] = useState('');
  const [searchResults, setSearchResults] = useState<Product[]>([]);
  const [isSearching, setIsSearching] = useState(false);
  const [showSearchDropdown, setShowSearchDropdown] = useState(false);
  const searchContainerRef = useRef<HTMLDivElement>(null);
  const userDropdownRef = useRef<HTMLDivElement>(null);

  // Live search debounce
  useEffect(() => {
    if (!searchQuery.trim()) {
      setSearchResults([]);
      setShowSearchDropdown(false);
      return;
    }

    const timer = setTimeout(async () => {
      setIsSearching(true);
      try {
        const results = await api.getProducts({ search: searchQuery.trim() });
        setSearchResults(results.slice(0, 5));
        setShowSearchDropdown(true);
      } catch (e) {
        console.error(e);
      } finally {
        setIsSearching(false);
      }
    }, 300);

    return () => clearTimeout(timer);
  }, [searchQuery]);

  // Click outside listener
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (searchContainerRef.current && !searchContainerRef.current.contains(event.target as Node)) {
        setShowSearchDropdown(false);
      }
      if (userDropdownRef.current && !userDropdownRef.current.contains(event.target as Node)) {
        setIsUserDropdownOpen(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  const handleSelectProduct = (prod: Product) => {
    setShowSearchDropdown(false);
    setSearchQuery('');
    onNavigate('product', prod);
  };

  const handleSearchSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (searchQuery.trim()) {
      setShowSearchDropdown(false);
      onNavigate('shop', { search: searchQuery.trim() });
    }
  };

  return (
    <header className="sticky top-0 z-40 bg-[#050505]/95 backdrop-blur-xl border-b border-purple-500/20">
      {/* Top Banner Notice */}
      <div className="bg-[#0F0F12] border-b border-purple-500/20 py-1.5 px-4 text-center text-xs text-purple-200">
        <div className="max-w-7xl mx-auto flex items-center justify-between">
          <div className="flex items-center gap-2">
            <span className="flex h-2 w-2 relative">
              <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-purple-400 opacity-75"></span>
              <span className="relative inline-flex rounded-full h-2 w-2 bg-purple-500"></span>
            </span>
            <span>تخفیف ویژه افتتاحیه: کد <strong className="text-purple-300 font-bold tracking-wider px-1.5 py-0.5 bg-purple-900/50 rounded border border-purple-500/30">ZANA</strong> برای ۱۵٪ تخفیف کل سفارش‌ها</span>
          </div>
          <div className="hidden sm:flex items-center gap-4 text-xs text-zinc-400">
            <span>تحویل آنی و خودکار</span>
            <span>•</span>
            <span>پشتیبانی تلگرام و آنلاین ۲۴/۷</span>
          </div>
        </div>
      </div>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="flex items-center justify-between h-16 sm:h-20 gap-4">
          
          {/* Right: Brand Logo */}
          <div className="flex items-center gap-6">
            <button
              onClick={() => onNavigate('home')}
              className="flex items-center gap-3 text-right group focus:outline-none"
            >
              <div className="w-10 h-10 rounded-xl bg-purple-500/10 border border-purple-500/30 flex items-center justify-center text-purple-300 group-hover:border-purple-400 transition-colors">
                <img src={wireguardMark} alt="WireGuard style mark" className="w-6 h-6 group-hover:scale-110 transition-transform" />
              </div>
              <div>
                <div className="flex items-center gap-1.5">
                  <span className="text-2xl sm:text-2xl font-black tracking-tight text-gradient-neon font-vazir">
                    ZaccShop
                  </span>
                </div>
              </div>
            </button>

            {/* Desktop Navigation Links */}
            <nav className="hidden lg:flex items-center gap-2 text-sm font-medium mr-4">
              <button
                onClick={() => onNavigate('home')}
                className={`px-3.5 py-2 rounded-lg transition-all ${
                  currentView === 'home'
                    ? 'text-white bg-purple-600/20 border border-purple-500/30'
                    : 'text-zinc-400 hover:text-purple-200 hover:bg-purple-950/20'
                }`}
              >
                خانه
              </button>

              <button
                onClick={() => onNavigate('shop')}
                className={`px-3.5 py-2 rounded-lg transition-all ${
                  currentView === 'shop'
                    ? 'text-white bg-purple-600/20 border border-purple-500/30'
                    : 'text-zinc-400 hover:text-purple-200 hover:bg-purple-950/20'
                }`}
              >
                فروشگاه
              </button>

              {/* Categories Popover */}
              <div className="relative" onMouseLeave={() => setIsCategoryDropdownOpen(false)}>
                <button
                  onMouseEnter={() => setIsCategoryDropdownOpen(true)}
                  onClick={() => setIsCategoryDropdownOpen(!isCategoryDropdownOpen)}
                  className="px-3.5 py-2 rounded-lg text-zinc-400 hover:text-purple-200 hover:bg-purple-950/20 transition-all flex items-center gap-1"
                >
                  <span>دسته‌بندی‌ها</span>
                  <ChevronDown className={`w-4 h-4 transition-transform ${isCategoryDropdownOpen ? 'rotate-180' : ''}`} />
                </button>

                {isCategoryDropdownOpen && (
                  <div className="absolute top-full right-0 w-64 mt-1 p-2 bg-[#0F0F12] border border-purple-500/30 rounded-2xl shadow-2xl z-50 backdrop-blur-xl">
                    <div className="text-xs font-bold text-zinc-400 px-3 py-2 border-b border-purple-900/40">
                      دسته‌بندی‌های دیجیتال
                    </div>
                    <div className="py-1 flex flex-col gap-0.5">
                      {categories.map((cat) => (
                        <button
                          key={cat.id}
                          onClick={() => {
                            setIsCategoryDropdownOpen(false);
                            onNavigate('shop', { categoryId: cat.id });
                          }}
                          className="w-full text-right px-3 py-2.5 rounded-xl text-sm text-zinc-300 hover:text-white hover:bg-purple-900/30 transition-colors flex items-center justify-between group"
                        >
                          <span className="group-hover:translate-x-[-2px] transition-transform">{cat.name}</span>
                          {cat.productCount !== undefined && (
                            <span className="text-[11px] px-2 py-0.5 rounded-full bg-purple-950/80 text-purple-300 border border-purple-500/20">
                              {toPersianDigits(cat.productCount)}
                            </span>
                          )}
                        </button>
                      ))}
                    </div>
                  </div>
                )}
              </div>

              <button
                onClick={() => onNavigate('tutorials')}
                className={`px-3.5 py-2 rounded-lg transition-all flex items-center gap-1.5 ${currentView === 'tutorials' ? 'text-white bg-purple-600/20 border border-purple-500/30' : 'text-zinc-400 hover:text-purple-200 hover:bg-purple-950/20'}`}
              >
                <BookOpen className="w-4 h-4 text-purple-400" />
                <span>آموزش اتصال</span>
              </button>

              <button
                onClick={() => onNavigate('shop', { categoryId: 'cat_gaming_service' })}
                className="px-3.5 py-2 rounded-lg text-purple-300 hover:text-white hover:bg-purple-950/40 border border-purple-500/20 transition-all flex items-center gap-1.5"
              >
                <Zap className="w-4 h-4 text-purple-400 fill-purple-400/20" />
                <span>کاهش پینگ</span>
              </button>

              <button
                onClick={() => onNavigate('track-order')}
                className={`px-3.5 py-2 rounded-lg transition-all ${
                  currentView === 'track-order'
                    ? 'text-white bg-purple-600/20 border border-purple-500/30'
                    : 'text-zinc-400 hover:text-purple-200 hover:bg-purple-950/20'
                }`}
              >
                پیگیری سفارش
              </button>
            </nav>
          </div>

          {/* Middle: Live Search Bar */}
          <div ref={searchContainerRef} className="hidden md:block flex-1 max-w-md relative">
            <form onSubmit={handleSearchSubmit} className="relative">
              <input
                type="text"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                placeholder="جستجوی پلن WireGuard..."
                className="w-full bg-[#0F0F12] text-sm text-zinc-100 placeholder-zinc-500 pr-10 pl-4 py-2 rounded-xl border border-purple-500/20 focus:border-purple-500 focus:outline-none transition-all"
              />
              <Search className="w-4 h-4 text-purple-400 absolute right-3.5 top-1/2 -translate-y-1/2 pointer-events-none" />
              {searchQuery && (
                <button
                  type="button"
                  onClick={() => { setSearchQuery(''); setShowSearchDropdown(false); }}
                  className="absolute left-3 top-1/2 -translate-y-1/2 text-zinc-400 hover:text-zinc-200 text-xs"
                >
                  <X className="w-4 h-4" />
                </button>
              )}
            </form>

            {/* Live Search Results Dropdown */}
            {showSearchDropdown && (
              <div className="absolute top-full left-0 right-0 mt-2 bg-[#0F0F12] border border-purple-500/30 rounded-2xl shadow-2xl p-2 z-50 backdrop-blur-xl">
                {isSearching ? (
                  <div className="py-6 text-center text-xs text-purple-300">در حال جستجو...</div>
                ) : searchResults.length > 0 ? (
                  <div className="flex flex-col gap-1">
                    <div className="text-[11px] font-bold text-zinc-400 px-3 py-1.5">نتایج پیدا شده:</div>
                    {searchResults.map((prod) => (
                      <button
                        key={prod.id}
                        onClick={() => handleSelectProduct(prod)}
                        className="w-full text-right p-2.5 rounded-xl hover:bg-purple-900/30 flex items-center gap-3 transition-colors group"
                      >
                        <img
                          src={prod.image}
                          alt={prod.title}
                          className="w-10 h-10 rounded-lg object-cover bg-purple-950 border border-purple-500/20 shrink-0"
                          referrerPolicy="no-referrer"
                        />
                        <div className="flex-1 min-w-0">
                          <div className="text-sm font-semibold text-zinc-200 group-hover:text-purple-300 truncate">
                            {prod.title}
                          </div>
                          <div className="text-xs text-purple-400 font-medium mt-0.5">
                            {formatPrice(prod.price)}
                          </div>
                        </div>
                      </button>
                    ))}
                    <button
                      onClick={handleSearchSubmit}
                      className="w-full text-center py-2 mt-1 text-xs text-purple-300 hover:text-purple-200 border-t border-purple-900/40 font-medium"
                    >
                      مشاهده همه نتایج برای «{searchQuery}»
                    </button>
                  </div>
                ) : (
                  <div className="py-6 text-center text-xs text-zinc-400">
                    محصولی با این عنوان یافت نشد
                  </div>
                )}
              </div>
            )}
          </div>

          {/* Left: Actions (Admin Badge, User, Cart, Mobile Toggle) */}
          <div className="flex items-center gap-2.5">
            
            {/* Admin Quick Button */}
            {isAdmin && (
              <button
                onClick={() => onNavigate('admin')}
                className={`hidden sm:flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-bold transition-all ${
                  currentView === 'admin'
                    ? 'bg-purple-600 text-white shadow-lg shadow-purple-600/40 border border-purple-400'
                    : 'bg-[#0F0F12] text-purple-300 hover:bg-[#181822] border border-purple-500/30'
                }`}
              >
                <ShieldCheck className="w-4 h-4 text-purple-300" />
                <span>پنل مدیریت</span>
              </button>
            )}

            {/* User Account Menu */}
            <div ref={userDropdownRef} className="relative">
              {user ? (
                <button
                  onClick={() => setIsUserDropdownOpen(!isUserDropdownOpen)}
                  className="flex items-center gap-2 p-2 sm:px-3 sm:py-2 rounded-xl bg-[#0F0F12] border border-purple-500/25 hover:border-purple-500/50 text-zinc-200 hover:text-white transition-all text-sm"
                >
                  <div className="w-6 h-6 rounded-lg bg-purple-600 flex items-center justify-center text-white font-bold text-xs">
                    {user.name.charAt(0)}
                  </div>
                  <span className="hidden sm:inline font-medium max-w-[100px] truncate">{user.name}</span>
                  <ChevronDown className="w-3.5 h-3.5 text-zinc-400" />
                </button>
              ) : (
                <button
                  onClick={() => openAuthModal('login')}
                  className="flex items-center gap-1.5 px-3.5 py-2 rounded-xl bg-[#0F0F12] border border-purple-500/25 hover:border-purple-500/60 text-zinc-200 hover:text-white transition-all text-xs sm:text-sm font-medium"
                >
                  <User className="w-4 h-4 text-purple-400" />
                  <span>حساب کاربری</span>
                </button>
              )}

              {/* User Dropdown Menu */}
              {isUserDropdownOpen && user && (
                <div className="absolute left-0 mt-2 w-56 bg-[#0F0F12] border border-purple-500/30 rounded-2xl shadow-2xl p-2 z-50 backdrop-blur-xl">
                  <div className="px-3 py-2 border-b border-purple-900/40">
                    <div className="font-bold text-sm text-white truncate">{user.name}</div>
                    <div className="text-xs text-zinc-400 truncate mt-0.5">{user.email}</div>
                    {user.role === 'admin' && (
                      <span className="inline-block mt-1.5 text-[10px] px-2 py-0.5 bg-purple-500/20 text-purple-300 rounded border border-purple-500/30 font-bold">
                        مدیر فروشگاه (Admin)
                      </span>
                    )}
                  </div>
                  <div className="py-1">
                    <button
                      onClick={() => { setIsUserDropdownOpen(false); onNavigate('profile'); }}
                      className="w-full text-right px-3 py-2 text-sm text-zinc-300 hover:text-white hover:bg-purple-900/30 rounded-xl transition-colors flex items-center gap-2"
                    >
                      <User className="w-4 h-4 text-purple-400" />
                      <span>پروفایل و سفارش‌های من</span>
                    </button>

                    {user.role === 'admin' && (
                      <button
                        onClick={() => { setIsUserDropdownOpen(false); onNavigate('admin'); }}
                        className="w-full text-right px-3 py-2 text-sm text-purple-300 hover:text-purple-100 hover:bg-purple-900/30 rounded-xl transition-colors flex items-center gap-2"
                      >
                        <ShieldCheck className="w-4 h-4 text-purple-400" />
                        <span>ورود به پنل مدیریت</span>
                      </button>
                    )}

                    <button
                      onClick={() => { setIsUserDropdownOpen(false); logout(); }}
                      className="w-full text-right px-3 py-2 text-sm text-rose-300 hover:text-rose-100 hover:bg-rose-950/40 rounded-xl transition-colors flex items-center gap-2 border-t border-purple-900/30 mt-1"
                    >
                      <LogOut className="w-4 h-4 text-rose-400" />
                      <span>خروج از حساب</span>
                    </button>
                  </div>
                </div>
              )}
            </div>

            {/* Shopping Cart Button */}
            <button
              onClick={() => setIsCartOpen(true)}
              className="relative flex items-center gap-2 px-3.5 py-2 rounded-xl bg-purple-600 hover:bg-purple-500 text-white font-bold text-xs sm:text-sm shadow-[0_0_15px_rgba(168,85,247,0.35)] transition-all active:scale-95"
            >
              <ShoppingCart className="w-4 h-4" />
              <span className="hidden sm:inline">سبد خرید</span>
              {itemCount > 0 && (
                <span className="bg-white text-purple-900 text-xs font-black px-1.5 py-0.2 rounded-full">
                  {toPersianDigits(itemCount)}
                </span>
              )}
            </button>

            {/* Mobile Menu Toggle Button */}
            <button
              onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
              className="lg:hidden p-2 rounded-xl bg-[#0F0F12] border border-purple-500/20 text-zinc-300 hover:text-white"
            >
              {isMobileMenuOpen ? <X className="w-5 h-5" /> : <Menu className="w-5 h-5" />}
            </button>

          </div>
        </div>

        {/* Mobile Search Bar */}
        <div className="md:hidden pb-3">
          <form onSubmit={handleSearchSubmit} className="relative">
            <input
              type="text"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              placeholder="جستجوی پلن WireGuard..."
              className="w-full bg-[#0F0F12] text-xs text-zinc-100 placeholder-zinc-500 pr-9 pl-4 py-2 rounded-xl border border-purple-500/20 focus:outline-none focus:border-purple-500"
            />
            <Search className="w-3.5 h-3.5 text-purple-400 absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none" />
          </form>
        </div>
      </div>

      {/* Mobile Drawer Menu */}
      {isMobileMenuOpen && (
        <div className="lg:hidden bg-[#0F0F12] border-b border-purple-900/40 px-4 py-4 space-y-2">
          <button
            onClick={() => { setIsMobileMenuOpen(false); onNavigate('home'); }}
            className={`w-full text-right px-3 py-2.5 rounded-xl text-sm font-medium ${
              currentView === 'home' ? 'bg-purple-600/20 text-purple-300' : 'text-zinc-300'
            }`}
          >
            خانه
          </button>
          <button
            onClick={() => { setIsMobileMenuOpen(false); onNavigate('shop'); }}
            className={`w-full text-right px-3 py-2.5 rounded-xl text-sm font-medium ${
              currentView === 'shop' ? 'bg-purple-600/20 text-purple-300' : 'text-zinc-300'
            }`}
          >
            فروشگاه
          </button>
          <button
            onClick={() => { setIsMobileMenuOpen(false); onNavigate('shop', { categoryId: 'cat_gaming_service' }); }}
            className="w-full text-right px-3 py-2.5 rounded-xl text-sm font-medium text-purple-300 bg-purple-950/50 flex items-center justify-between"
          >
            <span className="flex items-center gap-2">
              <Zap className="w-4 h-4 text-purple-400" />
              کاهش پینگ
            </span>
            <span className="text-[10px] px-2 py-0.5 bg-purple-500/30 rounded text-purple-200">پیشنهاد ویژه</span>
          </button>
          <button
            onClick={() => { setIsMobileMenuOpen(false); onNavigate('tutorials'); }}
            className="w-full text-right px-3 py-2.5 rounded-xl text-zinc-300 hover:text-white hover:bg-purple-900/30 flex items-center gap-2"
          >
            <BookOpen className="w-4 h-4 text-purple-400" />
            آموزش اتصال WireGuard
          </button>

          <button
            onClick={() => { setIsMobileMenuOpen(false); onNavigate('track-order'); }}
            className="w-full text-right px-3 py-2.5 rounded-xl text-sm font-medium text-zinc-300"
          >
            پیگیری سفارش
          </button>

          {isAdmin && (
            <button
              onClick={() => { setIsMobileMenuOpen(false); onNavigate('admin'); }}
              className="w-full text-right px-3 py-2.5 rounded-xl text-sm font-bold text-purple-200 bg-purple-900/60 border border-purple-500/40 flex items-center gap-2"
            >
              <ShieldCheck className="w-4 h-4 text-purple-300" />
              پنل مدیریت ادمین
            </button>
          )}

          {/* Categories inside Mobile */}
          <div className="pt-2 border-t border-purple-900/30">
            <div className="text-xs font-bold text-zinc-400 mb-2 px-1">دسته‌بندی‌های محصولات:</div>
            <div className="grid grid-cols-2 gap-1.5">
              {categories.map((c) => (
                <button
                  key={c.id}
                  onClick={() => {
                    setIsMobileMenuOpen(false);
                    onNavigate('shop', { categoryId: c.id });
                  }}
                  className="text-right px-2.5 py-2 rounded-xl bg-[#15151C] text-xs text-zinc-300 hover:text-white truncate"
                >
                  {c.name}
                </button>
              ))}
            </div>
          </div>
        </div>
      )}
    </header>
  );
};
