import React, {useCallback, useState} from 'react';
import {ScrollView, View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {KeyboardAvoidingView} from 'react-native-keyboard-controller';
import {useNavigation} from '@react-navigation/native';
import {
  IconInfoCircle,
  IconInfoSquareRounded,
} from '@tabler/icons-react-native';
import {
  Avatar,
  Button,
  CardContainer,
  InputSearch,
  List,
  ListEmpty,
  ListRow,
  Radio,
  RadioButton,
  Spinner,
  Typography,
} from '@components';
import {useDebounce} from '@hooks/useDebounce';
import {useSafeAreaBottomPadding} from '@hooks/useSafeAreaBottomPadding';
import {IconTypes} from '@interfaces/icon';
import {Navigation} from '@interfaces/navigation';
import {UserPermissions} from '@interfaces/user';
import {SEARCH_DELAY} from '@modules/group/constants';
import {useGetGroupsToSharePost} from '@modules/group/hooks/useGetGroupsToSharePost';
import {Group} from '@modules/group/interfaces';
import {usePermission} from '@redux/selectors';
import {Screens} from '@shared/constants';
import {commonStyles} from '@shared/styles';
import {SPACING, useTheme} from '@shared/theme';
import {isAndroid} from '@shared/utils';

import {styles} from './styles';

const keyExtractor = (item: Group) => item.id.toString();

function SharePost({route}: Navigation<Screens.SHARE_POST>) {
  const {postId, groupId} = route.params;
  const {t} = useTranslation();
  const {theme} = useTheme();
  const paddingBottom = useSafeAreaBottomPadding({
    extra: isAndroid ? SPACING.x1 : 0,
  });
  const navigation = useNavigation();

  const [postInFeed, setPostInFeed] = useState(false);
  const [selectedGroup, setSelectedGroup] = useState<Nullable<Group>>(null);
  const [searchValue, setSearchValue] = useState('');
  const debouncedSearch = useDebounce(searchValue, SEARCH_DELAY);

  const canPostInFeed = usePermission(UserPermissions.CREATE_POSTS);

  const {
    data: groups = [],
    isLoading,
    isFetchingNextPage,
    hasNextPage,
    getNextPage,
  } = useGetGroupsToSharePost({search: debouncedSearch});

  const continueDisabled = !postInFeed && !selectedGroup;

  const togglePostInFeed = useCallback(() => {
    setPostInFeed(prev => !prev);
    setSelectedGroup(null);
  }, []);

  const onSelectGroup = useCallback(
    (group: Group) => () => {
      setSelectedGroup(group);
      setPostInFeed(false);
    },
    [],
  );

  const onContinue = useCallback(() => {
    if (postInFeed) {
      navigation.navigate(Screens.PUBLISH_POST, {
        sharedPostId: postId,
        sharedGroupId: groupId,
      });
    } else if (selectedGroup) {
      navigation.navigate(Screens.PUBLISH_GROUP_POST, {
        groupId: selectedGroup.id,
        sharedPostId: postId,
        sharedGroupId: groupId,
      });
    }
  }, [navigation, postInFeed, selectedGroup, postId, groupId]);

  const renderItem = useCallback(
    ({item}: {item: Group}) => {
      const isEmoji = item.icon?.type === IconTypes.EMOJI;
      const avatarProps = isEmoji
        ? {emoji: item.icon.value}
        : {url: item.icon?.value};

      return (
        <ListRow style={styles.listRow} onPress={onSelectGroup(item)}>
          <Radio
            checked={selectedGroup?.id === item.id}
            onPress={onSelectGroup(item)}
          />
          <ListRow.Avatar {...avatarProps} />
          <ListRow.Title title={item.title} />
        </ListRow>
      );
    },
    [onSelectGroup, selectedGroup],
  );

  const hasGroups = groups.length > 0;
  const showEmpty =
    !canPostInFeed && !hasGroups && !isLoading && !debouncedSearch;

  return (
    <View
      style={[
        commonStyles.flex,
        {backgroundColor: theme.background.layout.default},
      ]}>
      <KeyboardAvoidingView style={commonStyles.flex} behavior="padding">
        <ScrollView
          contentContainerStyle={styles.scrollContent}
          keyboardShouldPersistTaps="handled">
          <Typography variant="m" weight="semiBold">
            {t('communication.drafts_for_review.target')}
          </Typography>
          <Typography>{t('post.share_destination_subtitle')}</Typography>

          {showEmpty && (
            <ListEmpty
              IconComponent={<Avatar Icon={IconInfoCircle} variant="primary" />}
              title={t('communication.drafts_for_review.no_target_title')}
            />
          )}

          {canPostInFeed && (
            <CardContainer style={styles.cardContainer}>
              <RadioButton
                checked={postInFeed}
                onPress={togglePostInFeed}
                title={t('post.share_destination_feed_wall')}
              />
            </CardContainer>
          )}

          <CardContainer style={styles.cardContainer}>
            <InputSearch
              value={searchValue}
              onChangeText={setSearchValue}
              placeholder={t('post.share_destination_search_group')}
            />
            {isLoading && !hasGroups ? (
              <View style={styles.spinnerContainer}>
                <Spinner />
              </View>
            ) : (
              <List
                scrollEnabled={false}
                data={groups}
                keyExtractor={keyExtractor}
                renderItem={renderItem}
                style={styles.listContainer}
                onNextPage={getNextPage}
                hasNextPage={hasNextPage}
                isFetchingNextPage={isFetchingNextPage}
                withRefresh={false}
                titleEmptyList={t('post.share_destination_no_results')}
                IconEmptyList={
                  <Avatar Icon={IconInfoSquareRounded} size="lg" />
                }
              />
            )}
          </CardContainer>
        </ScrollView>
        <View
          style={[
            styles.footer,
            {
              backgroundColor: theme.background.elements.default,
              paddingBottom,
              shadowColor: theme.background.layout.inverted,
            },
          ]}>
          <Button
            text={t('general.continue')}
            onPress={onContinue}
            disabled={continueDisabled}
          />
        </View>
      </KeyboardAvoidingView>
    </View>
  );
}

export default SharePost;
