import { useStoreState } from "@ariakit/react-store";
import {
  useAttribute,
  useId,
  useMergeRefs,
  createElement,
  createHook,
  forwardRef,
  memo,
} from "@ariakit/react-utils";
import type { Options, Props } from "@ariakit/react-utils";
import { invariant } from "@ariakit/utils";
import type { ElementType } from "react";
import {
  useComboboxProviderContext,
  useComboboxScopedContext,
} from "./combobox-context.tsx";
import type { ComboboxStore } from "./combobox-store.ts";

const TagName = "label" satisfies ElementType;
type TagName = typeof TagName;

/**
 * Returns props to create a `ComboboxLabel` component.
 * @see https://ariakit.com/components/combobox
 * @example
 * ```jsx
 * const store = useComboboxStore();
 * const props = useComboboxLabel({ store });
 * <Role {...props}>Favorite fruit</Role>
 * <Combobox store={store} />
 * ```
 */
export const useComboboxLabel = createHook<TagName, ComboboxLabelOptions>(
  function useComboboxLabel({ store, ...props }) {
    const scopedContext = useComboboxScopedContext(true);
    const context = useComboboxProviderContext();
    store = store || context || scopedContext;

    invariant(
      store,
      process.env.NODE_ENV !== "production" &&
        "ComboboxLabel must receive a `store` prop or be wrapped in a ComboboxProvider component.",
    );

    const inputElement = useStoreState(store, "inputElement");
    useAttribute(inputElement, "id");
    const comboboxId = inputElement?.id;
    const id = useId(props.id);

    props = {
      htmlFor: comboboxId,
      ...props,
      id,
      ref: useMergeRefs(store.setLabelElement, props.ref),
    };

    return props;
  },
);

/**
 * Renders a label for the [`Combobox`](https://ariakit.com/reference/combobox)
 * component.
 * @see https://ariakit.com/components/combobox
 * @example
 * ```jsx {2}
 * <ComboboxProvider>
 *   <ComboboxLabel>Favorite fruit</ComboboxLabel>
 *   <Combobox />
 *   <ComboboxPopover>
 *     <ComboboxItem value="Apple" />
 *     <ComboboxItem value="Orange" />
 *   </ComboboxPopover>
 * </ComboboxProvider>
 * ```
 */
export const ComboboxLabel = memo(
  forwardRef(function ComboboxLabel(props: ComboboxLabelProps) {
    const htmlProps = useComboboxLabel(props);
    return createElement(TagName, htmlProps);
  }),
);

export interface ComboboxLabelOptions<
  _T extends ElementType = TagName,
> extends Options {
  /**
   * Object returned by the
   * [`useComboboxStore`](https://ariakit.com/reference/use-combobox-store)
   * hook. If not provided, the closest
   * [`ComboboxProvider`](https://ariakit.com/reference/combobox-provider)
   * component's context will be used.
   */
  store?: ComboboxStore;
}

export type ComboboxLabelProps<T extends ElementType = TagName> = Props<
  T,
  ComboboxLabelOptions<T>
>;
