'use client';

import { useMemo } from 'react';
import {
  OptionProps,
  GroupBase,
  components as ReactSelectComponents,
} from 'react-select';
import SelectInput, { OptionType, SelectInputProps } from './SelectInput';
import { cn } from '@/lib/helper';

interface SelectInputCheckboxProps<T = OptionType>
  extends Omit<
    SelectInputProps<T>,
    'closeMenuOnSelect' | 'hideSelectedOptions' | 'optionComponent'
  > {
  closeMenuOnSelect?: boolean;
  hideSelectedOptions?: boolean;
}

const CheckboxOption = <
  T extends OptionType,
  IsMulti extends boolean,
  Group extends GroupBase<T>,
>(
  props: OptionProps<T, IsMulti, Group>
) => {
  const { isSelected, label, innerRef, innerProps, className } = props;

  return (
    <div
      ref={innerRef}
      {...innerProps}
      className={cn(
        'flex items-center gap-2 px-3 py-2 cursor-pointer',
        className
      )}
    >
      <input
        type='checkbox'
        checked={isSelected}
        onChange={() => null}
        className='checkbox checkbox-sm checkbox-primary pointer-events-none'
      />
      <label className='cursor-pointer flex-1 select-none'>{label}</label>
    </div>
  );
};

const SelectInputCheckbox = <T extends OptionType>(
  props: SelectInputCheckboxProps<T>
) => {
  const {
    closeMenuOnSelect = false,
    hideSelectedOptions = false,
    isMulti = true,
    className,
    ...restProps
  } = props;

  const customComponents = useMemo(() => {
    return {
      Option: CheckboxOption as typeof ReactSelectComponents.Option,
    };
  }, []);

  return (
    <SelectInput<T>
      {...restProps}
      isMulti={isMulti}
      closeMenuOnSelect={closeMenuOnSelect}
      hideSelectedOptions={hideSelectedOptions}
      className={{
        ...className,
        select: cn(className?.select, 'select-checkbox'),
      }}
      components={customComponents}
    />
  );
};

export default SelectInputCheckbox;
