"use client";

import { createPortal } from "react-dom";
import { useState, useRef, useMemo, useCallback, type ReactNode } from "react";
import { useDebounce } from "~/hooks/useDebounce.js";
import { useAnchoredOverlay } from "~/hooks/useAnchoredOverlay.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 closeDropdown = useCallback(() => {
    setOpen(false);
    setSearch("");
  }, []);

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

  const { data: selectedItems } = useSelectedQuery(value, !!value && !open);
  const { panelRef, position } = useAnchoredOverlay<HTMLDivElement>({
    open,
    onClose: closeDropdown,
    align: "start",
    matchTriggerWidth: true,
    triggerRef: containerRef,
  });

  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]);

  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 && (
        typeof document !== "undefined"
          ? createPortal(
              <div
                ref={panelRef}
                data-entity-combobox-overlay="true"
                className="fixed z-[9998] overflow-hidden rounded-xl border border-gray-200 bg-white shadow-xl dark:border-gray-600 dark:bg-gray-800"
                style={{
                  top: position.top,
                  left: position.left,
                  width: position.minWidth,
                }}
              >
                <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>,
              document.body,
            )
          : null
      )}
    </div>
  );
}
