import { useState } from "react";
import type { ComboboxOptions } from "./types";
import { isOptionGroup } from "./utils";

export function useComboboxHighlight(options: ComboboxOptions | undefined) {
  const [highlightedIndex, setHighlightedIndex] = useState(
    options && options.length ? 0 : -1,
  );
  const [highlightedGroupIndex, setHighlightedGroupIndex] = useState(0);

  function highlightNextOption() {
    const isGroup = isOptionGroup(options);

    if (!options) {
      return;
    }

    if (isGroup) {
      const group = options[highlightedGroupIndex];
      if (highlightedIndex === group.options.length - 1) {
        if (highlightedGroupIndex === options.length - 1) {
          return; // At the end of last group
        }
        // Move to next group
        setHighlightedIndex(0);
        setHighlightedGroupIndex(highlightedGroupIndex + 1);
      } else {
        setHighlightedIndex(highlightedIndex + 1);
      }
    } else {
      if (highlightedIndex === options.length - 1) {
        return; // At the end of options
      }
      setHighlightedIndex(highlightedIndex + 1);
    }
  }

  function highlightPreviousOption() {
    const isGroup = isOptionGroup(options);

    if (highlightedIndex === 0 && highlightedGroupIndex === 0) {
      return; // Already at start
    }

    if (isGroup) {
      if (highlightedIndex === 0) {
        // Move to previous group
        const prevGroupIndex = highlightedGroupIndex - 1;
        const prevGroup = options[prevGroupIndex];
        setHighlightedGroupIndex(prevGroupIndex);
        setHighlightedIndex(prevGroup.options.length - 1);
      } else {
        setHighlightedIndex(highlightedIndex - 1);
      }
    } else {
      setHighlightedIndex(highlightedIndex - 1);
    }
  }

  function highlightFirstOption() {
    setHighlightedIndex(0);
    setHighlightedGroupIndex(0);
  }

  function highlightLastOption() {
    const isGroup = isOptionGroup(options);

    if (!options) {
      return;
    }

    if (isGroup) {
      const lastGroupIndex = options.length - 1;
      const lastGroup = options[lastGroupIndex];
      setHighlightedGroupIndex(lastGroupIndex);
      setHighlightedIndex(lastGroup.options.length - 1);
    } else {
      setHighlightedIndex(options.length - 1);
    }
  }

  const clearHighlight = () => {
    setHighlightedIndex(
      typeof options === "undefined" || options.length ? 0 : -1,
    );
    setHighlightedGroupIndex(0);
  };

  return {
    highlightedIndex,
    highlightedGroupIndex,
    highlightPreviousOption,
    highlightNextOption,
    highlightFirstOption,
    highlightLastOption,
    clearHighlight,
  };
}
