import React from 'react';
import {Keyboard, View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {IconEdit, IconX} from '@tabler/icons-react-native';
import {useNavigation} from '@react-navigation/native';
import {StackNavigationProp} from '@react-navigation/stack';
import {
  Button,
  CardContainer,
  IconButton,
  RadioButton,
  SelectionCard,
  Typography,
  useNewPost,
} from '@components';
import {
  NewPostScreens,
  NewPostStackParamList,
} from '@components/_custom/NewPost/navigation';
import {useTheme} from '@shared/theme';
import {EMPTY_STRING} from '@shared/constants';

import {styles} from './styles';

function PollOptions() {
  const navigation =
    useNavigation<StackNavigationProp<NewPostStackParamList>>();
  const {t} = useTranslation();
  const {theme} = useTheme();
  const {
    setPollOptions,
    setPollConfiguration,
    setHasPoll,
    post,
    pollOptions,
    editor,
  } = useNewPost();
  const disabled = !!(
    post?.poll?.totalAnswerCount || post?._links?.requestEdit
  );

  const onDeletePoll = () => {
    setHasPoll(false);
    setPollOptions([EMPTY_STRING, EMPTY_STRING]);
    setPollConfiguration({
      endsAt: null,
      isAnonymous: true,
    });
  };

  const onEditPoll = () => {
    editor.blur();
    Keyboard.dismiss();
    setTimeout(() => {
      navigation.navigate(NewPostScreens.CreatePoll);
    }, 500);
  };

  return (
    <SelectionCard
      style={[styles.container, disabled && styles.disabled]}
      onPress={onEditPoll}
      disabled={disabled}>
      <View style={styles.header}>
        <Typography weight="semiBold" variant="m">
          {t('post.poll')}
        </Typography>
        {!(post?.id && post?.poll) && (
          <IconButton variant="flat" onPress={onDeletePoll} Icon={IconX} />
        )}
      </View>
      {pollOptions.map((item: string, index: number) => (
        <CardContainer
          key={index}
          style={{backgroundColor: theme.action.background.neutral.hover}}>
          <RadioButton
            title={item}
            checked={false}
            titleWeight="semiBold"
            disabled
          />
        </CardContainer>
      ))}
      <Button
        text={t('post.edit')}
        onPress={onEditPoll}
        disabled={disabled}
        variant="secondary"
        IconLeft={IconEdit}
      />
    </SelectionCard>
  );
}

export default PollOptions;
