"use client";

import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";

interface SearchDropdownProps {
  options: { value: string; label: string }[];
  value: string;
  onChange: (value: string) => void;
  placeholder?: string;
  error?: string;
  searchPlaceholder?: string;
  className?: string;

  // ---- Optional a11y / integration props. All default to the previous
  // behaviour, so existing call sites (profile page) are unaffected. ----

  /** Id for the trigger, so an external `<label htmlFor>` can point at it. */
  id?: string;
  ariaLabelledBy?: string;
  ariaDescribedBy?: string;
  ariaRequired?: boolean;
  /** Fired once focus has genuinely left the widget — drives `mode: "onTouched"`. */
  onBlur?: () => void;
  /**
   * "bootstrap" keeps the original `.form-select` trigger. "bare" drops it so a
   * wrapper (see `.lf-combobox`) can own the geometry instead.
   */
  variant?: "bootstrap" | "bare";
  /** Let a wrapping `Field` render the message instead of the built-in one. */
  suppressError?: boolean;
}

/**
 * Searchable single-select for lists too long to scan — country pickers run to
 * 249 entries, well past the ~30 where an unsearchable list stops being usable.
 *
 * ARIA follows the "combobox with listbox popup" pattern: while open, the
 * search input *is* the combobox and owns `aria-activedescendant`, and the
 * scrolling list is the listbox. The trigger is a plain button that opens it.
 * (Before, `role="listbox"` sat on a container that also held the search input,
 * which is invalid — a listbox may only own options — and the options carried
 * no `role="option"` at all, so nothing was announced as a choice.)
 */
