"use client";

import { useState, useRef, useEffect, useMemo, type ReactNode } from "react";
import { useDebounce } from "~/hooks/useDebounce.js";

interface EntityComboboxProps<T extends { id: string }> {
  value: string | null;
  onChange: (id: string | null) => void;
  placeholder?: string;
  disabled?: boolean;
  className?: string;
  /** Hook that returns search results when the dropdown is open. */
  useSearchQuery: (search: string, enabled: boolean) => { data: T[] | undefined };
  /** Hook that returns a broader list so the selected item's label can be resolved when the dropdown is closed. */
  useSelectedQuery: (id: string | null, enabled: boolean) => { data: T[] | undefined };
  /** Derive the display label from an item (shown in the input when closed). */
  getLabel: (item: T) => string;
  /** Optional custom renderer for each dropdown row. Falls back to `getLabel`. */
  renderItem?: (item: T, isSelected: boolean) => ReactNode;
}

export function EntityCombobox<T extends { id: string }>({
  value,
  onChange,
  placeholder = "Search\u2026",
  disabled = false,
  className = "",
  useSearchQuery,
  useSelectedQuery,
  getLabel,
  renderItem,
}: EntityComboboxProps<T>) {
  const [open, setOpen] = useState(false);
  const [search, setSearch] = useState("");
  const debouncedSearch = useDebounce(search, 300);
  const containerRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  const { data: searchItems } = useSearchQuery(debouncedSearch, open);
  const items = searchItems ?? [];

  const { data: selectedItems } = useSelectedQuery(value, !!value && !open);

  const selectedLabel = useMemo(() => {
    if (!value) return "";
    const fromOpen = items.find((i) => i.id === value);
    if (fromOpen) return getLabel(fromOpen);
    const fromSelected = selectedItems?.find((i) => i.id === value);
    if (fromSelected) return getLabel(fromSelected);
    return value;
  }, [value, items, selectedItems, getLabel]);

  useEffect(() => {
    if (!open) return;
    function handleClick(e: MouseEvent) {
      if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
        setOpen(false);
        setSearch("");
      }
    }
    document.addEventListener("mousedown", handleClick);
    return () => document.removeEventListener("mousedown", handleClick);
  }, [open]);

  function handleFocus() {
    if (disabled) return;
    setOpen(true);
    setSearch("");
  }

  function select(id: string | null) {
    onChange(id);
    setOpen(false);
    setSearch("");
    inputRef.current?.blur();
  }

  return (
    <div className={`relative ${className}`} ref={containerRef}>
      <div className="relative">
        <input
          ref={inputRef}
          type="text"
          value={open ? search : selectedLabel}
          onChange={(e) => setSearch(e.target.value)}
          onFocus={handleFocus}
          placeholder={placeholder}
          disabled={disabled}
          className={`w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-brand-500 disabled:opacity-50 disabled:cursor-not-allowed ${
            open
              ? "border-brand-500 ring-2 ring-brand-500"
              : "border-gray-300 hover:border-gray-400 dark:border-gray-600 dark:hover:border-gray-500"
          } bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 placeholder:text-gray-400 dark:placeholder:text-gray-500`}
          readOnly={!open}
        />
        {value && !disabled && !open && (
          <button
            type="button"
            onMouseDown={(e) => { e.preventDefault(); e.stopPropagation(); select(null); }}
            className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 text-lg leading-none"
            aria-label="Clear"
            tabIndex={-1}
          >
            {"\u00d7"}
          </button>
        )}
      </div>

      {open && (
        <div className="absolute left-0 right-0 top-full mt-1 z-[60] bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-600 rounded-xl shadow-xl overflow-hidden">
          <ul className="max-h-52 overflow-y-auto py-1">
            {items.length === 0 ? (
              <li className="px-3 py-2 text-sm text-gray-400 dark:text-gray-500">No results</li>
            ) : (
              items.map((item) => (
                <li key={item.id}>
                  <button
                    type="button"
                    onMouseDown={() => select(item.id)}
                    className={`w-full text-left px-3 py-1.5 text-sm hover:bg-brand-50 dark:hover:bg-brand-950/40 ${
                      item.id === value
                        ? "bg-brand-50 dark:bg-brand-950/40 text-brand-700 dark:text-brand-300 font-medium"
                        : "text-gray-700 dark:text-gray-200"
                    }`}
                  >
                    {renderItem ? renderItem(item, item.id === value) : getLabel(item)}
                  </button>
                </li>
              ))
            )}
          </ul>
        </div>
      )}
    </div>
  );
}
