'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, isFocused } =
    props;

  return (
    <div
      ref={innerRef}
      {...innerProps}
      className={cn(
        'flex items-center gap-3 p-3 cursor-pointer transition-all hover:bg-primary/5',
        {
          'bg-primary/5': isFocused,
        },
        className
      )}
    >
      <input
        type='checkbox'
        checked={isSelected}
        onChange={() => null}
        className='checkbox checkbox-sm rounded-md checkbox-primary pointer-events-none border-base-content/10'
      />

      <label className='cursor-pointer flex-1 select-none text-sm text-base-content/50 font-medium'>
        {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;
