package com.base.pdfviewerscannerwhite.ui.view

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import androidx.core.content.FileProvider
import androidx.core.widget.addTextChangedListener
import com.base.pdfviewerscannerwhite.R
import com.base.pdfviewerscannerwhite.bean.DocumentBean
import com.base.pdfviewerscannerwhite.databinding.DialogDeleteBinding
import com.base.pdfviewerscannerwhite.databinding.DialogDocumentDetailBinding
import com.base.pdfviewerscannerwhite.databinding.DialogDocumentRenameBinding
import com.base.pdfviewerscannerwhite.databinding.DialogPageNumberBinding
import com.base.pdfviewerscannerwhite.databinding.DialogPdfDetailBinding
import com.base.pdfviewerscannerwhite.databinding.DialogPdfMoreBinding
import com.base.pdfviewerscannerwhite.ui.adapter.DocumentAdapter
import com.base.pdfviewerscannerwhite.ui.main.DocumentView
import com.base.pdfviewerscannerwhite.ui.document.pdf.PdfView
import com.base.pdfviewerscannerwhite.utils.IntentShareUtils.sharePdfIntent
import com.base.pdfviewerscannerwhite.utils.IntentShareUtils.sharePdfPrintIntent
import com.base.pdfviewerscannerwhite.utils.KotlinExt.toFormatSize
import com.base.pdfviewerscannerwhite.utils.KotlinExt.toFormatTime
import com.base.pdfviewerscannerwhite.utils.KotlinExt.toFormatTime2
import com.base.pdfviewerscannerwhite.utils.KotlinExt.toFormatTime3
import com.base.pdfviewerscannerwhite.utils.LogEx
import com.base.pdfviewerscannerwhite.utils.SpStringUtils
import com.base.pdfviewerscannerwhite.utils.SpStringUtils.LAST_VIEW_KEY
import com.base.pdfviewerscannerwhite.utils.ToastUtils.toast
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import java.io.File


object DialogView {
    fun Context.showDocumentDetail(path: String) {
        val dialog = BottomSheetDialog(this, R.style.BottomSheetDialog)
        val binding = DialogDocumentDetailBinding.inflate(LayoutInflater.from(this))
        dialog.setContentView(binding.root)
        dialog.setCanceledOnTouchOutside(false)

        dialog.show()

        val parentView = binding.root.parent as View
        val behavior = BottomSheetBehavior.from(parentView)
        //展开
        behavior.state = BottomSheetBehavior.STATE_EXPANDED

        val file = File(path)
        binding.tvName.text = file.name
        binding.tvPath.text = file.absolutePath
        val lastView = SpStringUtils.getSpStringList(LAST_VIEW_KEY).find { it.contains(file.absolutePath) }
        if (lastView != null) {
            val lastTime = lastView.split("_")[1]
            binding.tvLastView.text = lastTime.toLong().toFormatTime3()
        }
        binding.tvLastChange.text = file.lastModified().toFormatTime3()
        binding.tvFileSize.text = file.length().toFormatSize()

        binding.tvBtnOk.setOnClickListener {
            dialog.dismiss()
        }

    }

    @SuppressLint("SetTextI18n", "NotifyDataSetChanged")
    fun Context.showPdfDetailDialog(
        documentView: DocumentView,
        item: DocumentBean,
        adapter: DocumentAdapter,
        dismissAction: () -> Unit
    ): BottomSheetDialog {
        val dialog = BottomSheetDialog(this, R.style.BottomSheetDialog)
        val binding = DialogPdfDetailBinding.inflate(LayoutInflater.from(this))
        dialog.setContentView(binding.root)
        dialog.setCanceledOnTouchOutside(false)

        dialog.show()

        val parentView = binding.root.parent as View
        val behavior = BottomSheetBehavior.from(parentView)
        //展开
        behavior.state = BottomSheetBehavior.STATE_EXPANDED


        val file = File(item.path)
        binding.tvName.text = file.name
        binding.tvInfo.text = file.lastModified().toFormatTime() + " " + file.length().toFormatSize()
        if (item.isBookmarked) {
            binding.ivBookmark.setImageResource(R.mipmap.h_soucang_s)
        } else {
            binding.ivBookmark.setImageResource(R.mipmap.h_soucang_n)
        }
        binding.ivBookmark.setOnClickListener {
            item.isBookmarked = !item.isBookmarked
            adapter.notifyDataSetChanged()
            if (item.isBookmarked) {
                binding.ivBookmark.setImageResource(R.mipmap.h_soucang_s)
            } else {
                binding.ivBookmark.setImageResource(R.mipmap.h_soucang_n)
            }
        }

        binding.llRename.setOnClickListener {
            documentView.dialogRename(item)
        }
        binding.llSplit.setOnClickListener {
            dialog.dismiss()
            documentView.splitPdf(item.path)
        }
        binding.llDelete.setOnClickListener {
            dialog.dismiss()
            showDeleteDialog{
                documentView.deleteDocument(item)
            }
        }
        dialog.setOnDismissListener {
            dismissAction.invoke()
        }
        return dialog
    }

