"use client";

import Select, {
  type CSSObjectWithLabel,
  type StylesConfig,
} from "react-select";
import { SelectOption } from "./volunteerListHelpers";
import { useSelectMenuPortal } from "@/components/ui/SelectMenuPortal";

/*
 * `StylesConfig` is react-select's own type for this object, and
 * `CSSObjectWithLabel` the type of the `base` each callback extends. The three
 * `any`s this replaces were there because nobody had looked the names up — the
 * library exports both.
 *
 * `menuPortal` only takes effect together with `menuPortalTarget` on the
 * `<Select>` below; the z-index is what lifts the menu above the table's
 * sticky header.
 */
const selectStyles: StylesConfig<SelectOption, false> = {
  menuPortal: (base: CSSObjectWithLabel) => ({ ...base, zIndex: 9999 }),
  menu: (base: CSSObjectWithLabel) => ({
    ...base,
    minWidth: "200px",
    width: "auto",
  }),
  control: (base: CSSObjectWithLabel) => ({ ...base, minWidth: "200px" }),
  valueContainer: (base) => ({
    ...base,
    flex: "1 1 0%",
    minWidth: 0,
    padding: "4px 8px",
  }),
  singleValue: (base) => ({
    ...base,
    whiteSpace: "normal",
    overflow: "visible",
    textOverflow: "clip",
    overflowWrap: "anywhere",
    lineHeight: 1.5,
  }),
  option: (base) => ({ ...base, whiteSpace: "normal", overflowWrap: "anywhere" }),
  indicatorsContainer: (base) => ({ ...base, flexShrink: 0 }),
};

interface RegistrationSelectCellProps {
  options: SelectOption[];
  value: string;
  onChange: (value: string | undefined) => void | Promise<void>;
  onMenuScrollToBottom: () => void;
  isLoading: boolean;
  isDisabled: boolean;
  placeholder: string;
}

/** The team/role dropdown a registration row can be reassigned from, shared by both columns. */
export default function RegistrationSelectCell({
  options,
  value,
  onChange,
  onMenuScrollToBottom,
  isLoading,
  isDisabled,
  placeholder,
}: RegistrationSelectCellProps) {
  const menuPortalProps = useSelectMenuPortal();

  return (
    <div className="relative z-10 w-[220px] min-w-[200px]">
      <Select
        className="w-full"
        options={options}
        value={options.find((option) => option.value === value) || options[0]}
        onChange={async (option: SelectOption | null) => {
          await onChange(option?.value || undefined);
        }}
        onMenuScrollToBottom={onMenuScrollToBottom}
        isLoading={isLoading}
        isDisabled={isDisabled}
        placeholder={placeholder}
        {...menuPortalProps}
        styles={selectStyles}
        menuShouldBlockScroll={false}
        isSearchable={false}
      />
    </div>
  );
}
