import React, { useState } from 'react'
import {
  View,
  ActivityIndicator,
  StyleSheet,
  Platform,
  PermissionsAndroid,
  Alert,
  Text,
  TouchableOpacity,
} from 'react-native'
import { WebView } from 'react-native-webview'
import appColors from '../../../theme/appColors'
import { fontSizes, windowHeight } from '../../../theme/appConstant'
import { useValues } from '../../../utils/context'
import Icons from '../../../utils/icons/icons'
import appFonts from '../../../theme/appFonts'
import RNFS from 'react-native-fs'
import Share from 'react-native-share'
import { useNavigation } from '@react-navigation/native'
import { URL } from '../../../api/config'
import styles from './style'
import { Header } from '../../../commonComponents'
import { useSelector } from 'react-redux'

export function PdfViewer({ route }: any) {
  const { pdfUrl, rideNumber } = route?.params || {}
  const { isDark } = useValues()
  const [loading, setLoading] = useState<boolean>(true)
  const pdfGoogleViewer = `https://docs.google.com/gview?embedded=true&url=${encodeURIComponent(
    pdfUrl,
  )}`

  const [isSharing, setIsSharing] = useState<boolean>(false)

  const downloadPdf = async () => {
    if (isSharing) return
    setIsSharing(true)

    const name = `invoice${rideNumber}.pdf`
    const pdfUrl = `${URL}/api/ride/driver-invoice/${rideNumber}`
    const downloadDest =
      Platform.OS === 'android'
        ? `${RNFS.DownloadDirectoryPath}/${name}`
        : `${RNFS.DocumentDirectoryPath}/${name}`

    try {
      const fileExists = await RNFS.exists(downloadDest)

      if (!fileExists) {
        await RNFS.downloadFile({
          fromUrl: pdfUrl,
          toFile: downloadDest,
        }).promise
      } else {
      }

      await Share.open({
        url: `file://${downloadDest}`,
        type: 'application/pdf',
        title: 'Share PDF',
      })

      Alert.alert(
        'Download Complete',
        `PDF saved to ${Platform.OS === 'android' ? 'Downloads folder' : 'Documents folder'
        }:\n${downloadDest}`,
      )
    } catch (err) {
    } finally {
      setIsSharing(false)
    }
  }
  const { translateData, taxidoSettingData } = useSelector(
    (state: any) => state.setting,
  )
  return (
    <View
      style={{
        flex: 1,
        backgroundColor: isDark ? appColors.darkThemeSub : appColors.white,
      }}
    >
      <Header
        title={translateData?.Invoice}
        icon={
          <Icons.Download
            color={isDark ? appColors.darkText : appColors.black}
          />
        }
        onPress={() => {
          if (loading) {
            return
          }
          downloadPdf()
        }}
      />

      {loading && (
        <View style={styles.loaderContainer}>
          <ActivityIndicator size="large" color={appColors.primary} />
        </View>
      )}

      <WebView
        source={{ uri: pdfGoogleViewer }}
        style={{
          flex: 1,
          width: '100%',
          backgroundColor: isDark ? appColors.darkThemeSub : appColors.white,
        }}
        javaScriptEnabled={true}
        domStorageEnabled={true}
        onLoadStart={() => setLoading(true)}
        onLoadEnd={() => setLoading(false)}
        onError={error => {
          setLoading(false)
        }}
      />
    </View>
  )
}