    fun Activity.showPdfMoreDialog(
        pdfView: PdfView,
        pageNumber: Int,
        pafPath: String,
    ) {
        val dialog = BottomSheetDialog(this, R.style.BottomSheetDialog)
        val binding = DialogPdfMoreBinding.inflate(LayoutInflater.from(this))
        dialog.setContentView(binding.root)
        dialog.setCanceledOnTouchOutside(false)

        dialog.show()

        val parentView = binding.root.parent as View
        val behavior = BottomSheetBehavior.from(parentView)
        //展开
        behavior.state = BottomSheetBehavior.STATE_EXPANDED

        binding.llJump.setOnClickListener {
            showJumpPageNumberDialog(pageNumber) { pageIndex ->
                dialog.dismiss()
                pdfView.jumpPage(pageIndex)
            }
        }
        binding.llSplit.setOnClickListener {
            dialog.dismiss()
            pdfView.jumpSplit()
        }
        binding.llDetail.setOnClickListener {
            showDocumentDetail(pafPath)
        }
        binding.llShare.setOnClickListener {
            dialog.dismiss()
            val pkg = this.packageName
            LogEx.logDebug("showPdfMoreDialog", "pkg=$pkg")
            val uri = FileProvider.getUriForFile(
                this, this.packageName + ".provider", File(pafPath)
            )
            startActivity(Intent.createChooser(sharePdfIntent(uri), "Share PDF"))
        }
        binding.llPrint.setOnClickListener {
            val uri = FileProvider.getUriForFile(
                this, this.packageName + ".provider", File(pafPath)
            )
            startActivity(Intent.createChooser(sharePdfPrintIntent(uri), "Print PDF"))
        }

    }


    private fun Context.showJumpPageNumberDialog(pageNumber: Int, okAction: ((pageIndex: Int) -> Unit)?) {
        val dialog = BottomSheetDialog(this, R.style.BottomSheetDialog)
        val binding = DialogPageNumberBinding.inflate(LayoutInflater.from(this))
        dialog.setContentView(binding.root)
        dialog.setCanceledOnTouchOutside(false)

        val window = dialog.window
        window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)

        dialog.show()

        val parentView = binding.root.parent as View
        val behavior = BottomSheetBehavior.from(parentView)
        //展开
        behavior.state = BottomSheetBehavior.STATE_EXPANDED

        binding.edit.filters = arrayOf(NumberRangeFilter(1, pageNumber + 1))
        binding.edit.hint = "1 - ${pageNumber + 1}"
        binding.edit.addTextChangedListener {
            binding.tvOk.isEnabled = !it.isNullOrEmpty()
        }
        binding.edit.requestFocus()
        binding.tvOk.setOnClickListener {
            val number = binding.edit.text.toString()
            if (number.isEmpty()) {
                toast("number can't be empty!")
                return@setOnClickListener
            }
            dialog.dismiss()
            okAction?.invoke(number.toInt() - 1)
        }
    }

    fun Context.showDocumentRenameDialog(
        name: String? = null,
        firstDialog: Dialog? = null,
        okAction: ((newName: String) -> Unit)? = null,
    ) {
        val dialog = BottomSheetDialog(this, R.style.BottomSheetDialog)
        val binding = DialogDocumentRenameBinding.inflate(LayoutInflater.from(this))
        dialog.setContentView(binding.root)
        dialog.setCanceledOnTouchOutside(false)

        val window = dialog.window
        window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)

        dialog.show()

        val parentView = binding.root.parent as View
        val behavior = BottomSheetBehavior.from(parentView)
        //展开
        behavior.state = BottomSheetBehavior.STATE_EXPANDED

        binding.edit.addTextChangedListener {
            binding.tvOk.isEnabled = !it.isNullOrEmpty()
        }

        val tempName = "Split_" + System.currentTimeMillis().toFormatTime2()
        binding.edit.setText(name ?: tempName)
        binding.edit.requestFocus()

        binding.tvCancel.setOnClickListener {
            dialog.dismiss()
        }
        binding.tvOk.setOnClickListener {
            dialog.dismiss()

            val newName = binding.edit.text.toString()
            if (newName.isEmpty()) {
                toast("name can't be empty!")
                return@setOnClickListener
            }
            okAction?.invoke(newName)
            firstDialog?.dismiss()
        }
    }

    fun Context.showDeleteDialog(deleteAction: () -> Unit) {
        val dialog = BottomSheetDialog(this, R.style.BottomSheetDialog)
        val binding = DialogDeleteBinding.inflate(LayoutInflater.from(this))
        dialog.setContentView(binding.root)
        dialog.setCanceledOnTouchOutside(false)

        dialog.show()

        val parentView = binding.root.parent as View
        val behavior = BottomSheetBehavior.from(parentView)
        //展开
        behavior.state = BottomSheetBehavior.STATE_EXPANDED

        binding.tvCancel.setOnClickListener {
            dialog.dismiss()
        }
        binding.tvDelete.setOnClickListener {
            dialog.dismiss()
            deleteAction.invoke()
        }
    }
}