import { overlay } from 'overlay-kit';
import { BottomSheet } from '@/shared/ui/bottom-sheets/bottom-sheet';
import {
  SelectTemplate,
  ElementType,
  RadioChangeProps,
  SelectTemplateProps,
} from '@/shared/ui/selects/select-template';
import { JSX } from 'react/jsx-runtime';

export interface SelectBottomSheetProps<T> extends SelectTemplateProps<T> {
  title?: string | JSX.Element;
  description?: string | JSX.Element;
  onClose?: () => void;
}

export const useSelectBottomSheet = <T,>() => {
  const openSelectBottomSheet = (selectBottomSheet: SelectBottomSheetProps<T>) => {
    const {
      values = [],
      labels = [],
      valueKey = undefined,
      selectedLabel = '',
      selectedValue = '',
      title = '',
      description = '',
    } = selectBottomSheet;

    const handleRadioChange = ({ event, label, value }: RadioChangeProps<ElementType<typeof values>>) => {
      selectBottomSheet?.onRadioChange?.({ event, label, value });
    };

    overlay.open(({ isOpen, close, unmount }) => {
      return (
        <BottomSheet title={title} description={description} afterLeave={unmount} open={isOpen} onClose={close}>
          <SelectTemplate
            values={values}
            valueKey={valueKey}
            labels={labels}
            selectedLabel={selectedLabel}
            selectedValue={selectedValue}
            onRadioChange={handleRadioChange}
          />
        </BottomSheet>
      );
    });
  };

  return { openSelectBottomSheet, closeBottomSheet: overlay.closeAll };
};
