'use client';

/**
 * Header Component
 * Pure Tailwind CSS - Clean top header bar with search, notifications, and profile
 */

import { useState, useEffect, useRef } from 'react';
import { useRouter } from 'next/navigation';
import { useQuery } from '@tanstack/react-query';
import { Menu, Bell, Search, X, Package, Users, Loader2 } from 'lucide-react';
import { useAuth } from '@/contexts/AuthContext';
import { productsAPI } from '@/lib/api/products';
import { customersAPI } from '@/lib/api/customers';

export default function Header({ onMenuClick, showMenuButton = true }) {
  const { user } = useAuth();
  const router = useRouter();
  const [searchQuery, setSearchQuery] = useState('');
  const [showSearchResults, setShowSearchResults] = useState(false);
  const [showNotifications, setShowNotifications] = useState(false);
  const searchRef = useRef(null);
  const notificationsRef = useRef(null);

  // Search queries
  const { data: productsData, isLoading: productsLoading } = useQuery({
    queryKey: ['search-products', searchQuery],
    queryFn: async () => {
      if (!searchQuery || searchQuery.trim().length < 2) return { products: [] };
      try {
        const response = await productsAPI.search(searchQuery.trim(), { limit: 5 });
        return { products: response?.data?.products || response?.data?.data || [] };
      } catch (error) {
        console.error('Error searching products:', error);
        return { products: [] };
      }
    },
    enabled: Boolean(searchQuery && searchQuery.trim().length >= 2),
    staleTime: 30000,
  });

  const { data: customersData, isLoading: customersLoading } = useQuery({
    queryKey: ['search-customers', searchQuery],
    queryFn: async () => {
      if (!searchQuery || searchQuery.trim().length < 2) return { customers: [] };
      try {
        const response = await customersAPI.search(searchQuery.trim());
        return { customers: response?.data?.customers || response?.data?.data || [] };
      } catch (error) {
        console.error('Error searching customers:', error);
        return { customers: [] };
      }
    },
    enabled: Boolean(searchQuery && searchQuery.trim().length >= 2),
    staleTime: 30000,
  });

  const products = productsData?.products || [];
  const customers = customersData?.customers || [];
  const isLoading = productsLoading || customersLoading;
  const hasResults = products.length > 0 || customers.length > 0;

  // Close search results when clicking outside
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (searchRef.current && !searchRef.current.contains(event.target)) {
        setShowSearchResults(false);
      }
      if (notificationsRef.current && !notificationsRef.current.contains(event.target)) {
        setShowNotifications(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  // Show results when query changes and has results
  useEffect(() => {
    if (searchQuery && searchQuery.trim().length >= 2) {
      setShowSearchResults(true);
    } else {
      setShowSearchResults(false);
    }
  }, [searchQuery, hasResults, isLoading]);

  const handleSearchResultClick = (type, id) => {
    setSearchQuery('');
    setShowSearchResults(false);
    if (type === 'product') {
      router.push(`/products/${id}`);
    } else if (type === 'customer') {
      router.push(`/customers/${id}`);
    }
  };

  const handleProfileClick = () => {
    router.push('/settings/profile');
  };

  const handleNotificationClick = () => {
    setShowNotifications(!showNotifications);
  };

  return (
    <header className="
      h-16
      bg-white dark:bg-gray-900
      border-b border-gray-200 dark:border-gray-800
      flex items-center justify-between px-4 lg:px-6
      sticky top-0 z-30
      shadow-sm
    ">
      {/* Left side - Menu button and search */}
      <div className="flex items-center gap-4 flex-1">
        {showMenuButton && (
          <button
            onClick={onMenuClick}
            className="
              lg:hidden p-2 rounded-lg
              text-gray-600 hover:bg-gray-100
              dark:text-gray-300 dark:hover:bg-gray-800
              transition-colors duration-200
              active:scale-95
            "
            aria-label="Toggle menu"
          >
            <Menu className="w-6 h-6" />
          </button>
        )}

        {/* Search bar */}
        <div className="hidden md:flex items-center flex-1 max-w-md relative" ref={searchRef}>
          <div className="relative w-full">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 dark:text-gray-500 pointer-events-none" />
            <input
              type="text"
              placeholder="Search products, customers..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              onFocus={() => {
                if (searchQuery && searchQuery.trim().length >= 2) {
                  setShowSearchResults(true);
                }
              }}
              className="
                w-full pl-10 pr-10 py-2
                bg-gray-50 border border-gray-300 rounded-lg
                text-gray-900 placeholder:text-gray-400
                focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent
                transition-all duration-200
                dark:bg-gray-800 dark:border-gray-600 dark:text-gray-100 dark:placeholder:text-gray-500
              "
            />
            {searchQuery && (
              <button
                onClick={() => {
                  setSearchQuery('');
                  setShowSearchResults(false);
                }}
                className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
              >
                <X className="w-4 h-4" />
              </button>
            )}
          </div>

          {/* Search Results Dropdown */}
          {showSearchResults && searchQuery && searchQuery.trim().length >= 2 && (
            <div className="absolute top-full left-0 right-0 mt-2 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg max-h-96 overflow-y-auto z-50">
              {isLoading ? (
                <div className="p-4 text-center text-gray-500 dark:text-gray-400">
                  <Loader2 className="w-5 h-5 animate-spin mx-auto mb-2" />
                  <p className="text-sm">Searching...</p>
                </div>
              ) : hasResults ? (
                <div className="py-2">
                  {/* Products */}
                  {products.length > 0 && (
                    <div className="px-3 py-2">
                      <p className="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase mb-2">Products</p>
                      {products.map((product) => (
                        <button
                          key={product.id}
                          onClick={() => handleSearchResultClick('product', product.id)}
                          className="w-full flex items-center gap-3 px-3 py-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded transition-colors"
                        >
                          <Package className="w-4 h-4 text-gray-400 flex-shrink-0" />
                          <div className="flex-1 text-left">
                            <p className="text-sm font-medium text-gray-900 dark:text-white">{product.name}</p>
                            {product.sku && (
                              <p className="text-xs text-gray-500 dark:text-gray-400">SKU: {product.sku}</p>
                            )}
                          </div>
                        </button>
                      ))}
                    </div>
                  )}

                  {/* Customers */}
                  {customers.length > 0 && (
                    <div className="px-3 py-2 border-t border-gray-200 dark:border-gray-700">
                      <p className="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase mb-2">Customers</p>
                      {customers.map((customer) => (
                        <button
                          key={customer.id}
                          onClick={() => handleSearchResultClick('customer', customer.id)}
                          className="w-full flex items-center gap-3 px-3 py-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded transition-colors"
                        >
                          <Users className="w-4 h-4 text-gray-400 flex-shrink-0" />
                          <div className="flex-1 text-left">
                            <p className="text-sm font-medium text-gray-900 dark:text-white">
                              {customer.name || customer.company_name || 'Unnamed Customer'}
                            </p>
                            {customer.email && (
                              <p className="text-xs text-gray-500 dark:text-gray-400">{customer.email}</p>
                            )}
                          </div>
                        </button>
                      ))}
                    </div>
                  )}

                </div>
              ) : (
                <div className="p-4 text-center text-gray-500 dark:text-gray-400">
                  <p className="text-sm">No results found</p>
                </div>
              )}
            </div>
          )}
        </div>
      </div>

      {/* Right side - Notifications and user */}
      <div className="flex items-center gap-3">
        {/* Notifications */}
        <div className="relative" ref={notificationsRef}>
          <button
            onClick={handleNotificationClick}
            className="
              relative p-2 rounded-lg
              text-gray-600 hover:bg-gray-100
              dark:text-gray-300 dark:hover:bg-gray-800
              transition-colors duration-200
              active:scale-95
            "
            aria-label="Notifications"
          >
            <Bell className="w-5 h-5" />
            <span className="absolute top-1.5 right-1.5 w-2 h-2 bg-red-500 rounded-full ring-2 ring-white dark:ring-gray-900"></span>
          </button>

          {/* Notifications Dropdown */}
          {showNotifications && (
            <div className="absolute right-0 top-full mt-2 w-80 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg z-50">
              <div className="p-4 border-b border-gray-200 dark:border-gray-700">
                <h3 className="text-sm font-semibold text-gray-900 dark:text-white">Notifications</h3>
              </div>
              <div className="p-4 text-center text-gray-500 dark:text-gray-400 text-sm">
                <p>No new notifications</p>
                <p className="text-xs mt-1">Notifications feature coming soon</p>
              </div>
            </div>
          )}
        </div>

        {/* User info */}
        {user && (
          <button
            onClick={handleProfileClick}
            className="flex items-center gap-3 pl-3 border-l border-gray-200 dark:border-gray-800 hover:opacity-80 transition-opacity cursor-pointer"
          >
            <div className="hidden sm:block text-right">
              <p className="text-sm font-medium text-gray-900 dark:text-white">
                {user.full_name || user.username}
              </p>
              <p className="text-xs text-gray-500 dark:text-gray-400 capitalize">
                {user.role}
              </p>
            </div>
            <div className="
              w-10 h-10
              bg-blue-600 rounded-full
              flex items-center justify-center
              text-white font-semibold text-sm
              shadow-sm
            ">
              {(user.full_name || user.username)
                ?.charAt(0)
                .toUpperCase() || 'U'}
            </div>
          </button>
        )}
      </div>
    </header>
  );
}
