Нужно ли добавить в методы для открытия ссылок try catch? package ru.maxi.mobile.feature.webview.ui

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.annotation.RequiresApi
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import by.kirich1409.viewbindingdelegate.viewBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import ru.maxi.mobile.R
import ru.maxi.mobile.base.ui.MvvmBaseFragment
import ru.maxi.mobile.common.utils.android.screenArgs
import ru.maxi.mobile.common.utils.android.setupDarkMode
import ru.maxi.mobile.core.data.LoadableData
import ru.maxi.mobile.databinding.FragmentWebviewBinding
import java.net.URL

/**
 * Фрагмент для отображения WebView
 */
@AndroidEntryPoint
class WebViewFragment : MvvmBaseFragment(R.layout.fragment_webview) {

    private val screenArgs by screenArgs(WebViewArgs)

    private val viewBinding by viewBinding(FragmentWebviewBinding::bind)

    private val viewModel by viewModels<WebViewViewModel>()

    override val analyticsName: String = "_WebView"

    @SuppressLint("SetJavaScriptEnabled")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        Log.d("TESTING", "WebViewFragment onViewCreated")

        actionBarManager.setTitle(screenArgs.title)
        actionBarManager.showBackButton()

        with(viewBinding) {
            webView.apply {
                settings.apply {
                    textZoom = 100
                    javaScriptEnabled = true
                }
                webViewClient = CustomWebViewClient()
                setupDarkMode()
            }
            noConnectionView.setOnActionButtonClickListener { webView.reload() }
        }

        with(viewLifecycleOwner) {
            lifecycleScope.launch {
                repeatOnLifecycle(Lifecycle.State.STARTED) {
                    launch { viewModel.viewState.collect(::onViewStateChange) }
                }
            }
        }
    }

    private fun onViewStateChange(viewState: LoadableData<URL>) {
        when (viewState) {
            is LoadableData.Loading -> with(viewBinding) {
                loaderView.show()
                noConnectionView.isVisible = false
                webView.isInvisible = true
                viewState.value?.let(::loadPage)
            }

            is LoadableData.Error -> with(viewBinding) {
                loaderView.hide()
                noConnectionView.isVisible = true
                webView.isInvisible = true
            }

            is LoadableData.Success -> with(viewBinding) {
                loaderView.hide()
                noConnectionView.isVisible = false
                webView.isVisible = true
                loadPage(viewState.value)
            }
        }
    }

    private fun loadPage(url: URL) {
        if (viewBinding.webView.url != url.toString()) {
            viewBinding.webView.loadUrl(url.toString())
        }
    }

    private inner class CustomWebViewClient : WebViewClient() {

        override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
            Log.d("TESTING", "CustomWebViewClient  shouldOverrideUrlLoading 2")
            return handleLink(request?.url.toString())
        }

        private fun handleLink(urlLink: String): Boolean {
            Log.d("TESTING", "CustomWebViewClient handleLink")
            urlLink.let { url ->
                if (url.endsWith(".pdf", ignoreCase = true)) {
                    openPdfFile(url)
                    return true
                } else if (url.startsWith("https://maxi.today")) {
                    Log.d("TESTING", "maxi.today intent")
                    val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                    startActivity(browserIntent)
                }
            }
            return false
        }

        private fun openPdfFile(pdfUrl: String) {
            Log.d("TESTING", "CustomWebViewClient openPdfFile")
            val intent = Intent(Intent.ACTION_VIEW)
            intent.setDataAndType(Uri.parse(pdfUrl), "application/pdf")
            val packageManager = requireContext().packageManager

            if (intent.resolveActivity(packageManager) != null) {
                Log.d("TESTING", "CustomWebViewClient openPdfFile if true")
                startActivity(intent)
            } else {
                Log.d("TESTING", "CustomWebViewClient openPdfFile false")
                // Если приложение отсутствует, открываем PDF в браузере
                val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(pdfUrl))
                startActivity(browserIntent)
            }
        }

        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
            super.onPageStarted(view, url, favicon)
            viewModel.onPageStarted()
        }

        override fun onPageFinished(view: WebView?, url: String?) {
            super.onPageFinished(view, url)
            viewModel.onPageFinished()
        }

        override fun onReceivedError(
            view: WebView?,
            request: WebResourceRequest,
            error: WebResourceError?,
        ) {
            if (request.isForMainFrame) {
                viewModel.onError()
            }
        }

        override fun onReceivedHttpError(
            view: WebView?,
            request: WebResourceRequest,
            errorResponse: WebResourceResponse?,
        ) {
            if (request.isForMainFrame) {
                viewModel.onError()
            }
        }
    }
}