'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 SelectInputRadioProps<T = OptionType>
  extends Omit<SelectInputProps<T>, 'closeMenuOnSelect' | 'optionComponent'> {
  closeMenuOnSelect?: boolean;
}

const RadioOption = <
  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='radio'
        checked={isSelected}
        onChange={() => null}
        className='radio radio-md radio-primary pointer-events-none'
      />

      <label className='cursor-pointer flex-1 select-none text-sm text-base-content/50 font-medium'>
        {label}
      </label>
    </div>
  );
};

const SelectInputRadio = <T extends OptionType>(
  props: SelectInputRadioProps<T>
) => {
  const { closeMenuOnSelect = true, className, ...restProps } = props;

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

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

export default SelectInputRadio;
