"use client";

import { useRef, useState } from "react";
import { useRouter } from "next/navigation";
import {
  useProductSearch,
  useClickOutside,
  SEARCH_CATEGORIES,
} from "@/lib/search";
import type { SearchCategory } from "@/lib/search";
import { SearchResultsPanel } from "@/components/search/SearchResultsPanel";
import { getProductUrl } from "@/lib/shop/productMapper";

interface HeaderSearchBarProps {
  variant: "desktop" | "mobile";
}

export function HeaderSearchBar({ variant }: HeaderSearchBarProps) {
  const router = useRouter();
  const search = useProductSearch();
  const searchBarRef = useRef<HTMLDivElement>(null);

  // Desktop-only: custom category dropdown state
  const [selectedCategory, setSelectedCategory] = useState<SearchCategory>(
    SEARCH_CATEGORIES[0],
  );
  const [dropdownOpen, setDropdownOpen] = useState(false);

  useClickOutside(
    [searchBarRef, search.panelRef],
    search.close,
    search.isOpen,
  );

  function handleCategorySelect(cat: SearchCategory) {
    setSelectedCategory(cat);
    search.setCategorySlug(cat.slug);
    setDropdownOpen(false);
  }

  const isDesktop = variant === "desktop";

  return (
    <div
      ref={searchBarRef}
      className={
        isDesktop
          ? "relative flex w-full max-w-2xl items-center rounded-full border border-[#d9e8e7] bg-[#f9fcfb] shadow-sm transition-shadow focus-within:border-[#38a99f] focus-within:shadow-md"
          : "relative flex items-center rounded-full border border-[#d9e8e7] bg-[#f9fcfb] py-3 px-3 shadow-sm transition-shadow focus-within:border-[#38a99f] focus-within:shadow-md"
      }
    >
      {/* Category picker */}
      {isDesktop ? (
        /* Desktop: custom dropdown */
        <div className="relative">
          <button
            onClick={() => setDropdownOpen(!dropdownOpen)}
            onBlur={() => setTimeout(() => setDropdownOpen(false), 150)}
            className="flex items-center gap-1.5 rounded-l-full py-3 pl-5 pr-3 text-sm text-[#3d5554] transition-colors hover:text-[#1a2e2d]"
          >
            <span className="max-w-[110px] truncate">{selectedCategory.label}</span>
            <svg
              width="12"
              height="12"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="2.5"
              strokeLinecap="round"
              strokeLinejoin="round"
              className={`transition-transform ${dropdownOpen ? "rotate-180" : ""}`}
            >
              <polyline points="6 9 12 15 18 9" />
            </svg>
          </button>

          {dropdownOpen && (
            <div className="absolute left-0 top-full z-50 mt-1 min-w-[180px] overflow-hidden rounded-xl border border-[#e8f7f6] bg-white py-1 shadow-lg">
              {SEARCH_CATEGORIES.map((cat) => (
                <button
                  key={cat.label}
                  onClick={() => handleCategorySelect(cat)}
                  className={`block w-full px-4 py-2 text-left text-sm transition-colors hover:bg-[#e8f7f6] ${
                    selectedCategory.label === cat.label
                      ? "font-medium text-[#236f6b]"
                      : "text-[#3d5554]"
                  }`}
                >
                  {cat.label}
                </button>
              ))}
            </div>
          )}
        </div>
      ) : (
        /* Mobile: native select leverages OS picker */
        <div className="flex items-center gap-1 border-r border-[#d9e8e7] pl-3 pr-2">
          <select
            value={search.categorySlug ?? ""}
            onChange={(e) => search.setCategorySlug(e.target.value || undefined)}
            className="max-w-[80px] appearance-none truncate bg-transparent text-xs font-medium text-[#3d5554] outline-none"
            aria-label="Search category"
          >
            {SEARCH_CATEGORIES.map((cat) => (
              <option key={cat.label} value={cat.slug ?? ""}>
                {cat.label}
              </option>
            ))}
          </select>
          <svg
            width="12"
            height="12"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2.5"
            strokeLinecap="round"
            strokeLinejoin="round"
            className="shrink-0 text-[#8aa9a8]"
            aria-hidden="true"
          >
            <polyline points="6 9 12 15 18 9" />
          </svg>
        </div>
      )}

      {/* Divider — desktop only, between category picker and input */}
      {isDesktop && <div className="h-6 w-px bg-[#d9e8e7]" />}

      {/* Input */}
      <input
        ref={search.inputRef}
        type="text"
        value={search.query}
        onChange={(e) => search.setQuery(e.target.value)}
        onFocus={() => search.open()}
        onKeyDown={search.handleKeyDown}
        onBlur={search.handleBlur}
        placeholder={
          isDesktop
            ? "Search for products, brands, and more..."
            : "Search for food, toys, etc."
        }
        className={
          isDesktop
            ? "flex-1 bg-transparent py-3 pl-4 pr-5 text-sm text-[#1a2e2d] outline-none placeholder:text-[#8aa9a8]"
            : "min-h-[44px] flex-1 border-none bg-transparent py-2 pl-3 pr-4 text-sm text-[#1a2e2d] outline-none placeholder:text-[#8aa9a8] focus:ring-0"
        }
        role="combobox"
        aria-expanded={search.isOpen && search.showResults}
        aria-controls="search-results-panel"
        aria-activedescendant={
          search.selectedIndex >= 0
            ? `search-result-${search.selectedIndex}`
            : undefined
        }
        aria-autocomplete="list"
        autoComplete="off"
      />

      {/* Results Panel */}
      {(search.showResults || search.showMinCharsHint) && (
        <SearchResultsPanel
          results={search.results}
          isLoading={search.isLoading}
          isStalled={search.isStalled}
          isEmpty={search.isEmpty}
          query={search.query}
          selectedIndex={search.selectedIndex}
          onItemSelect={(item) => {
            router.push(getProductUrl(item));
            search.close();
          }}
          onItemHover={search.setSelectedIndex}
          showMinCharsHint={search.showMinCharsHint}
          panelRef={search.panelRef}
        />
      )}
    </div>
  );
}