const SearchDropdown = ({
  options,
  value,
  onChange,
  placeholder = "Select",
  error,
  searchPlaceholder = "Search...",
  className,
  id,
  ariaLabelledBy,
  ariaDescribedBy,
  ariaRequired,
  onBlur,
  variant = "bootstrap",
  suppressError = false,
}: SearchDropdownProps) => {
  const [query, setQuery] = useState("");
  const [open, setOpen] = useState(false);
  const [highlightedIndex, setHighlightedIndex] = useState(0);
  const [openUp, setOpenUp] = useState(false);

  const rootRef = useRef<HTMLDivElement | null>(null);
  const listRef = useRef<HTMLDivElement | null>(null);
  const triggerRef = useRef<HTMLButtonElement | null>(null);
  const savedScrollTopRef = useRef(0);
  // Blur is reported when the widget closes after having been opened, not on
  // every DOM blur — focus legitimately moves into the popup while choosing.
  const touchedRef = useRef(false);

  const reactId = useMemo(
    () => `sd-${Math.random().toString(36).slice(2, 9)}`,
    []
  );
  const baseId = id || reactId;
  const listboxId = `${baseId}-listbox`;
  const optionId = (index: number) => `${baseId}-opt-${index}`;

  const filteredOptions = useMemo(() => {
    const lowered = query.trim().toLowerCase();
    if (!lowered) return options;
    return options.filter((option) =>
      option.label.toLowerCase().includes(lowered)
    );
  }, [options, query]);

  const selectedLabel = useMemo(() => {
    return options.find((o) => o.value === value)?.label ?? "";
  }, [options, value]);

  // Index 0 is the "clear" row that restores the placeholder.
  const totalOptions = filteredOptions.length + 1;

  function close(restoreFocus: boolean) {
    setOpen(false);
    setQuery("");
    savedScrollTopRef.current = 0;
    if (restoreFocus) triggerRef.current?.focus();
    if (touchedRef.current) {
      touchedRef.current = false;
      onBlur?.();
    }
  }

  /* Outside click + escape */
  useEffect(() => {
    if (!open) return;

    const onDocMouseDown = (event: MouseEvent) => {
      const target = event.target as Node | null;
      if (rootRef.current && target && !rootRef.current.contains(target)) {
        close(false);
      }
    };

    const onDocKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") close(true);
    };

    document.addEventListener("mousedown", onDocMouseDown);
    document.addEventListener("keydown", onDocKeyDown);

    return () => {
      document.removeEventListener("mousedown", onDocMouseDown);
      document.removeEventListener("keydown", onDocKeyDown);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open]);

  // Decide whether to open above or below based on viewport space.
  // Computed once when the dropdown opens — not re-triggered by list changes.
  useEffect(() => {
    if (!open) return;
    const root = rootRef.current;
    if (!root) return;

    const rect = root.getBoundingClientRect();
    const spaceBelow = window.innerHeight - rect.bottom;
    const estimatedHeight = 320;

    setOpenUp(spaceBelow < estimatedHeight);
  }, [open]);

  // When filteredOptions updates (e.g. async data arrives), restore the scroll
  // position the user was at so the list does not jump.
  useLayoutEffect(() => {
    if (listRef.current) {
      listRef.current.scrollTop = savedScrollTopRef.current;
    }
  }, [filteredOptions]);

  // Keep the keyboard-highlighted row visible.
  useLayoutEffect(() => {
    if (!open) return;
    const el = document.getElementById(optionId(highlightedIndex));
    el?.scrollIntoView({ block: "nearest" });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [highlightedIndex, open]);

  const handleSelect = (nextValue: string) => {
    onChange(nextValue);
    close(true);
  };

  const moveHighlight = (delta: number) => {
    setHighlightedIndex((current) => (current + delta + totalOptions) % totalOptions);
  };

  const triggerClass =
    variant === "bare"
      ? className || ""
      : `form-select border rounded ${className || ""} ${error ? "is-invalid" : ""}`;

  return (
    <div
      ref={rootRef}
      className={`position-relative ${variant === "bare" ? "lf-combobox-root" : ""}`}
      data-open={open ? "true" : "false"}
    >
      <button
        ref={triggerRef}
        type="button"
        id={baseId}
        className={triggerClass}
        aria-haspopup="listbox"
        aria-expanded={open}
        aria-controls={open ? listboxId : undefined}
        aria-labelledby={ariaLabelledBy}
        // The error text is reachable from the trigger through its description.
        // `aria-invalid`/`aria-required` are deliberately not here: neither is
        // supported on role="button", so they live on the combobox input below,
        // where ARIA does define them.
        aria-describedby={ariaDescribedBy}
        style={variant === "bare" ? undefined : { textAlign: "left" }}
        onClick={() =>
          setOpen((v) => {
            const next = !v;
            if (next) {
              touchedRef.current = true;
              setHighlightedIndex(0);
            }
            return next;
          })
        }
        onKeyDown={(e) => {
          // Opening straight into the list with the keyboard, as a native
          // select does, rather than forcing a separate Enter first.
          if (e.key === "ArrowDown" || e.key === "ArrowUp") {
            e.preventDefault();
            touchedRef.current = true;
            setHighlightedIndex(0);
            setOpen(true);
          }
        }}
      >
        {variant === "bare" ? (
          <>
            <span className="text-truncate">{selectedLabel || placeholder}</span>
            <svg
              width="12"
              height="8"
              viewBox="0 0 12 8"
              fill="none"
              aria-hidden="true"
              style={{ flex: "0 0 auto" }}
            >
              <path
                d="M1 1.5 6 6.5l5-5"
                stroke="currentColor"
                strokeWidth="1.6"
                strokeLinecap="round"
                strokeLinejoin="round"
              />
            </svg>
          </>
        ) : (
          selectedLabel || placeholder
        )}
      </button>

      {open && (
        <div
          className={`position-absolute w-100 bg-white border rounded z-3 ${
            openUp ? "mb-1" : "mt-1"
          } search-dropdown-popup`}
          style={
            openUp
              ? { bottom: "100%", top: "auto" }
              : { top: "100%", bottom: "auto" }
          }
        >
          <div className="p-2 border-bottom">
            <input
              autoFocus
              type="text"
              role="combobox"
              aria-expanded="true"
              aria-controls={listboxId}
              aria-autocomplete="list"
              aria-activedescendant={optionId(highlightedIndex)}
              aria-label={searchPlaceholder}
              aria-describedby={ariaDescribedBy}
              aria-invalid={error ? true : undefined}
              aria-required={ariaRequired ? true : undefined}
              className="form-control border rounded"
              placeholder={searchPlaceholder}
              value={query}
              onChange={(e) => {
                setQuery(e.target.value);
                setHighlightedIndex(0);
                savedScrollTopRef.current = 0;
              }}
              onKeyDown={(e) => {
                if (e.key === "ArrowDown") {
                  e.preventDefault();
                  moveHighlight(1);
                } else if (e.key === "ArrowUp") {
                  e.preventDefault();
                  moveHighlight(-1);
                } else if (e.key === "Home") {
                  e.preventDefault();
                  setHighlightedIndex(0);
                } else if (e.key === "End") {
                  e.preventDefault();
                  setHighlightedIndex(totalOptions - 1);
                } else if (e.key === "Enter") {
                  e.preventDefault();
                  if (highlightedIndex === 0) {
                    handleSelect("");
                  } else if (filteredOptions[highlightedIndex - 1]) {
                    handleSelect(filteredOptions[highlightedIndex - 1].value);
                  }
                } else if (e.key === "Escape") {
                  e.preventDefault();
                  close(true);
                } else if (e.key === "Tab") {
                  close(false);
                }
              }}
            />
          </div>

          <div
            ref={listRef}
            id={listboxId}
            role="listbox"
            aria-label={placeholder}
            style={{ maxHeight: 260, overflowY: "auto" }}
            onScroll={() => {
              if (listRef.current) {
                savedScrollTopRef.current = listRef.current.scrollTop;
              }
            }}
          >
            <button
              type="button"
              id={optionId(0)}
              role="option"
              aria-selected={value === ""}
              className={`w-100 text-start px-2 py-2 border-0 bg-light search-dropdown-option ${
                highlightedIndex === 0 ? "search-dropdown-option--active" : ""
              }`}
              onClick={() => handleSelect("")}
            >
              {placeholder}
            </button>

            {filteredOptions.length === 0 ? (
              <div className="px-2 pb-2 text-muted small">No results</div>
            ) : (
              filteredOptions.map((option, index) => (
                <button
                  key={option.value}
                  type="button"
                  id={optionId(index + 1)}
                  role="option"
                  aria-selected={option.value === value}
                  className={`w-100 text-start px-2 py-2 border-0 bg-white search-dropdown-option ${
                    highlightedIndex === index + 1
                      ? "search-dropdown-option--active"
                      : ""
                  }`}
                  onClick={() => handleSelect(option.value)}
                >
                  {option.label}
                </button>
              ))
            )}
          </div>
        </div>
      )}

      {error && !suppressError && (
        <div className="invalid-feedback d-block">{error}</div>
      )}
    </div>
  );
};

export { SearchDropdown };
