import React, {useEffect, useState} from 'react';
import {View, Animated} from 'react-native';
import {IconTrash} from '@tabler/icons-react-native';
import {IconButton, Typography, CardContainer, TextInput} from '@components';
import {useTheme} from '@shared/theme';

import {styles} from './styles';

const POLL_ITEM_MAX_LENGTH = 100;
const MIN_POLL_OPTIONS_LENGTH = 2;
interface PollOptionInputProps {
  value: string;
  index: number;
  onChangeText: (text: string) => void;
  onRemove: () => void;
  canRemove?: boolean;
  placeholder: string;
  disabled?: boolean;
}

function PollOptionInput({
  value,
  index,
  onChangeText,
  onRemove,
  canRemove,
  placeholder,
  disabled,
}: PollOptionInputProps) {
  const {theme} = useTheme();
  const [isFocused, setIsFocused] = useState(false);
  const [opacityAnim] = useState(new Animated.Value(0));

  useEffect(() => {
    Animated.timing(opacityAnim, {
      toValue: isFocused ? 1 : 0,
      duration: 200,
      useNativeDriver: true,
    }).start();
  }, [isFocused, opacityAnim]);

  const onFocus = () => setIsFocused(true);
  const onBlur = () => setIsFocused(false);

  return (
    <View style={styles.optionContainer}>
      <CardContainer
        style={[
          styles.inputContainer,
          isFocused && {borderColor: theme.brand[500]},
        ]}>
        <TextInput
          onFocus={onFocus}
          onBlur={onBlur}
          editable={!disabled}
          onChangeText={onChangeText}
          style={styles.input}
          placeholder={placeholder}
          value={value}
          maxLength={POLL_ITEM_MAX_LENGTH}
          autoCorrect
          autoCapitalize="none"
          multiline
        />
        {(canRemove || index >= MIN_POLL_OPTIONS_LENGTH) && (
          <IconButton
            variant="flat"
            Icon={IconTrash}
            onPress={onRemove}
            disabled={disabled}
          />
        )}
      </CardContainer>

      <Animated.View style={{opacity: opacityAnim}}>
        <Typography
          align="right"
          variant="s"
          color={theme.text.neutral.lighter}>
          {`${value.length}/${POLL_ITEM_MAX_LENGTH}`}
        </Typography>
      </Animated.View>
    </View>
  );
}

export default PollOptionInput;
