'use client';

import React, { useState, useEffect, useRef } from 'react';
import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import { useCart } from '@/context/CartContext';
import { useSiteSettings } from '@/context/SiteSettingsContext';
import { useAuth } from '@/context/AuthContext';
import { Home, LayoutGrid, ShoppingCart, Search, User, X } from 'lucide-react';
import api from '@/lib/api';

interface Product {
  id: number;
  name: string;
  slug: string;
  price: number;
  sale_price?: number;
  image_url: string;
  category?: {
    name: string;
    slug: string;
  };
}

export const MobileBottomNav: React.FC = () => {
  const pathname = usePathname();
  const router = useRouter();
  const { cartCount, setCartOpen } = useCart();
  const { formatPrice, settings } = useSiteSettings();
  const { user } = useAuth();
  const [showSearch, setShowSearch] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [allProducts, setAllProducts] = useState<Product[]>([]);
  const [loadingProducts, setLoadingProducts] = useState(false);
  const inputRef = useRef<HTMLInputElement>(null);

  // Focus input and fetch products when search overlay state changes
  useEffect(() => {
    if (showSearch) {
      setTimeout(() => {
        inputRef.current?.focus();
      }, 150);

      // Fetch all products once for instant client-side search
      const fetchAllProducts = async () => {
        setLoadingProducts(true);
        try {
          const res = await api.get('/api/products?limit=250');
          const items = res.data.data || [];
          setAllProducts(items);
        } catch (err) {
          console.error('Failed to load products for search', err);
        } finally {
          setLoadingProducts(false);
        }
      };

      if (allProducts.length === 0) {
        fetchAllProducts();
      }
    } else {
      setSearchQuery('');
    }
  }, [showSearch, allProducts.length]);

  // Filter products in memory instantly as the user types
  const query = searchQuery.trim().toLowerCase();
  const filteredResults = query
    ? allProducts.filter((product) => {
        const nameMatch = product.name.toLowerCase().includes(query);
        const catMatch = product.category?.name?.toLowerCase().includes(query);
        return nameMatch || catMatch;
      }).slice(0, 5) // Limit to top 5 results
    : [];

  // Exclude rendering on checkout page
  if (pathname === '/checkout') {
    return null;
  }

  const handleSearchSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (searchQuery.trim()) {
      router.push(`/shop?search=${encodeURIComponent(searchQuery.trim())}`);
      setShowSearch(false);
      setSearchQuery('');
    }
  };

  const handleMenuClick = () => {
    window.dispatchEvent(new CustomEvent('toggle-mobile-menu'));
  };

  const renderItemIcon = (item: any) => {
    const url = item.link_url?.toLowerCase() || '';
    const name = item.name?.toLowerCase() || '';

    // Cart icon with count badge
    if (url.includes('cart') || name.includes('cart') || name.includes('কার্ট')) {
      return (
        <div className="relative">
          <ShoppingCart className="h-5.5 w-5.5" />
          {cartCount > 0 && (
            <span className="absolute -top-1.5 -right-2 flex h-4.5 w-4.5 items-center justify-center rounded-full bg-slate-900 text-[9px] font-black text-white shadow-sm ring-1 ring-secondary">
              {cartCount}
            </span>
          )}
        </div>
      );
    }

    if (url === '/' || name.includes('home') || name.includes('হোম')) {
      return <Home className="h-5.5 w-5.5" />;
    }
    
    if (url.includes('shop') || url.includes('category') || name.includes('category') || name.includes('ক্যাটাগরি') || name.includes('menu') || name.includes('মেনু')) {
      return <LayoutGrid className="h-5.5 w-5.5" />;
    }

    if (url.includes('search') || name.includes('search') || name.includes('খুঁজুন')) {
      return <Search className="h-5.5 w-5.5" />;
    }

    if (url.includes('dashboard') || name.includes('account') || name.includes('profile') || name.includes('প্রোফাইল') || name.includes('অ্যাকাউন্ট') || name.includes('আমার')) {
      return <User className="h-5.5 w-5.5" />;
    }

    // Default icon fallback
    return <LayoutGrid className="h-5.5 w-5.5" />;
  };

  return (
    <>
      {/* Search Overlay */}
      <div 
        className={`fixed inset-0 z-50 bg-black/40 backdrop-blur-xs transition-opacity duration-300 ${
          showSearch ? 'opacity-100 pointer-events-auto' : 'opacity-0 pointer-events-none'
        }`}
        onClick={() => setShowSearch(false)}
      >
        <div 
          className={`absolute top-0 left-0 right-0 bg-white border-b border-slate-200 px-4 pt-3 pb-4 shadow-lg transition-transform duration-300 ease-out flex flex-col gap-3 ${
            showSearch ? 'translate-y-0' : '-translate-y-full'
          }`}
          onClick={(e) => e.stopPropagation()}
        >
          <div className="flex items-center justify-between">
            <h3 className="text-[16px] font-bold text-slate-800 font-open-sans">Search Products</h3>
            <button 
              type="button"
              onClick={() => setShowSearch(false)}
              className="h-8 w-8 flex items-center justify-center rounded-full bg-red-50 hover:bg-red-100 text-[#ef4444] transition-colors focus:outline-none cursor-pointer"
            >
              <X className="h-4 w-4 stroke-[2.5]" />
            </button>
          </div>
          <form onSubmit={handleSearchSubmit} className="flex">
            <input
              ref={inputRef}
              type="text"
              placeholder="Search in..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="flex-1 text-sm py-2.5 px-4 border border-slate-200 rounded-l-lg focus:outline-none bg-white font-open-sans text-slate-700 placeholder:text-slate-400"
            />
            <button 
              type="submit" 
              className="bg-secondary hover:bg-secondary-dark text-white px-5 rounded-r-lg transition-colors flex items-center justify-center shrink-0 cursor-pointer"
            >
              <Search className="h-5 w-5" />
            </button>
          </form>

          {/* Search Results Dropdown List */}
          {searchQuery.trim() && (
            <div className="mt-1 bg-white border border-slate-150 rounded-xl shadow-lg max-h-[300px] overflow-y-auto divide-y divide-slate-100 animate-in fade-in duration-200">
              {loadingProducts && allProducts.length === 0 ? (
                <div className="flex items-center justify-center py-6 text-slate-400 text-xs gap-2">
                  <span className="animate-spin rounded-full h-4 w-4 border-2 border-slate-350 border-t-secondary"></span>
                  <span>Searching products...</span>
                </div>
              ) : filteredResults.length > 0 ? (
                filteredResults.map((product) => {
                  const price = product.sale_price ?? product.price;
                  const comparePrice = product.price;
                  const hasDiscount = product.sale_price && product.price > product.sale_price;

                  const resolvedImageUrl = product.image_url.startsWith('http') 
                    ? product.image_url 
                    : `${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000'}${product.image_url}`;

                  return (
                    <Link
                      key={product.id}
                      href={`/products/${product.slug}`}
                      onClick={() => setShowSearch(false)}
                      className="flex items-center gap-3 p-3 hover:bg-slate-50 transition-colors text-left"
                    >
                      {/* Image */}
                      <div className="h-12 w-12 bg-slate-50 border border-slate-100 rounded-lg overflow-hidden flex items-center justify-center p-1 flex-shrink-0 bg-white">
                        <img 
                          src={resolvedImageUrl} 
                          alt={product.name} 
                          className="max-h-full max-w-full object-contain"
                          onError={(e) => {
                            e.currentTarget.src = '/images/placeholder.jpg';
                          }}
                        />
                      </div>
                      {/* Info */}
                      <div className="flex-1 min-w-0">
                        <h4 className="text-slate-800 truncate" style={{ fontFamily: '"Open Sans", sans-serif', fontSize: '14px', fontWeight: 500 }}>
                          {product.name}
                        </h4>
                        <div className="flex items-center gap-1.5 mt-0.5">
                          <span className="text-secondary" style={{ fontFamily: '"Open Sans", sans-serif', fontSize: '13px', fontWeight: 600 }}>{formatPrice(price)}</span>
                          {hasDiscount && (
                            <span className="text-[10px] text-slate-440 line-through">{formatPrice(comparePrice)}</span>
                          )}
                        </div>
                        {product.category?.name && (
                          <span className="text-[10px] text-slate-450 block mt-0.5 font-medium">
                            {product.category.name}
                          </span>
                        )}
                      </div>
                    </Link>
                  );
                })
              ) : (
                <div className="text-center py-6 text-slate-400 text-xs">
                  No products found for "{searchQuery}"
                </div>
              )}
            </div>
          )}
        </div>
      </div>

      {/* Sticky Bottom Nav Bar */}
      {(() => {
        const stickyItems = settings?.navigation?.sticky_bar;
        const hasDynamicItems = stickyItems && stickyItems.length > 0;

        if (hasDynamicItems) {
          // DYNAMIC: Render custom items from Menu Builder
          return (
            <div className="fixed bottom-0 left-0 right-0 bg-secondary text-white h-[56px] z-40 lg:hidden flex justify-around items-center border-t border-secondary-dark shadow-[0_-4px_10px_rgba(0,0,0,0.12)] font-open-sans">
              {stickyItems!.map((item) => {
                const isCart = item.link_url?.toLowerCase().includes('cart') || item.name?.toLowerCase().includes('cart') || item.name?.toLowerCase().includes('কার্ট');
                const isMenu = item.link_url?.toLowerCase().includes('menu') || item.name?.toLowerCase().includes('menu') || item.name?.toLowerCase().includes('মেনু');
                const isSearch = item.link_url?.toLowerCase().includes('search') || item.name?.toLowerCase().includes('search') || item.name?.toLowerCase().includes('খুঁজুন');

                const handleClick = (e: React.MouseEvent) => {
                  if (isCart) {
                    e.preventDefault();
                    setCartOpen(true);
                  } else if (isMenu) {
                    e.preventDefault();
                    handleMenuClick();
                  } else if (isSearch) {
                    e.preventDefault();
                    setShowSearch(true);
                  }
                };

                return (
                  <Link
                    key={item.id}
                    href={user?.role === 'reseller' && item.link_url === '/dashboard' ? '/reseller/dashboard' : item.link_url}
                    onClick={handleClick}
                    className="flex flex-col items-center justify-center flex-1 h-full active:scale-95 transition-transform"
                  >
                    {renderItemIcon(item)}
                    <span className="text-[9px] font-bold tracking-wider mt-0.5 text-center px-1 leading-tight">
                      {item.name}
                    </span>
                  </Link>
                );
              })}
            </div>
          );
        }

        // FALLBACK: Original hardcoded 5-button bottom bar
        return (
          <div className="fixed bottom-0 left-0 right-0 bg-secondary text-white h-[56px] z-40 lg:hidden flex justify-around items-center border-t border-secondary-dark shadow-[0_-4px_10px_rgba(0,0,0,0.12)] font-open-sans">
            
            {/* HOME */}
            <Link href="/" className="flex flex-col items-center justify-center w-16 h-full active:scale-95 transition-transform">
              <Home className="h-5.5 w-5.5" />
              <span className="text-[9px] font-bold tracking-wider mt-0.5">HOME</span>
            </Link>

            {/* MENU */}
            <button 
              onClick={handleMenuClick} 
              className="flex flex-col items-center justify-center w-16 h-full active:scale-95 transition-transform focus:outline-none cursor-pointer"
            >
              <LayoutGrid className="h-5.5 w-5.5" />
              <span className="text-[9px] font-bold tracking-wider mt-0.5">MENU</span>
            </button>

            {/* CART */}
            <button 
              onClick={() => setCartOpen(true)} 
              className="flex flex-col items-center justify-center w-16 h-full relative active:scale-95 transition-transform focus:outline-none cursor-pointer"
            >
              <div className="relative">
                <ShoppingCart className="h-5.5 w-5.5" />
                {cartCount > 0 && (
                  <span className="absolute -top-1.5 -right-2 flex h-4.5 w-4.5 items-center justify-center rounded-full bg-slate-900 text-[9px] font-black text-white shadow-sm ring-1 ring-secondary">
                    {cartCount}
                  </span>
                )}
              </div>
              <span className="text-[9px] font-bold tracking-wider mt-0.5">CART</span>
            </button>

            {/* SEARCH */}
            <button 
              onClick={() => setShowSearch(true)} 
              className="flex flex-col items-center justify-center w-16 h-full active:scale-95 transition-transform focus:outline-none cursor-pointer"
            >
              <Search className="h-5.5 w-5.5" />
              <span className="text-[9px] font-bold tracking-wider mt-0.5">SEARCH</span>
            </button>

            {/* ACCOUNT */}
            <Link href={user?.role === 'reseller' ? '/reseller/dashboard' : '/dashboard'} className="flex flex-col items-center justify-center w-16 h-full active:scale-95 transition-transform">
              <User className="h-5.5 w-5.5" />
              <span className="text-[9px] font-bold tracking-wider mt-0.5">ACCOUNT</span>
            </Link>

          </div>
        );
      })()}
    </>
  );
};

function numberWithCommas(x: number | null | undefined) {
  if (x === null || x === undefined || isNaN(Number(x))) return '0';
  return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
