import React, {useCallback, useEffect, useMemo} from 'react';
import {Share, View} from 'react-native';
import Pdf from 'react-native-pdf';
import {IconShare} from '@tabler/icons-react-native';
import {IconButton, PdfLoadingIndicator} from '@components';
import {getApiHeaders} from '@config/api';
import {tokenManager} from '@config/tokens';
import {Navigation} from '@interfaces/navigation';
import {Screens} from '@shared/constants';
import {downloadAndShareFile} from '@shared/utils';
import {useTheme} from '@shared/theme';
import {commonStyles} from '@shared/styles';

interface HeaderRightProps {
  onPress: () => void;
}

function ShareHeaderRight({onPress}: HeaderRightProps) {
  return (
    <IconButton
      hitSlop={16}
      Icon={IconShare}
      onPress={onPress}
      variant="tertiary"
    />
  );
}

function PdfViewer({
  route: {
    params: {uri, title, headers, fileName},
  },
  navigation,
}: Navigation<Screens.PDF_VIEWER>) {
  const {theme} = useTheme();
  const token = tokenManager.getAccessToken();

  const source = useMemo(
    () => ({
      uri,
      headers: headers || getApiHeaders(token),
    }),
    [headers, token, uri],
  );

  const onShare = useCallback(async () => {
    try {
      await downloadAndShareFile({
        url: uri,
        headers: source.headers,
        name: fileName,
      });
    } catch (e) {
      // just the url in case of error
      await Share.share({url: uri});
    }
  }, [uri, source, fileName]);

  const renderPdfLoader = useCallback(
    (progress: number) => <PdfLoadingIndicator progress={progress} />,
    [],
  );

  useEffect(() => {
    const headerRight = () => <ShareHeaderRight onPress={onShare} />;
    navigation.setOptions({
      ...(title && {title}),
      headerRight,
    });
  }, [navigation, onShare, title]);

  return (
    <View
      style={[
        commonStyles.flex,
        {backgroundColor: theme.background.layout.default},
      ]}>
      <Pdf
        source={source}
        trustAllCerts={false}
        renderActivityIndicator={renderPdfLoader}
        style={commonStyles.flex}
      />
    </View>
  );
}

export default PdfViewer;
