import React, {useCallback, useMemo} from 'react';
import {View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import {IconPlus} from '@tabler/icons-react-native';
import {RenderSceneProps, Tabs, Typography} from '@components';
import {useCursorInfinityQuery} from '@hooks/queries/useCursorInfinityQuery';
import {Navigation} from '@interfaces/navigation';
import {Footer} from '@modules/drafts/components/Footer';
import {getAvailableAuthors} from '@modules/drafts/services';
import {DRAFT_QUERY_KEYS} from '@modules/drafts/constants';
import {AuthorType} from '@modules/drafts/interfaces';
import {REDUCED_LIMIT} from '@services/constants';
import {useTheme} from '@shared/theme';
import {commonStyles} from '@shared/styles';
import {Screens} from '@shared/constants';

import SearchPosts from './components/SearchPosts';
import {styles} from './styles';

function DraftsWrapper({navigation}: Navigation<Screens.DRAFTS>) {
  const {t} = useTranslation();
  const {theme} = useTheme();
  const {bottom} = useSafeAreaInsets();

  const forCreationQuery = useCursorInfinityQuery({
    queryKey: DRAFT_QUERY_KEYS.authors(AuthorType.FOR_CREATION),
    queryFn: ({cursor}) =>
      getAvailableAuthors({
        limit: REDUCED_LIMIT,
        cursor,
      }),
  });

  const asEndUserQuery = useCursorInfinityQuery({
    queryKey: DRAFT_QUERY_KEYS.authors(AuthorType.AS_END_USER),
    queryFn: ({cursor}) =>
      getAvailableAuthors(
        {
          limit: REDUCED_LIMIT,
          cursor,
        },
        AuthorType.AS_END_USER,
      ),
  });

  const routes = useMemo(
    () =>
      [
        {key: 'OTHERS', label: t('drafts.main.for_others')},
        {key: 'FOR_ME', label: t('drafts.main.for_me')},
      ].filter(Boolean),
    [t],
  );

  const renderScene = useCallback((props: RenderSceneProps) => {
    switch (props.route.key) {
      case 'OTHERS':
        return <SearchPosts mine />;
      case 'FOR_ME':
        return <SearchPosts />;
    }
  }, []);

  const onCreate = () => navigation.navigate(Screens.NEW_DRAFT);

  const Component = useMemo(() => {
    if (forCreationQuery.data?.length && asEndUserQuery.data?.length) {
      return (
        <View style={styles.tabsContainer}>
          <Tabs routes={routes} renderScene={renderScene} />
        </View>
      );
    }

    if (forCreationQuery.data?.length && !asEndUserQuery.data?.length) {
      return (
        <>
          <View
            style={[
              styles.titleContainer,
              {backgroundColor: theme.background.elements.grey},
            ]}>
            <Typography weight="semiBold" variant="l">
              {t('drafts.main.for_others')}
            </Typography>
          </View>
          <SearchPosts mine />
        </>
      );
    }

    return (
      <>
        <View
          style={[
            styles.titleContainer,
            {backgroundColor: theme.background.elements.grey},
          ]}>
          <Typography weight="semiBold" variant="l">
            {t('drafts.main.for_me')}
          </Typography>
        </View>
        <SearchPosts />
      </>
    );
  }, [
    asEndUserQuery.data?.length,
    forCreationQuery.data?.length,
    renderScene,
    routes,
    t,
    theme.background.elements.grey,
  ]);

  return (
    <View
      style={[
        commonStyles.flex,
        {
          backgroundColor: theme.background.elements.default,
          paddingBottom: bottom,
        },
      ]}>
      {Component}
      {!!forCreationQuery?.data?.length && (
        <Footer
          primary={{
            onSubmit: onCreate,
            label: t('drafts.main.create_draft'),
            icon: IconPlus,
          }}
        />
      )}
    </View>
  );
}

export default DraftsWrapper;
