package com.base.pdfreaderallpdfreader.ui.main

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.text.Spannable
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import androidx.activity.addCallback
import androidx.core.view.GravityCompat
import androidx.core.view.updatePadding
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavController
import androidx.navigation.findNavController
import com.base.pdfreaderallpdfreader.BuildConfig
import com.base.pdfreaderallpdfreader.R
import com.base.pdfreaderallpdfreader.ads.AdmobHelper
import com.base.pdfreaderallpdfreader.ads.AdmobHelper.lastScanShowAd
import com.base.pdfreaderallpdfreader.ads.admob.AdmobBannerUtils
import com.base.pdfreaderallpdfreader.ads.admob.AdmobInterstitialUtils
import com.base.pdfreaderallpdfreader.base.BaseActivity
import com.base.pdfreaderallpdfreader.bean.ConstObject.NOTIFICATION_ACTION_BOOKMARK
import com.base.pdfreaderallpdfreader.bean.ConstObject.NOTIFICATION_ACTION_NEW_IMAGE_PDF
import com.base.pdfreaderallpdfreader.databinding.ActivityMainBinding
import com.base.pdfreaderallpdfreader.fcm.NotificationUiUtil
import com.base.pdfreaderallpdfreader.fcm.NotificationUiUtil.getNextActionId
import com.base.pdfreaderallpdfreader.helper.ConfigHelper
import com.base.pdfreaderallpdfreader.ui.feedback.FeedbackActivity
import com.base.pdfreaderallpdfreader.ui.language.LanguageActivity
import com.base.pdfreaderallpdfreader.ui.pdf.PdfActivity
import com.base.pdfreaderallpdfreader.ui.search.SearchActivity
import com.base.pdfreaderallpdfreader.ui.view.MainDialog.showAppExitDialog
import com.base.pdfreaderallpdfreader.ui.view.MainDialog.showNotificationDialog
import com.base.pdfreaderallpdfreader.ui.view.MainDialog.showStoragePermission
import com.base.pdfreaderallpdfreader.ui.view.NameDialog.showDocumentRenameDialog
import com.base.pdfreaderallpdfreader.ui.view.PwdDialog.showPdfPwdDialog
import com.base.pdfreaderallpdfreader.ui.view.RateDialog.showRateDialog
import com.base.pdfreaderallpdfreader.utils.BarUtils
import com.base.pdfreaderallpdfreader.utils.LogEx
import com.base.pdfreaderallpdfreader.utils.PdfBoxUtils.checkPdfEncryption
import com.base.pdfreaderallpdfreader.utils.PermissionUtils.checkNotificationPermission
import com.base.pdfreaderallpdfreader.utils.PermissionUtils.checkStorePermission
import com.base.pdfreaderallpdfreader.utils.ShortcutUtils.addDeskShortCut
import com.base.pdfreaderallpdfreader.utils.ToastUtils.toast
import com.base.pdfreaderallpdfreader.utils.updateMediaStore
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File


class MainActivity : BaseActivity<ActivityMainBinding>() {

    private val TAG = "MainActivity"
    override val binding: ActivityMainBinding by lazy {
        ActivityMainBinding.inflate(layoutInflater)
    }
    private lateinit var mainViewModel: MainViewModel

    private lateinit var navController: NavController

    private var actionId: String = ""

    override fun initView() {

        mainViewModel = ViewModelProvider(this)[MainViewModel::class.java]
        mainViewModel.initScannerLauncher(this)
        mainViewModel.handleActivityGmsScanResult = { imageUri, pdfUri ->

            LogEx.logDebug(TAG, "pdfUri=$pdfUri imageUri=$imageUri")

            val file = File(pdfUri.toString().replace("file://", ""))
            if (file.exists()) {
                showDocumentRenameDialog(file.name,
                    okAction = {
                        val child = if (it.endsWith(".pdf")) it else "$it.pdf"
                        val newFile = File(getDocumentAppDir(), child)
                        mainViewModel.copyFile(file, newFile)
                        this.updateMediaStore()
                    },
                    dismissAction = {

                    })

            } else {
                toast("can't get file")
            }
        }

        BarUtils.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, Color.WHITE)
        binding.root.updatePadding(top = BarUtils.getStatusBarHeight())
        navController = findNavController(R.id.nav_host_fragment_content_main)

        val spannableString = SpannableString(this.getString(R.string.pdf_reader))
        spannableString.setSpan(ForegroundColorSpan(Color.parseColor("#E20001")), 0, 3, Spannable.SPAN_INCLUSIVE_INCLUSIVE)
        binding.includeMain.tvTittle.text = spannableString
        binding.tvPdfReader.text = spannableString

