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

import { forwardRef } from '../utils/react';
import * as css from './select.css';

/*-- Types --*/

type ListboxOptionContext = {
  active: boolean;
  selected: boolean;
  disabled: boolean;
};

type ListboxOptionProps<TValue = unknown> = {
  value: TValue;
  disabled?: boolean | undefined;
  children?:
    | React.ReactNode
    | ((context: ListboxOptionContext) => React.ReactElement);
  className?: string | ((context: ListboxOptionContext) => string);
};

export interface SelectOptionProps extends ListboxOptionProps {}

/*-- Main --*/

export const SelectOption = forwardRef<'li', SelectOptionProps>(
  function SelectOption({ className, ...rest }, ref) {
    const cn = useCallback(
      (context: ListboxOptionContext) =>
        clsx(
          typeof className === 'function' ? className(context) : className,
          css.option({ active: context.active }),
        ),
      [className],
    );

    return <Listbox.Option ref={ref} className={cn} {...rest} />;
  },
);
