import React, {useState} from 'react';
import {View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {useMutation} from 'react-query';
import {Button, CardContainer} from '@components';
import PollConfig from '@components/_custom/NewPost/screens/CreatePoll/components/PollConfig';
import {useGoBack} from '@hooks/useGoBack';
import {useSafeAreaBottomPadding} from '@hooks/useSafeAreaBottomPadding';
import {Navigation} from '@interfaces/navigation';
import {PollConfiguration} from '@modules/post/interfaces';
import {changePollEndTime} from '@modules/post/services';
import {showSnackbar} from '@redux/dispatchers';
import {useTheme} from '@shared/theme';
import {commonStyles} from '@shared/styles';
import {isBefore} from '@shared/utils';
import {Screens} from '@shared/constants';

import {styles} from './styles';

function EditEndTime({route}: Navigation<Screens.EDIT_END_TIME>) {
  const {t} = useTranslation();
  const {theme} = useTheme();
  const {goBack} = useGoBack();
  const {endsAt, groupId, postId, pollId} = route.params;
  const [pollConfiguration, setPollConfiguration] = useState<PollConfiguration>(
    {
      endsAt: endsAt ? new Date(endsAt) : null,
      isAnonymous: true,
    },
  );
  const isEndDateBeforeNow =
    !!pollConfiguration.endsAt &&
    isBefore(pollConfiguration.endsAt, new Date());
  const disabledSave = isEndDateBeforeNow;
  const paddingBottom = useSafeAreaBottomPadding();

  const changePollEndTimeMutation = useMutation(changePollEndTime, {
    onSuccess: () => {
      showSnackbar({
        title: t('new_post.post_updated'),
        variant: 'success',
      });
      goBack();
    },
  });

  const onPressSave = () => {
    changePollEndTimeMutation.mutate({
      pollId,
      postId,
      groupId,
      endsAt: pollConfiguration.endsAt,
    });
  };

  return (
    <View
      style={[
        commonStyles.flex,
        {backgroundColor: theme.background.elements.grey},
      ]}>
      <View style={styles.configContainer}>
        <PollConfig
          pollConfiguration={pollConfiguration}
          setPollConfiguration={setPollConfiguration}
          isEndDateBeforeNow={isEndDateBeforeNow}
          showVotersSwitch={false}
        />
      </View>
      <CardContainer elevation style={[styles.footer, {paddingBottom}]}>
        <Button
          text={t('general.save')}
          onPress={onPressSave}
          disabled={disabledSave || changePollEndTimeMutation.isLoading}
          isLoading={changePollEndTimeMutation.isLoading}
        />
      </CardContainer>
    </View>
  );
}

export default EditEndTime;
