import React, {memo, useCallback, useEffect, useMemo, useState} from 'react';
import {Pressable, View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {SafeAreaView} from 'react-native-safe-area-context';
import {useNavigation} from '@react-navigation/native';
import {IconArrowLeft, IconUsersGroup} from '@tabler/icons-react-native';
import {StackNavigationProp} from '@react-navigation/stack';
import {
  Typography,
  Button,
  RenderSceneProps,
  Tabs,
  Tooltip,
  Footer,
  NewPostScreens,
  NewPostStackParamList,
} from '@components';
import {useQueryFetchIfEmpty} from '@hooks/queries/useQueryFetchIfEmpty';
import {getSegmentationGroups} from '@services/segmentation';
import {useTheme} from '@shared/theme';

import {useNewPost} from '../../hooks/useNewPost';
import {styles} from './styles';
import SelectedGroups from './components/SelectedGroups';
import SegmentationGroups from './components/SegmentationGroups';
import SegmentationUsers from './components/SegmentationUsers';
import {useGetSegmentationUsersCount} from '../../hooks/useGetSegmentationUsersCount';
import {newPostQueryKeys} from '../../constants';

function SegmentationScreen() {
  const {segmentationItemIds, setSegmentationItemIds} = useNewPost();
  const {t} = useTranslation();
  const {theme, iconSizes} = useTheme();
  const navigation =
    useNavigation<StackNavigationProp<NewPostStackParamList>>();
  const [selectedSegmentationItemIds, setSelectedSegmentationItemIds] =
    useState<number[]>(segmentationItemIds);

  const usersCount = useGetSegmentationUsersCount({
    selectedSegmentationItemIds,
  });

  useEffect(() => {
    const headerRight = () => (
      <View style={styles.headerRight}>
        <Button onPress={navigation.goBack} text={t('new_post.accept')} />
      </View>
    );

    navigation.setOptions({headerRight, headerTitle: ''});
  }, [navigation, t]);

  const routes = useMemo(
    () => [
      {key: 'GROUPS', label: t('new_post.groups')},
      {key: 'USERS', label: t('new_post.users')},
    ],
    [t],
  );

  const onToggleItem = useCallback((item: number) => {
    setSelectedSegmentationItemIds(prev => {
      const itemIsSelected = prev.some(i => i === item);
      if (itemIsSelected) {
        return prev.filter(i => i !== item);
      }
      return [...prev, item];
    });
  }, []);

  const {data: segmentationItems, isLoading: isLoadingGroups} =
    useQueryFetchIfEmpty(newPostQueryKeys.segmentationGroups, () =>
      getSegmentationGroups(),
    );

  const renderScene = useCallback(
    (props: RenderSceneProps) => {
      switch (props.route.key) {
        case 'GROUPS':
          return (
            <SegmentationGroups
              selectedSegmentationItemIds={selectedSegmentationItemIds}
              onToggleItem={onToggleItem}
              segmentationItems={segmentationItems || []}
              isLoading={isLoadingGroups}
            />
          );
        case 'USERS':
          return (
            <SegmentationUsers
              selectedSegmentationItemIds={selectedSegmentationItemIds}
            />
          );
      }
    },
    [
      isLoadingGroups,
      onToggleItem,
      segmentationItems,
      selectedSegmentationItemIds,
    ],
  );

  const onAccept = () => {
    setSegmentationItemIds(selectedSegmentationItemIds);
    navigation.navigate(NewPostScreens.NewPostMain);
  };

  const selectedSegmentationItems = useMemo(() => {
    return selectedSegmentationItemIds.map(id => ({
      id,
      name:
        segmentationItems
          ?.flatMap(group => group.items || [])
          .find(item => item.id === id)?.name || '',
    }));
  }, [selectedSegmentationItemIds, segmentationItems]);

  return (
    <SafeAreaView
      style={[
        styles.container,
        {backgroundColor: theme.background.elements.default},
      ]}>
      <View
        style={[
          styles.headerContainer,
          {
            borderBottomColor: theme.border.neutral.default,
            backgroundColor: theme.background.elements.default,
          },
        ]}>
        <Pressable onPress={navigation.goBack}>
          <IconArrowLeft
            color={theme.text.neutral.default}
            size={iconSizes.x6}
          />
        </Pressable>
        <Typography>{t('new_post.segmentation')}</Typography>
        <View style={styles.headerRight} />
      </View>
      <View style={styles.scopeContainer}>
        <IconUsersGroup
          color={theme.text.neutral.default}
          size={iconSizes.x6}
        />
        <Typography>{`${t('new_post.scope', {
          count: usersCount || 0,
        })}`}</Typography>
        <Tooltip info={t('new_post.segmentation_tooltip')} />
      </View>
      <SelectedGroups
        selectedSegmentationItems={selectedSegmentationItems}
        onToggleItem={onToggleItem}
      />
      <View style={styles.tabsContainer}>
        <Tabs routes={routes} renderScene={renderScene} />
      </View>
      <Footer>
        <Button onPress={onAccept} text={t('new_post.accept')} />
      </Footer>
    </SafeAreaView>
  );
}

export default memo(SegmentationScreen);
