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

import { ScrollArea, ScrollAreaProps } from '../scroll-area';
import { forwardRef } from '../utils/react';
import * as css from './select.css';

/*-- Types --*/

type ListboxOptionsContext = {
  open: boolean;
};

type ListboxOptionsProps = {
  children?:
    | React.ReactNode
    | ((context: ListboxOptionsContext) => React.ReactElement);
  className?: string | ((context: ListboxOptionsContext) => string);
} & (
  | ({ static?: undefined } & { unmount?: boolean | undefined })
  | ({ unmount?: undefined } & { static?: boolean | undefined })
);

export type SelectOptionsProps = ListboxOptionsProps;

/*-- Main --*/

const UlScrollArea = forwardRef<'ul', ScrollAreaProps>(
  ({ as = 'ul', ...rest }, ref) => <ScrollArea ref={ref} as={as} {...rest} />,
);

export const SelectOptions = forwardRef<'ul', SelectOptionsProps>(
  function SelectOptions({ className, unmount, ...rest }, ref) {
    const cn = clsx(className, css.options);

    return (
      <Listbox.Options
        as={UlScrollArea}
        ref={ref}
        className={cn}
        unmount={unmount as undefined}
        {...rest}
      />
    );
  },
);
