import React, {useState, useCallback, useMemo} from 'react';
import {
  GestureResponderEvent,
  Linking,
  ListRenderItem,
  ScrollView,
  View,
} from 'react-native';
import {useTranslation} from 'react-i18next';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import {
  Attachment,
  ChipListItem,
  Chips,
  List,
  ListItem,
  Spinner,
  Typography,
  Image,
  HtmlRender,
  FileAndAttachment,
  WebView,
  normalizeAspectRatioEmbedStylesInHtml,
  Title,
} from '@components';
import {useBackHandler} from '@hooks/useBackHandler';
import {useGoBack} from '@hooks/useGoBack';
import {useTimeInScreen} from '@hooks/useTimeInScreen';
import {Navigation} from '@interfaces/navigation';
import {IconTypes} from '@interfaces/icon';
import {LibraryChildren} from '@modules/libraries/interfaces';
import {KnowledgeLibrarySk} from '@modules/libraries/skeletons/KnowledgeLibrarySk';
import {SPACING, useTheme} from '@shared/theme';
import {AMPLITUDE_EVENTS, Screens, windowDimensions} from '@shared/constants';
import {getFullDate, handleFileView, logAmplitudeEvent} from '@shared/utils';

import {styles} from './styles';
import {useFetchLibrary} from './hooks/useFetchLibrary';
import KnowledgeLibraryHeader from './components/KnowledgeLibraryHeader';

export function KnowledgeLibrary({
  navigation,
  route: {
    params: {id, childId},
  },
}: Navigation<Screens.KNOWLEDGE_LIBRARY>) {
  const libraryId = childId ?? id;
  const {t} = useTranslation();
  const {goBack} = useGoBack();
  const {bottom: paddingBottom} = useSafeAreaInsets();
  const [isFileLoading, setIsFileLoading] = useState(false);
  const {knowledgeLibrary, isLoading} = useFetchLibrary(libraryId);
  const [webViewUrl, setWebViewURL] = useState('');
  const [selectedChip, setSelectedChip] = useState(1);
  const hasUrl = webViewUrl.length;
  const {theme} = useTheme();
  const isSubpagesSelected = selectedChip === 2;
  const lastItemIndex = (knowledgeLibrary?.children.length || 0) - 1;

  const chipList: ChipListItem[] = useMemo(() => {
    return knowledgeLibrary?.children.length && knowledgeLibrary.body
      ? [
          {id: 1, label: t('libraries.general')},
          {id: 2, label: t('libraries.subpages')},
        ]
      : [];
  }, [knowledgeLibrary, t]);

  useTimeInScreen(
    AMPLITUDE_EVENTS.WIDGET_LIBRARY_VIEW,
    {
      widgetId: libraryId,
      parentId: knowledgeLibrary?.parentId,
      name: knowledgeLibrary?.title,
    },
    !!knowledgeLibrary,
  );

  const html = useMemo(() => {
    return normalizeAspectRatioEmbedStylesInHtml(knowledgeLibrary?.body || '');
  }, [knowledgeLibrary?.body]);

  const onClose = useCallback(() => {
    if (hasUrl) {
      setWebViewURL('');
    } else {
      goBack();
    }
    return true;
  }, [hasUrl, goBack]);

  const onLinkPress = async (_: GestureResponderEvent, href: string) => {
    if (await Linking.canOpenURL(href)) {
      setWebViewURL(href);
    }
  };

  useBackHandler(onClose);

  const renderAttachment = (attachment: FileAndAttachment) => {
    const seeAttachment = () => {
      logAmplitudeEvent(AMPLITUDE_EVENTS.WIDGET_LIBRARY_ATTACHMENT_DOWNLOAD, {
        widgetId: libraryId,
        parentId: knowledgeLibrary?.parentId,
        name: knowledgeLibrary?.title,
        fileType: attachment.type,
        fileName: attachment.name,
      });
      handleFileView(attachment, currentName =>
        setIsFileLoading(!!currentName.length),
      );
    };
    return (
      <Attachment key={attachment.id} {...attachment} onPress={seeAttachment} />
    );
  };

  const renderItem: ListRenderItem<LibraryChildren> = ({item, index}) => {
    const onChildrenPress = () =>
      navigation.push(Screens.KNOWLEDGE_LIBRARY, {id: item.id});
    return (
      <ListItem
        onItemPress={onChildrenPress}
        backgroundColor={theme.background.layout.default}
        title={item.title}
        withRightIcon
        avatar={{
          rounded: false,
          ...(item.icon.type === IconTypes.IMAGE
            ? {size: 'sm', url: item.icon.value}
            : {emoji: item.icon.value}),
        }}
        presentation="card"
        isFirstItem={index === 0}
        isLastItem={index === lastItemIndex}
      />
    );
  };

  return (
    <>
      <View
        style={[
          styles.container,
          {backgroundColor: theme.background.layout.default},
        ]}>
        <KnowledgeLibraryHeader
          title={knowledgeLibrary?.title.trim()}
          hasUrl={hasUrl}
          onClose={onClose}
        />
        {hasUrl ? (
          <WebView source={{uri: webViewUrl}} style={styles.content} />
        ) : isLoading ? (
          <KnowledgeLibrarySk />
        ) : (
          <ScrollView
            showsVerticalScrollIndicator={false}
            contentContainerStyle={[
              styles.content,
              {backgroundColor: theme.background.layout.default, paddingBottom},
            ]}>
            {!!knowledgeLibrary?.coverPicture && (
              <Image
                source={{uri: knowledgeLibrary.coverPicture}}
                style={styles.coverPicture}
                enableCache
              />
            )}
            {!!chipList.length && (
              <Chips
                list={chipList}
                selected={selectedChip}
                onItemPress={setSelectedChip}
                style={[
                  styles.body,
                  !knowledgeLibrary?.coverPicture && styles.noImage,
                ]}
              />
            )}
            <Title
              size="l"
              style={[styles.title, !chipList.length && styles.noChipsTitle]}
              title={knowledgeLibrary?.title.trim()}
              {...(knowledgeLibrary?.showUpdateDate && {
                topText: t('libraries.library.updated_at', {
                  date: getFullDate(knowledgeLibrary?.updatedAt),
                }),
              })}
            />
            {!!knowledgeLibrary?.body && !isSubpagesSelected && (
              <HtmlRender
                html={html}
                contentWidth={windowDimensions.width - SPACING.x4}
                containerStyle={[
                  styles.body,
                  {backgroundColor: theme.background.layout.default},
                ]}
                withZoom
                onLinkPress={onLinkPress}
              />
            )}
            {!!knowledgeLibrary?.attachments?.length && !isSubpagesSelected && (
              <>
                <Typography
                  variant="xs"
                  weight="semiBold"
                  color={theme.text.neutral.disabled}
                  style={styles.body}>
                  {t('libraries.downloadable_content')}
                </Typography>
                {knowledgeLibrary.attachments.map(renderAttachment)}
              </>
            )}
            {!!knowledgeLibrary?.children.length && (
              <>
                <Typography
                  variant="xs"
                  weight="semiBold"
                  color={theme.text.neutral.disabled}
                  style={styles.body}>
                  {t('libraries.subpages')}
                </Typography>
                <List
                  withDivider
                  data={knowledgeLibrary.children}
                  renderItem={renderItem}
                  isLoading={isLoading}
                  presentation="card"
                />
              </>
            )}
          </ScrollView>
        )}
      </View>
      {isFileLoading && (
        <View style={styles.loadingContainer}>
          <Spinner dark />
        </View>
      )}
    </>
  );
}
