import * as FileSystem from 'expo-file-system'
import { getContentUriAsync } from 'expo-file-system'
import * as IntentLauncher from 'expo-intent-launcher'
import { useState } from 'react'
import { Platform } from 'react-native'

import { IFile } from '@/types/file.types'

import { SERVER_URL } from '@/config/api.config'

const { StorageAccessFramework } = FileSystem

export const useDownloadFileAndOpen = (file: IFile) => {
	const [downloadProgress, setDownloadProgress] = useState<number>()

	const downloadPath = `${FileSystem.documentDirectory}downloads/`

	const ensureDirAsync = async (dir, intermediates = true) => {
		const props = await FileSystem.getInfoAsync(dir)
		if (props.exists && props.isDirectory) {
			return props
		}
		await FileSystem.makeDirectoryAsync(dir, { intermediates })
		return await ensureDirAsync(dir, intermediates)
	}

	// Функция для отображения хода загрузки
	const downloadCallback = downloadProgress => {
		const progress =
			downloadProgress.totalBytesWritten /
			downloadProgress.totalBytesExpectedToWrite
		setDownloadProgress(progress)
	}

	const downloadFile = async fileUrl => {
		if (Platform.OS === 'android') {
			await ensureDirAsync(downloadPath)
		}

		const fileName = file.fileUri.split('/').pop()
		const fileUri = `${downloadPath}${fileName}`

		const downloadResumable = FileSystem.createDownloadResumable(
			fileUrl,
			fileUri,
			{},
			downloadCallback
		)

		try {
			const { uri } = await downloadResumable.downloadAsync()
			if (Platform.OS === 'android') {
				await saveAndroidFile(uri, fileName)
			} else {
				await saveIosFile(uri)
			}
		} catch (e) {
			console.error('Download error:', e)
		}
	}

	const saveAndroidFile = async (fileUri, fileName) => {
		try {
			const fileString = await FileSystem.readAsStringAsync(fileUri, {
				encoding: FileSystem.EncodingType.Base64
			})

			const permissions =
				await StorageAccessFramework.requestDirectoryPermissionsAsync()
			if (!permissions.granted) {
				return
			}

			try {
				const uri = await StorageAccessFramework.createFileAsync(
					permissions.directoryUri,
					fileName,
					file.fileType
				)
				await FileSystem.writeAsStringAsync(uri, fileString, {
					encoding: FileSystem.EncodingType.Base64
				})
				alert('Report Downloaded Successfully')
			} catch (e) {
				console.error('Error creating file:', e)
			}
		} catch (err) {
			console.error('Error reading file:', err)
		}
	}

	const saveIosFile = async fileUri => {
		// Здесь ваш код для сохранения файла на iOS
		// Например, использование expo-sharing для обмена файлом
	}

	const checkAndOpenFile = async () => {
		const fileUrl = SERVER_URL + file.fileUri
		const fileName = fileUrl.split('/').pop()
		const fileUri = `${downloadPath}${fileName}`

		try {
			const fileInfo = await FileSystem.getInfoAsync(fileUri)
			if (fileInfo.exists) {
				const data = await getContentUriAsync(fileUri)
				await IntentLauncher.startActivityAsync('android.intent.action.VIEW', {
					data: data,
					type: file.fileType
				})
			} else {
				await downloadFile(fileUrl)
			}
		} catch (error) {
			console.error('Error checking file:', error)
			// Alert.alert('Ошибка', 'Не удалось проверить файл.');
		}
	}

	return {
		checkAndOpenFile,
		downloadFile
	}
}
