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

import android.graphics.Color
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.graphics.drawable.toDrawable
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.activityViewModels
import com.all.pdfreader.pro.app.R
import com.all.pdfreader.pro.app.databinding.DialogGotoPageBinding
import com.all.pdfreader.pro.app.databinding.DialogRenameFileBinding
import com.all.pdfreader.pro.app.model.RenameType
import com.all.pdfreader.pro.app.room.entity.BookmarkEntity
import com.all.pdfreader.pro.app.room.entity.PdfDocumentEntity
import com.all.pdfreader.pro.app.util.AppUtils.showKeyboard
import com.all.pdfreader.pro.app.util.FileUtils
import com.all.pdfreader.pro.app.util.ToastUtils
import com.all.pdfreader.pro.app.viewmodel.PdfViewModel
import java.io.File

class GotoPageDialogFragment(
    private val onOkClick: () -> Unit = {},
) : DialogFragment() {

    private lateinit var binding: DialogGotoPageBinding
    private val viewModel: PdfViewModel by activityViewModels()
    private lateinit var pdfDocument: PdfDocumentEntity

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        binding = DialogGotoPageBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun onStart() {
        super.onStart()
        dialog?.window?.apply {
            // 去掉系统默认的背景 padding
            setBackgroundDrawable(Color.TRANSPARENT.toDrawable())
            // 设置宽度为全屏减去 16dp
            val margin = resources.getDimensionPixelSize(R.dimen.dialog_margin) // 16dp
            val width = resources.displayMetrics.widthPixels - margin * 2
            setLayout(width, ViewGroup.LayoutParams.WRAP_CONTENT)
        }
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewModel.pdfDocument.value?.let {
            pdfDocument = it
            initView()
            setupOnClick()
        } ?: run {
            showToast(getString(R.string.file_not))
            dismiss()
        }
    }

    private fun initView() {
        binding.etName.showKeyboard()
        binding.tilName.hint = getString(R.string.name_must_be_number, pdfDocument.pageCount)
    }

    private fun setupOnClick() {
        binding.cancelBtn.setOnClickListener {
            dismiss()
        }
        binding.okBtn.setOnClickListener {
            val text = binding.etName.text.toString()
            if (validateEnter(text)) {
                val pageNumber = text.trim().toInt()
                viewModel.gotoPage(pageNumber)
                dismiss()
            }
        }
        binding.etName.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                binding.tilName.error = null
            }

            override fun afterTextChanged(s: Editable?) {}
        })
    }

    private fun validateEnter(inputText: String): Boolean {
        // 不允许为空
        if (inputText.isBlank()) {
            binding.tilName.error = getString(R.string.name_not_empty)
            return false
        }
        // 去掉首尾空格后转换成数字
        val pageNumber = inputText.trim().toInt()

        // 数字范围校验
        if (pageNumber < 1 || pageNumber > pdfDocument.pageCount) {
            binding.tilName.error = getString(R.string.name_out_of_range, pdfDocument.pageCount)
            return false
        }
        return true
    }

    private fun showToast(message: String) {
        ToastUtils.show(requireActivity(), message)
    }
}