import React, {useCallback, useEffect, useMemo} from 'react';
import {FlatList, ListRenderItem, RefreshControl, View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import {IconChecks} from '@tabler/icons-react-native';
import {NativeStackScreenProps} from '@react-navigation/native-stack';
import {useNetInfo} from '@react-native-community/netinfo';
import {Divider, Skeleton, StateCard, Typography} from '@components';
import {MessageInfoReadState} from '@modules/chats/interfaces';
import {useGetMessageInfo} from '@modules/chats/hooks';
import {CHAT_MESSAGE_HEADER_HEIGHT} from '@modules/chats/constants';
import {RootStackParamList} from '@navigation/interfaces';
import {SPACING, useTheme} from '@shared/theme';
import {logAmplitudeEvent} from '@shared/utils';
import {AMPLITUDE_EVENTS, Screens} from '@shared/constants';

import {Header} from './components/Header';
import {Message, ThreeDotsView} from './components';
import ListUserItem from './components/ListUserItem';
import {SKELETON_WIDTH, styles} from './styles';
import {LIST_ITEM_HEIGHT} from './constants';

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

const getChatItemLayout = (_data: unknown, index: number) => {
  return {
    length: LIST_ITEM_HEIGHT,
    offset: LIST_ITEM_HEIGHT * index,
    index,
  };
};

const CustomDivider = () => <Divider style={styles.divider} />;

export function ChatMessageInfo({
  navigation,
  route: {
    params: {message},
  },
}: NativeStackScreenProps<RootStackParamList, Screens.CHAT_MESSAGE_INFO>) {
  const {t} = useTranslation();
  const {top, bottom} = useSafeAreaInsets();
  const {theme, spacing} = useTheme();
  const {
    readList,
    isLoading,
    isFetchingNextPage,
    getNextPage,
    isPendingReads,
    isRefreshing,
    refresh,
  } = useGetMessageInfo({
    messageTs: message?.data.ts,
    channel: message?.data.channel,
  });

  const {isInternetReachable} = useNetInfo();
  const renderItem: ListRenderItem<MessageInfoReadState | {id: 'pending'}> =
    useCallback(
      ({item, index}) => {
        const isFirst = index === 0;
        const isLast = index === readList.length - 1 && !isPendingReads;
        return (
          <ListUserItem
            item={item as MessageInfoReadState}
            first={isFirst}
            last={isLast}
          />
        );
      },
      [readList.length, isPendingReads],
    );

  const ListHeaderComponent = useMemo(() => {
    return (
      <View>
        {!!message && <Message message={message} />}
        <View
          style={[
            styles.listHeader,
            {borderTopColor: theme.border.neutral.default},
          ]}>
          <IconChecks size={16} color={theme.brand[400]} />
          <Typography variant="xs" weight="semiBold">
            {t('chat.message_info.read_by')}
          </Typography>
        </View>
      </View>
    );
  }, [message, t, theme]);

  const contentContainerStyle = useMemo(() => {
    return {
      paddingBottom: bottom + CHAT_MESSAGE_HEADER_HEIGHT + top + SPACING.x2,
    };
  }, [bottom, top]);

  useEffect(() => {
    if (message) {
      logAmplitudeEvent(AMPLITUDE_EVENTS.CHATS_2_MESSAGE_INFO_OPENED, {
        conversationId: message.data.channel,
        conversationType: 'channel',
        messageType: message.extendedType,
        messageId: message.id,
      });
    }

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const hasLoadedData = readList.length > 0;
  return (
    <View
      style={[
        styles.container,
        {
          backgroundColor: theme.background.layout.tertiary,
          paddingTop: top,
        },
      ]}>
      <Header />
      <View
        style={[
          styles.content,
          {backgroundColor: theme.background.layout.default},
        ]}>
        <View
          style={[
            styles.listContainer,
            {borderTopColor: theme.border.neutral.default},
          ]}>
          {!isInternetReachable ? (
            <View style={styles.noInternetContainer}>
              <StateCard
                variant="wifi-off"
                title={t('ats.common.error_internet.title')}
                description={t('ats.common.error_internet.description')}>
                <StateCard.Footer>
                  <StateCard.Button
                    variant="secondary"
                    text={t('general.close')}
                    onPress={navigation.goBack}
                  />
                </StateCard.Footer>
              </StateCard>
            </View>
          ) : (
            <FlatList
              data={readList}
              renderItem={renderItem}
              keyExtractor={keyExtractor}
              getItemLayout={getChatItemLayout}
              contentContainerStyle={contentContainerStyle}
              ListFooterComponent={
                isFetchingNextPage || isLoading ? (
                  <View
                    style={[
                      styles.skeletonContainer,
                      hasLoadedData
                        ? styles.skeletonContainerData
                        : styles.skeletonContainerNoData,
                      {
                        backgroundColor: theme.background.layout.tertiary,
                        borderColor: theme.border.neutral.default,
                      },
                    ]}>
                    <Skeleton>
                      <Skeleton.Item
                        width={SKELETON_WIDTH}
                        height={spacing.x3}
                      />
                    </Skeleton>
                  </View>
                ) : isPendingReads ? (
                  <ThreeDotsView isFirst={!readList.length} />
                ) : null
              }
              ItemSeparatorComponent={CustomDivider}
              onEndReached={getNextPage}
              onEndReachedThreshold={0.5}
              refreshControl={
                <RefreshControl refreshing={isRefreshing} onRefresh={refresh} />
              }
              ListHeaderComponent={ListHeaderComponent}
            />
          )}
        </View>
      </View>
    </View>
  );
}
