package com.all.pdfreader.pro.app.ui.act

import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.all.pdfreader.pro.app.R
import com.all.pdfreader.pro.app.databinding.ActivityPdfToImgBinding
import com.all.pdfreader.pro.app.model.PdfPageItem
import com.all.pdfreader.pro.app.model.PdfPickerSource
import com.all.pdfreader.pro.app.ui.adapter.SplitPdfAdapter
import com.all.pdfreader.pro.app.ui.dialog.PdfPasswordProtectionDialogFragment
import com.all.pdfreader.pro.app.util.AppUtils.setOnSingleClickListener
import com.all.pdfreader.pro.app.util.FileUtils.isPdfEncrypted
import com.all.pdfreader.pro.app.util.PdfUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.io.Serializable

class PdfToImageActivity : BaseActivity() {
    override val TAG: String = "PdfToImageActivity"


    var currentPassword: String? = null//只会选择一个文件。直接进行密码传递
    private lateinit var source: PdfPickerSource

    companion object {
        private const val EXTRA_PDF_PATH = "extra_pdf_path"
        private const val EXTRA_SOURCE = "extra_source"
        fun createIntent(context: Context, filePath: String, source: PdfPickerSource): Intent {
            return Intent(context, PdfToImageActivity::class.java).apply {
                putExtra(EXTRA_PDF_PATH, filePath)
                putExtra(EXTRA_SOURCE, source)
            }
        }
    }

    private lateinit var binding: ActivityPdfToImgBinding
    private lateinit var adapter: SplitPdfAdapter
    private var pdfPageList: MutableList<PdfPageItem> = mutableListOf()
    private lateinit var filePath: String

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityPdfToImgBinding.inflate(layoutInflater)
        setContentView(binding.root)
        filePath = intent.getStringExtra(EXTRA_PDF_PATH)
            ?: throw IllegalArgumentException("PDF file hash is required")
        source = getSerializableOrDefault(EXTRA_SOURCE, PdfPickerSource.NONE)
        if (filePath.isEmpty()) {
            showToast(getString(R.string.file_not))
            finish()
        }
        initView()
        setupClick()
        initSplitData(File(filePath))
    }

    private fun initView() {
        binding.continueNowBtn.isEnabled = false
        binding.title.text = getString(R.string.selected_page, 0)
        binding.loadingRoot.root.visibility = View.VISIBLE//初始显示loading
        binding.splitRv.layoutManager = GridLayoutManager(this, 2)
        adapter = SplitPdfAdapter(pdfPageList) { item, pos ->
            item.isSelected = !item.isSelected
            adapter.setItemSelected(pos, item.isSelected)
            binding.title.text = getString(R.string.selected_page, adapter.getSelPages())

            // 只有存在选中的item则为true
            val anySelected = pdfPageList.any { it.isSelected }
            binding.continueNowBtn.isEnabled = anySelected
            updateContinueNowBtnState(anySelected)
        }
        binding.splitRv.adapter = adapter

    }

    private fun setupClick() {
        binding.backBtn.setOnSingleClickListener { onBackPressedDispatcher.onBackPressed() }
        binding.selectAllBtn.setOnSingleClickListener {
            val selectAll = pdfPageList.any { !it.isSelected }//如果列表里有一页没选中 → 返回 true
            adapter.setAllSelected(selectAll)
            binding.title.text = getString(R.string.selected_page, adapter.getSelPages())
            binding.continueNowBtn.isEnabled = selectAll
            updateSelectAllState(selectAll)
            updateContinueNowBtnState(selectAll)
        }
        binding.continueNowBtn.setOnSingleClickListener {
            val selectedPages = pdfPageList.filter { it.isSelected }.map { it.copy() }
            val intent = if (source == PdfPickerSource.PDF_TO_IMAGES) {
                PdfResultActivity.createIntentPdfToImageActivityToResult(
                    context = this,
                    filepath = filePath,
                    list = ArrayList(selectedPages),
                    source = PdfPickerSource.PDF_TO_IMAGES,
                    password = currentPassword
                )
            } else {
                PdfResultActivity.createIntentPdfToImageActivityToResult(
                    context = this,
                    filepath = filePath,
                    list = ArrayList(selectedPages),
                    source = PdfPickerSource.TO_LONG_IMAGE,
                    password = currentPassword
                )
            }
            startActivity(intent)
            finish()
        }
    }

    private fun initSplitData(file: File) {
        lifecycleScope.launch(Dispatchers.IO) {
            // 是否存在密码
            val isEncrypted = withContext(Dispatchers.IO) {
                isPdfEncrypted(file)
            }
            if (isEncrypted) {
                PdfPasswordProtectionDialogFragment(file, onOkClick = { password ->
                    initSplitDataWithPassword(file, password)
                }, onCancelClick = {
                    finish()
                }).show(supportFragmentManager, TAG)
            } else {
                initSplitDataWithPassword(file)
            }
        }
    }

    private fun initSplitDataWithPassword(file: File, password: String? = null) {
        if (!password.isNullOrEmpty()) {
            currentPassword = password
        }
        lifecycleScope.launch {
            pdfPageList.clear()
            // 先切换到 IO 线程执行删除，等待完成
            withContext(Dispatchers.IO) {
                PdfUtils.clearPdfThumbsCache(this@PdfToImageActivity)
            }
            // 删除完成后，开始收集数据
            var firstPageLoaded = false
            PdfUtils.splitPdfToPageItemsFlow(
                context = this@PdfToImageActivity,
                inputFile = file,
                password = password
            ).collect { pageItem ->
                logDebug("splitPdfToPageItemsFlow pageItem->$pageItem")
                if (pdfPageList.size <= pageItem.pageIndex) {
                    pdfPageList.add(pageItem)
                    adapter.notifyItemInserted(pdfPageList.size - 1)
                } else {
                    pdfPageList[pageItem.pageIndex] = pageItem
                    adapter.updateItem(pageItem.pageIndex)
                }
                if (!firstPageLoaded) {
                    binding.loadingRoot.root.visibility = View.GONE
                    firstPageLoaded = true
                }
            }
        }
    }

    private fun updateSelectAllState(b: Boolean) {
//        binding.selectAll.setBackgroundResource(
//            if (b) R.drawable.dr_circular_sel_on_bg
//            else R.drawable.dr_circular_sel_off_bg
//        )
    }

    private fun updateContinueNowBtnState(b: Boolean) {
        binding.continueNowBtn.setBackgroundResource(
            if (b) R.drawable.dr_click_btn_bg
            else R.drawable.dr_btn_not_clickable_bg
        )
    }

    override fun onDestroy() {
        super.onDestroy()
    }

    private inline fun <reified T : Serializable> getSerializableOrDefault(
        key: String, default: T
    ): T {
        val result: T? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            intent.getSerializableExtra(key, T::class.java)
        } else {
            @Suppress("DEPRECATION") intent.getSerializableExtra(key) as? T
        }
        return result ?: default
    }

}