"use client";

import { Search, ChevronDown } from "lucide-react";
import { components, type DropdownIndicatorProps, type InputProps, type MenuListProps } from "react-select";
import { cn } from "@/lib/utils";

// Shared building blocks for react-select dropdowns that need a search box
// injected at the top of the open menu instead of react-select's own input
// row in the control. Previously copy-pasted per page (send/page.tsx,
// RecipientEditView.tsx, SendNewBeneficiaryView.tsx) — extracted here once a
// 4th copy was about to appear (see docs/payment-gateway-options.md).

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function SearchMenuList(props: MenuListProps<any, false>) {
  return (
    <components.MenuList {...props}>
      <div className="flex items-center gap-2.5 border-b border-slate-200 px-4 dark:border-slate-700">
        <Search className="h-4 w-4 shrink-0 text-slate-400" />
        <input
          autoFocus
          value={props.selectProps.inputValue}
          onChange={(e) =>
            props.selectProps.onInputChange(e.target.value, { action: "input-change", prevInputValue: props.selectProps.inputValue })
          }
          onMouseDown={(e) => e.stopPropagation()}
          onTouchEnd={(e) => e.stopPropagation()}
          placeholder="Search..."
          style={{ outline: "none", boxShadow: "none" }}
          className="min-w-0 flex-1 bg-transparent py-3 text-sm text-slate-900 placeholder:text-slate-400 dark:text-white"
        />
      </div>
      {props.children}
    </components.MenuList>
  );
}

// isSearchable={false} renders DummyInput (ignores components.Input), so callers use
// isSearchable={true} + this override: always hidden in control, onBlur stripped
// so autoFocus on the menu's search input doesn't trigger the blur→close chain.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function SearchInput(props: InputProps<any, false>) {
  const { onBlur: _discarded, ...rest } = props;
  return <components.Input {...rest} isHidden={true} />;
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function SelectDropdownIndicator(props: DropdownIndicatorProps<any, false>) {
  return (
    <components.DropdownIndicator {...props}>
      <ChevronDown
        className={cn(
          "h-4 w-4 text-slate-400 transition-transform duration-200",
          props.selectProps.menuIsOpen && "rotate-180",
        )}
      />
    </components.DropdownIndicator>
  );
}

export const SEARCHABLE_SELECT_COMPONENTS = {
  DropdownIndicator: SelectDropdownIndicator,
  IndicatorSeparator: () => null,
  MenuList: SearchMenuList,
  Input: SearchInput,
};
