import { useEffect, useRef } from "react";
import classNames from "classnames/dedupe";
import { getOptionValue, getOptionLabel, buildOptionTestId } from "./utils";
import type { ComboboxOption, ComboboxOptionProps } from "./types";

export const Option = <T extends ComboboxOption>({
  option,
  isHighlighted,
  onOptionSelect,
  optionComponent: OptionComponent,
  optionTestIdPrefix,
  id,
}: ComboboxOptionProps<T>) => {
  const optionRef = useRef<HTMLLIElement>(null);
  const optionValue = getOptionValue(option) || "";
  const testId = buildOptionTestId(
    optionTestIdPrefix || "combobox-option",
    optionValue,
  );

  useEffect(() => {
    if (
      isHighlighted &&
      optionRef.current &&
      optionRef.current.scrollIntoView
    ) {
      optionRef.current.scrollIntoView({ block: "nearest" });
    }
  }, [isHighlighted]);

  return (
    <li
      ref={optionRef}
      role="option"
      data-testid={testId}
      key={getOptionValue(option)}
      id={id}
      aria-selected={isHighlighted}
      onMouseDown={() => onOptionSelect(option)}
      className={classNames("mobius-combobox__option", "has-pii", {
        "mobius-combobox__option--is-highlighted": isHighlighted,
      })}
    >
      {OptionComponent ? (
        <OptionComponent option={option} isHighlighted={isHighlighted} />
      ) : (
        getOptionLabel(option)
      )}
    </li>
  );
};
