import { JoinOperator } from '@composed-components/ConditionLine/types';
import MenuList from '@composed-components/MenuList';
import Button from '@design-system/Buttons/Button';
import { IconChevronDown } from '@tabler/icons-react';

import { type JoinSelectorProps } from './types';

const JoinSelector = ({
  disabled,
  title,
  options,
  value = JoinOperator.AND,
  readOnly,
  onChange,
  slotProps,
}: JoinSelectorProps) => {
  const mappedOptions = options.map(option => ({
    title: option.label,
    value: option.value,
    onClick: () => onChange(option),
  }));

  const selectedOption = mappedOptions.find(option => option.value === value);

  return (
    <MenuList
      disableMenu={disabled || readOnly}
      options={mappedOptions}
      {...slotProps?.menuList}
      customButton={
        <Button
          variant={readOnly ? 'tertiary' : 'secondary'}
          endIcon={readOnly ? undefined : <IconChevronDown size={16} />}
          {...slotProps?.button}
          sx={{
            minWidth: '0',
            ...(readOnly && {
              '&:disabled': {
                color: theme => theme.palette.new.text.neutral.brand,
              },
            }),
            ...slotProps?.button?.sx,
          }}
        >
          {title || selectedOption?.title}
        </Button>
      }
    />
  );
};

export type { JoinSelectorProps };

export default JoinSelector;
