import React, {useCallback, useState} from 'react';
import {View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {
  KeyboardAwareScrollView,
  KeyboardStickyView,
  useKeyboardController,
} from 'react-native-keyboard-controller';
import {useFocusEffect, useNavigation} from '@react-navigation/native';
import {NativeStackNavigationProp} from '@react-navigation/native-stack';
import {StackNavigationProp} from '@react-navigation/stack';
import {IconX} from '@tabler/icons-react-native';
import {Button, CardContainer, IconButton, Typography} from '@components';
import {useNewPost} from '@components/_custom/NewPost/hooks/useNewPost';
import {
  NewPostScreens,
  NewPostStackParamList,
} from '@components/_custom/NewPost/navigation';
import {useSafeAreaBottomPadding} from '@hooks/useSafeAreaBottomPadding';
import {PollConfiguration} from '@modules/post/interfaces';
import {SPACING, useTheme} from '@shared/theme';
import {commonStyles} from '@shared/styles';
import {isAndroid, isBefore} from '@shared/utils';

import PollOptions from './components/PollOptions';
import PollConfig from './components/PollConfig';
import {styles} from './styles';

const BOTTOM_OFFSET = isAndroid ? 120 : 140;

type NavigationProp = StackNavigationProp<
  NewPostStackParamList,
  NewPostScreens.CreatePoll
>;

function CreatePoll() {
  const {t} = useTranslation();
  const {theme} = useTheme();
  const navigation = useNavigation<NavigationProp>();
  const {
    pollOptions: contextPollOptions,
    setPollOptions: setContextPollOptions,
    pollConfiguration: {endsAt, isAnonymous},
    setPollConfiguration: setContextPollConfiguration,
    setHasPoll,
  } = useNewPost();
  const [pollOptions, setPollOptions] = useState<string[]>(contextPollOptions);
  const [pollConfiguration, setPollConfiguration] = useState<PollConfiguration>(
    {
      endsAt: endsAt ? new Date(endsAt) : null,
      isAnonymous,
    },
  );
  const isEndDateBeforeNow =
    !!pollConfiguration.endsAt &&
    isBefore(pollConfiguration.endsAt, new Date());
  const disabledSave =
    pollOptions.some(option => !option) || isEndDateBeforeNow;
  const paddingBottom = useSafeAreaBottomPadding();

  const keyboardController = useKeyboardController();

  // This is because PublishPost screen disables keyboardController when navigating to this screen on Android
  useFocusEffect(
    useCallback(() => {
      if (isAndroid) {
        setTimeout(() => {
          keyboardController.setEnabled(true);
        }, 1000);
      }
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []),
  );

  const onPressSave = () => {
    setHasPoll(true);
    setContextPollOptions(pollOptions);
    setContextPollConfiguration(pollConfiguration);
    navigation.goBack();
  };

  return (
    <View
      style={[
        commonStyles.flex,
        {backgroundColor: theme.background.elements.grey},
      ]}>
      <KeyboardAwareScrollView
        keyboardShouldPersistTaps="handled"
        bottomOffset={BOTTOM_OFFSET}
        contentContainerStyle={styles.scrollView}>
        <PollOptions
          pollOptions={pollOptions}
          setPollOptions={setPollOptions}
        />
        <PollConfig
          pollConfiguration={pollConfiguration}
          setPollConfiguration={setPollConfiguration}
          isEndDateBeforeNow={isEndDateBeforeNow}
        />
      </KeyboardAwareScrollView>
      <KeyboardStickyView
        offset={{
          closed: 0,
          opened: paddingBottom - SPACING.x2,
        }}>
        <CardContainer elevation style={[styles.footer, {paddingBottom}]}>
          <Button
            text={t('general.save')}
            onPress={onPressSave}
            disabled={disabledSave}
          />
        </CardContainer>
      </KeyboardStickyView>
    </View>
  );
}

const HeaderRight = ({
  navigation,
}: {
  navigation: NativeStackNavigationProp<
    NewPostStackParamList,
    NewPostScreens.CreatePoll
  >;
}) => (
  <IconButton variant="tertiary" Icon={IconX} onPress={navigation.goBack} />
);

const HeaderTitle = () => {
  const {t} = useTranslation();
  return <Typography weight="semiBold">{t('screens.CreatePoll')}</Typography>;
};

CreatePoll.HeaderRight = HeaderRight;
CreatePoll.HeaderTitle = HeaderTitle;

export default CreatePoll;
