import React from 'react';
import {View, LayoutAnimation} from 'react-native';
import {useTranslation} from 'react-i18next';
import {IconPlus} from '@tabler/icons-react-native';
import {Button, Typography} from '@components';
import {SetState} from '@interfaces/generic';
import {EMPTY_STRING} from '@shared/constants';
import {useTheme} from '@shared/theme';

import {styles} from './styles';
import PollOptionInput from './components/PollOptionInput';

const MAX_POLL_OPTIONS_LENGTH = 4;

interface Props {
  pollOptions: string[];
  setPollOptions: SetState<string[]>;
}

function PollOptions({pollOptions, setPollOptions}: Props) {
  const {t} = useTranslation();
  const {theme} = useTheme();
  const canRemoveOption = pollOptions.length > 2;

  const onChangePollOption = (index: number) => (newOption: string) =>
    setPollOptions(prevState =>
      prevState.map((option, optionIndex) =>
        optionIndex === index ? newOption : option,
      ),
    );

  const onRemovePollOption = (index: number) =>
    setPollOptions(prevState =>
      prevState.filter((_, optionIndex) => optionIndex !== index),
    );

  const onAddPollOption = () =>
    setPollOptions(prevState => prevState.concat([EMPTY_STRING]));

  const onRemoveOption = (index: number) => () => {
    LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
    onRemovePollOption(index);
  };

  const onAddOption = () => {
    LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
    onAddPollOption();
  };

  return (
    <View
      style={[
        styles.container,
        {backgroundColor: theme.background.elements.default},
      ]}>
      <Typography weight="semiBold" variant="m">
        {t('general.options')}
      </Typography>
      <View style={styles.gap}>
        {pollOptions.map((item: string, index: number) => (
          <PollOptionInput
            key={index}
            value={item}
            index={index}
            onChangeText={onChangePollOption(index)}
            onRemove={onRemoveOption(index)}
            canRemove={canRemoveOption}
            placeholder={`${t('post.option')} ${index + 1}`}
          />
        ))}
        {pollOptions.length < MAX_POLL_OPTIONS_LENGTH && (
          <Button
            text={t('post.add_option')}
            variant="secondary"
            IconLeft={IconPlus}
            onPress={onAddOption}
            style={styles.containerTitle}
          />
        )}
      </View>
    </View>
  );
}

export default PollOptions;
