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

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.activity.OnBackPressedCallback
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.all.pdfreader.pro.app.R
import com.all.pdfreader.pro.app.databinding.ActivityPdfSplitBinding
import com.all.pdfreader.pro.app.model.PdfPageItem
import com.all.pdfreader.pro.app.model.PdfPickerSource
import com.all.pdfreader.pro.app.model.PdfSelectedPagesItem
import com.all.pdfreader.pro.app.model.RenameType
import com.all.pdfreader.pro.app.ui.adapter.SplitPdfAdapter
import com.all.pdfreader.pro.app.ui.adapter.SplitSelectedPdfAdapter
import com.all.pdfreader.pro.app.ui.dialog.PdfPasswordProtectionDialogFragment
import com.all.pdfreader.pro.app.ui.dialog.PromptDialogFragment
import com.all.pdfreader.pro.app.ui.dialog.RenameDialogFragment
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.FileUtils.toUnderscoreDateTime
import com.all.pdfreader.pro.app.util.PdfUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File

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


    private var currentViewState: ViewState = ViewState.SPLIT_LIST
    var currentPassword : String? = null//拆分只会选择一个文件。直接进行密码传递

    private enum class ViewState {
        SPLIT_LIST,     // 拆分页列表
        SPLIT_SELECTED  // 已选页面列表
    }

    companion object {
        private const val EXTRA_PDF_PATH = "extra_pdf_path"

        fun createIntent(context: Context, filePath: String): Intent {
            return Intent(context, SplitPdfActivity::class.java).apply {
                putExtra(EXTRA_PDF_PATH, filePath)
            }
        }
    }

    private lateinit var binding: ActivityPdfSplitBinding
    private lateinit var adapter: SplitPdfAdapter
    private var splitList: MutableList<PdfPageItem> = mutableListOf()
    private var selectedList: MutableList<PdfSelectedPagesItem> = mutableListOf()
    private lateinit var selectedPdfAdapter: SplitSelectedPdfAdapter
    private var isSelectedViewShow = false//用于返回的时候是否提示（点击了继续按钮就会产生提示）
    private lateinit var filePath: String

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityPdfSplitBinding.inflate(layoutInflater)
        setContentView(binding.root)
        setupBackPressedCallback()
        filePath = intent.getStringExtra(EXTRA_PDF_PATH)
            ?: throw IllegalArgumentException("PDF file hash is required")
        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.selectAllBtn.visibility = View.GONE//初始隐藏全选按钮
        binding.addBtn.visibility = View.GONE//初始隐藏add按钮
        binding.loadingRoot.root.visibility = View.VISIBLE//初始显示loading
        binding.splitRv.layoutManager = GridLayoutManager(this, 2)
        adapter = SplitPdfAdapter(splitList) { 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 = splitList.any { it.isSelected }
            binding.continueNowBtn.isEnabled = anySelected
            updateContinueNowBtnState(anySelected)
        }
        binding.splitRv.adapter = adapter

        selectedPdfAdapter = SplitSelectedPdfAdapter(selectedList, onEditClick = { item, pos ->
            RenameDialogFragment(
                RenameType.NAME, null, item.fileName, onOkClickString = { string ->
                    selectedList[pos].fileName = string
                    selectedPdfAdapter.updateItem(pos)
                }).show(supportFragmentManager, "SplitPdfActivity")
        }, onDeleteClick = { item, pos ->
            selectedList.remove(item)
            selectedPdfAdapter.removeItem(pos)
            updateSplitBtnState(selectedList.isNotEmpty())
        })
        binding.splitSelectRv.layoutManager = LinearLayoutManager(this)
        binding.splitSelectRv.adapter = selectedPdfAdapter
    }

    private fun setupClick() {
        binding.backBtn.setOnSingleClickListener { onBackPressedDispatcher.onBackPressed() }
        binding.selectAllBtn.setOnSingleClickListener {
            val selectAll = splitList.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 = splitList.filter { it.isSelected }.map { it.copy() }
            val name =
                getString(R.string.split) + "_" + System.currentTimeMillis().toUnderscoreDateTime()
            val item = PdfSelectedPagesItem(filePath, name, selectedPages)
            selectedList.add(item)
            selectedPdfAdapter.updateAdapter()
            isSelectedViewShow = true
            updateViewState(true)
        }
        binding.addBtn.setOnSingleClickListener {
            binding.continueNowBtn.isEnabled = false//继续按钮不可点击
            updateContinueNowBtnState(false)//重置继续按钮背景
            adapter.setAllSelected(false)
            updateSelectAllState(false)
            updateViewState(false)
        }
        binding.splitBtn.setOnSingleClickListener {
            logDebug("${selectedList.size}")
            //因为图片做的路径缓存方式，所以这里直接传入整个集合到result页处理
            val intent = PdfResultActivity.createIntentSplitPdfActivityToResult(
                this,
                ArrayList(selectedList),
                PdfPickerSource.SPLIT,
                password = currentPassword
            )
            startActivity(intent)
            finish()
        }
    }

    private fun initSplitData(file: File) {
        lifecycleScope.launch {
            // 是否存在密码
            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 {
            splitList.clear()
            // 先切换到 IO 线程执行删除，等待完成
            withContext(Dispatchers.IO) {
                PdfUtils.clearPdfThumbsCache(this@SplitPdfActivity)
            }
            // 删除完成后，开始收集数据
            var firstPageLoaded = false
            PdfUtils.splitPdfToPageItemsFlow(
                context = this@SplitPdfActivity,
                inputFile = file,
                password = password
            ).collect { pageItem ->
                logDebug("splitPdfToPageItemsFlow pageItem->$pageItem")
                if (splitList.size <= pageItem.pageIndex) {
                    splitList.add(pageItem)
                    adapter.notifyItemInserted(splitList.size - 1)
                } else {
                    splitList[pageItem.pageIndex] = pageItem
                    adapter.updateItem(pageItem.pageIndex)
                }
                if (!firstPageLoaded) {
                    binding.loadingRoot.root.visibility = View.GONE
                    if (!isSelectedViewShow) {
                        binding.selectAllBtn.visibility = View.VISIBLE
                    }
                    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
        )
    }

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

    private fun updateViewState(b: Boolean) {
        if (b) {
            currentViewState = ViewState.SPLIT_SELECTED
            binding.selectAllBtn.visibility = View.GONE//隐藏全选按钮
            binding.addBtn.visibility = View.VISIBLE//显示add按钮
            binding.title.text = getString(R.string.split_pdf)//设置标题
        } else {
            currentViewState = ViewState.SPLIT_LIST
            binding.selectAllBtn.visibility = View.VISIBLE
            binding.addBtn.visibility = View.GONE
            binding.title.text =
                getString(R.string.selected_page, adapter.getSelPages())//重新设置标题为选中了多少个
        }
        updateViewStateWithAnimation(b)

        updateSplitBtnState(selectedList.isNotEmpty())
    }

    private fun updateViewStateWithAnimation(showSelectedView: Boolean) {
        if (showSelectedView) {
            // 切换到已选页面列表
            binding.splitListLayout.animate().translationY(-50f).alpha(0f).setDuration(200)
                .withEndAction {
                    binding.splitListLayout.visibility = View.GONE
                    binding.splitListLayout.translationY = 0f
                }.start()

            binding.splitSelectLayout.alpha = 0f
            binding.splitSelectLayout.translationY = 50f
            binding.splitSelectLayout.visibility = View.VISIBLE
            binding.splitSelectLayout.animate().translationY(0f).alpha(1f).setDuration(200).start()
        } else {
            // 切回拆分页列表
            binding.splitSelectLayout.animate().translationY(50f).alpha(0f).setDuration(200)
                .withEndAction {
                    binding.splitSelectLayout.visibility = View.GONE
                    binding.splitSelectLayout.translationY = 0f
                }.start()

            binding.splitListLayout.alpha = 0f
            binding.splitListLayout.translationY = -50f
            binding.splitListLayout.visibility = View.VISIBLE
            binding.splitListLayout.animate().translationY(0f).alpha(1f).setDuration(200).start()
        }
    }


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

    private fun setupBackPressedCallback() {
        onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                if (!isSelectedViewShow) {//点击继续后，说明已经操过过了，不直接finish
                    isEnabled = false
                    onBackPressedDispatcher.onBackPressed()
                    return
                }
                when (currentViewState) {
                    ViewState.SPLIT_SELECTED -> {
                        // 已选页面列表，提示是否退出
                        PromptDialogFragment(
                            getString(R.string.exit_split),
                            getString(R.string.confirm_discard_changes),
                            getString(R.string.discard),
                            onOkClick = {
                                isEnabled = false
                                onBackPressedDispatcher.onBackPressed()
                            }).show(supportFragmentManager, getString(R.string.exit_split))
                    }

                    ViewState.SPLIT_LIST -> {
                        // 拆分页列表，返回到已选页面列表
                        adapter.setAllSelected(false)//重置所有选中状态为false
                        updateSelectAllState(false)//重置选中按钮
                        binding.continueNowBtn.isEnabled = false//继续按钮不可点击
                        updateContinueNowBtnState(false)//重置继续按钮背景
                        updateViewState(true)
                    }
                }
            }
        })
    }
}