import React, { useMemo } from 'react';
import { Listbox } from '@headlessui/react';

import { forwardRef } from '../utils/react';
import { FieldLabel } from '../field-label';

/*-- Types --*/

type ListboxLabelContext = {
  open: boolean;
  disabled: boolean;
};

type ListboxLabelProps = {
  children?:
    | React.ReactNode
    | ((context: ListboxLabelContext) => React.ReactElement);
  className?: string | ((context: ListboxLabelContext) => string);
};

export interface SelectLabelProps extends ListboxLabelProps {}

/*-- Main --*/

export const SelectLabel = forwardRef<typeof FieldLabel, SelectLabelProps>(
  function SelectLabel({ as, ...rest }, ref) {
    const WrappedFieldLabel = useMemo(
      () =>
        React.forwardRef(function WrappedFieldLabel(props: any, ref) {
          return <FieldLabel ref={ref} {...props} as={as} />;
        }),
      [as],
    );

    return <Listbox.Label ref={ref} as={WrappedFieldLabel} {...rest} />;
  },
);
