import React, {useCallback} from 'react';
import {View} from 'react-native';
import {SelectionCard, Checkbox, RadioButton, Typography} from '@components';
import {Option} from '@modules/peopleExperience/interfaces';
import {useTheme} from '@shared/theme';

import {styles} from './styles';

interface Props {
  questionId: string;
  options: Option[];
  value?: Nullable<number[] | number>;
  onChangeValue: (value?: Nullable<number[] | number>) => void;
  disabled?: boolean;
  radio?: boolean;
}

function CheckboxInput({
  questionId,
  options,
  value,
  onChangeValue,
  disabled,
  radio,
}: Props) {
  const {theme} = useTheme();
  const onPress = useCallback(
    (checked: boolean, index: number) => () => {
      if (radio) {
        onChangeValue(checked ? null : index);
      } else {
        const arrayValue = (value || []) as number[];
        onChangeValue(
          checked
            ? arrayValue.filter(v => v !== index)
            : arrayValue.concat(index),
        );
      }
    },
    [onChangeValue, radio, value],
  );

  return (
    <View style={styles.gap}>
      {options.map((item, index) => {
        const checked = radio
          ? value === index
          : ((value || []) as number[]).includes(index);
        return (
          <SelectionCard
            isSelected={checked}
            key={`${questionId}-${item.id}`}
            onPress={onPress(checked, index)}
            style={styles.selectionContainer}
            disabled={disabled}>
            <View style={styles.horizontalContainer}>
              {radio ? (
                <RadioButton
                  title={item.label}
                  style={styles.flex}
                  checked={checked}
                  onPress={onPress(checked, index)}
                  disabled={disabled}
                />
              ) : (
                <Checkbox
                  style={styles.flex}
                  title={item.label}
                  checked={checked}
                  onPress={onPress(checked, index)}
                  disabled={disabled}
                />
              )}
              <Typography variant="xs" color={theme.text.neutral.lighter}>
                {item.subLabel}
              </Typography>
            </View>
          </SelectionCard>
        );
      })}
    </View>
  );
}

export default CheckboxInput;