        if (checkStorePermission()) {
            val flag = checkNotificationPermission()
            LogEx.logDebug(TAG, "checkNotificationPermission flag=$flag")
            if (!flag) {
                showNotificationDialog(launcher)
            } else {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                    launcher.launch(arrayOf(Manifest.permission.POST_NOTIFICATIONS)) {}
                }
            }
        }

        addDeskShortCut()
    }

    private var jumpOutPage: Boolean = false
    override fun onResume() {
        super.onResume()
        LogEx.logDebug(TAG, "onResume")
        if (checkStorePermission()) {
            if (!jumpOutPage) {
                showMainBanner()
            }
        } else {
            if (!jumpOutPage) {
                showStoragePermission(launcher, jumpAction = { jumpOutPage = true })
            }
        }
        jumpOutPage = false
    }

    override fun initListener() {
        super.initListener()
        onBackPressedDispatcher.addCallback {
            showAppExitDialog()
        }
        binding.includeMain.ivMenu.setOnClickListener {
            binding.drawerLayout.openDrawer(GravityCompat.START)
        }
        binding.flFanhui.setOnClickListener {
            binding.drawerLayout.closeDrawer(GravityCompat.START)
        }
        binding.includeMain.includeContentMain.llHome.setOnClickListener {
            changeHomeUI()
        }
        binding.includeMain.includeContentMain.llHome.callOnClick()
        binding.includeMain.includeContentMain.llRecent.setOnClickListener {
            changeRecentUI()
        }
        binding.includeMain.includeContentMain.llBookmark.setOnClickListener {
            changeBookMarkUI()
        }
        binding.llLanguage.setOnClickListener {
            startActivity(Intent(this, LanguageActivity::class.java))
        }
        binding.includeMain.ivSearch.setOnClickListener {
            startActivity(Intent(this, SearchActivity::class.java))
        }
        binding.includeMain.includeContentMain.ivScan.setOnClickListener {
            starAdGmsScan()
        }
        binding.llFileManager.setOnClickListener {
            val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
            intent.addCategory(Intent.CATEGORY_OPENABLE)
            intent.setType("application/pdf")
            intent.flags = Intent.FLAG_GRANT_WRITE_URI_PERMISSION

            jumpOutPage = true
            launcher.launch(intent) {
                val uri = it.data?.data
                uri?.let {
                    jumpUriPdf(uri)
                }
            }
        }
        binding.llRate.setOnClickListener {
            showRateDialog(true)
        }
        binding.llPrivacy.setOnClickListener {
            val intent = Intent(
                Intent.ACTION_VIEW,
                Uri.parse(ConfigHelper.privacyPolicy)
            )
            startActivity(intent)
        }
        binding.llFeedback.setOnClickListener {
            startActivity(Intent(this, FeedbackActivity::class.java))
        }
        binding.llShare.setOnClickListener {

        }
        binding.includeMain.tvTittle.setOnClickListener {
            if (BuildConfig.DEBUG) {
                NotificationUiUtil.sendNotificationIfCan(this, "test", getNextActionId())
            }
        }
        handleActionFunction()

    }

    @SuppressLint("MissingSuperCall")
    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        handleActionFunction()
    }

    private fun handleActionFunction() {
        actionId = intent.extras?.getString("actionId") ?: ""
        LogEx.logDebug(TAG, "handleActionFunction actionId=$actionId")
        when (actionId) {
            NOTIFICATION_ACTION_BOOKMARK -> {
                changeBookMarkUI()
            }

            NOTIFICATION_ACTION_NEW_IMAGE_PDF -> {
                jumpOutPage = true
                mainViewModel.starGmsScan(this)
            }
        }
    }

    private fun jumpUriPdf(uri: Uri) {
        lifecycleScope.launch(Dispatchers.IO) {
            val state = checkPdfEncryption(uri = uri.toString())
            launch(Dispatchers.Main) {
                if (state == 0) {
                    startActivity(Intent(this@MainActivity, PdfActivity::class.java).apply {
                        putExtra("uri", uri.toString())
                    })
                } else {
                    showPdfPwdDialog(
                        state = state,
                        uri = uri.toString(),
                        isCheckPwd = true,
                        verificationAction = { pwd ->
                            startActivity(Intent(this@MainActivity, PdfActivity::class.java).apply {
                                putExtra("uri", uri.toString())
                                putExtra("pwd", pwd)
                            })
                        })
                }
            }
        }
    }

    private fun starAdGmsScan() {

        if (AdmobHelper.isShowScanInter() && AdmobHelper.canCommonShowAd()) {
            jumpOutPage = true
            AdmobInterstitialUtils.showInterstitialAd(this) {
                if (it) {
                    lastScanShowAd = System.currentTimeMillis()
                }
                jumpOutPage = true
                mainViewModel.starGmsScan(this)
            }
        } else {
            jumpOutPage = true
            mainViewModel.starGmsScan(this)
        }

    }

    private fun disSelectBottomNav() {
        binding.includeMain.includeContentMain.ivHome.isSelected = false
        binding.includeMain.includeContentMain.tvHome.isSelected = false

        binding.includeMain.includeContentMain.ivRecent.isSelected = false
        binding.includeMain.includeContentMain.tvRecent.isSelected = false

        binding.includeMain.includeContentMain.ivBookmark.isSelected = false
        binding.includeMain.includeContentMain.tvBookmark.isSelected = false
    }

    private fun changeBookMarkUI() {
        disSelectBottomNav()
        binding.includeMain.includeContentMain.ivBookmark.isSelected = true
        binding.includeMain.includeContentMain.tvBookmark.isSelected = true

        navController.popBackStack()
        navController.navigate(R.id.nav_bookmarkFragment)
    }

    private fun changeRecentUI() {
        disSelectBottomNav()
        binding.includeMain.includeContentMain.ivRecent.isSelected = true
        binding.includeMain.includeContentMain.tvRecent.isSelected = true

        navController.popBackStack()
        navController.navigate(R.id.nav_recentFragment)
    }

    private fun changeHomeUI() {
        disSelectBottomNav()
        binding.includeMain.includeContentMain.ivHome.isSelected = true
        binding.includeMain.includeContentMain.tvHome.isSelected = true

        navController.popBackStack()
        navController.navigate(R.id.nav_homeFragment)
    }

    private var bannerShowed: Boolean = false//banner已经显示
    private fun showMainBanner() {
        if (!bannerShowed) {
            bannerShowed = true
            LogEx.logDebug(TAG, "showMainBanner")
            AdmobBannerUtils.showCollapsibleBannerAd(this, binding.includeMain.includeContentMain.flBanner) {}
        }
    }

}