/**
 * ============================================
 * SEARCH BAR COMPONENT
 * ============================================
 * Equivalent to: search widget in Shopware header
 * Uses the /store-api/search-suggest endpoint
 */

'use client';

import { useState, useRef, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { searchSuggest, ShopwareProduct } from '@/lib/shopware-api';
import { useSalesChannel } from '@/lib/sales-channel-context';

export default function SearchBar() {
  const { formatPrice } = useSalesChannel();
  const router = useRouter();
  const [query, setQuery] = useState('');
  const [suggestions, setSuggestions] = useState<ShopwareProduct[]>([]);
  const [isOpen, setIsOpen] = useState(false);
  const [isSearchVisible, setIsSearchVisible] = useState(false);
  const inputRef = useRef<HTMLInputElement>(null);
  const timeoutRef = useRef<NodeJS.Timeout>();

  // Navigate to full search results page
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (query.trim().length < 2) return;
    setIsOpen(false);
    setIsSearchVisible(false);
    router.push(`/search?q=${encodeURIComponent(query.trim())}`);
  };

  // Debounced search - waits 300ms after typing stops before searching
  // (prevents API call on every keystroke)
  const handleSearch = (value: string) => {
    setQuery(value);

    if (timeoutRef.current) clearTimeout(timeoutRef.current);

    if (value.length < 2) {
      setSuggestions([]);
      setIsOpen(false);
      return;
    }

    timeoutRef.current = setTimeout(async () => {
      try {
        const results = await searchSuggest(value);
        setSuggestions(results.elements?.slice(0, 5) || []);
        setIsOpen(true);
      } catch (error) {
        console.error('Search failed:', error);
      }
    }, 300);
  };

  // Close suggestions when clicking outside
  useEffect(() => {
    const handleClickOutside = () => setIsOpen(false);
    document.addEventListener('click', handleClickOutside);
    return () => document.removeEventListener('click', handleClickOutside);
  }, []);

  // Focus input when search becomes visible
  useEffect(() => {
    if (isSearchVisible && inputRef.current) {
      inputRef.current.focus();
    }
  }, [isSearchVisible]);

  return (
    <div className="relative" onClick={(e) => e.stopPropagation()}>
      {/* Search toggle button (mobile-friendly) */}
      <button
        onClick={() => setIsSearchVisible(!isSearchVisible)}
        className="p-2 text-surface-600 hover:text-surface-900 transition-colors md:hidden"
        aria-label="Search"
      >
        <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
        </svg>
      </button>

      {/* Search input */}
      <div className={`${isSearchVisible ? 'block' : 'hidden'} md:block absolute right-0 top-full mt-2 md:relative md:mt-0`}>
        <form onSubmit={handleSubmit} className="relative">
          <input
            ref={inputRef}
            type="text"
            value={query}
            onChange={(e) => handleSearch(e.target.value)}
            placeholder="Search products..."
            className="w-64 pl-9 pr-4 py-2 text-sm bg-surface-50 border border-surface-200 rounded-lg focus:outline-none focus:border-brand-500 focus:ring-1 focus:ring-brand-500 transition-all"
          />
          <svg
            className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-surface-400"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
          >
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
          </svg>

          {/* Search suggestions dropdown */}
          {isOpen && suggestions.length > 0 && (
            <div className="absolute top-full mt-1 w-full bg-white rounded-lg shadow-xl border border-surface-200 overflow-hidden z-50">
              {suggestions.map((product) => (
                <button
                  key={product.id}
                  type="button"
                  onClick={() => {
                    router.push(`/products/${product.id}`);
                    setIsOpen(false);
                    setQuery('');
                    setIsSearchVisible(false);
                  }}
                  className="flex items-center gap-3 w-full px-4 py-3 hover:bg-surface-50 transition-colors text-left"
                >
                  <div className="w-10 h-10 bg-surface-50 rounded flex-shrink-0 flex items-center justify-center">
                    {product.cover?.media?.url ? (
                      <img
                        src={product.cover.media.url}
                        alt=""
                        className="w-full h-full object-contain"
                      />
                    ) : (
                      <span className="text-sm">📦</span>
                    )}
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium truncate">
                      {product.translated?.name || product.name}
                    </p>
                    <p className="text-xs font-bold text-brand-600">
                      {formatPrice(
                        product.calculatedPrice?.unitPrice ||
                          product.price?.[0]?.gross ||
                          0
                      )}
                    </p>
                  </div>
                </button>
              ))}
              {/* View all results link */}
              <button
                type="submit"
                className="flex items-center justify-center gap-2 w-full px-4 py-3 text-sm font-medium text-brand-600 hover:bg-brand-50 border-t border-surface-100 transition-colors"
              >
                View all results for &ldquo;{query}&rdquo;
                <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 8l4 4m0 0l-4 4m4-4H3" />
                </svg>
              </button>
            </div>
          )}
        </form>
      </div>
    </div>
  );
}
