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 androidx.core.graphics.drawable.toDrawable
import androidx.fragment.app.DialogFragment
import com.all.pdfreader.pro.app.R
import com.all.pdfreader.pro.app.databinding.DialogPdfSetPasswordBinding
import com.all.pdfreader.pro.app.util.AppUtils.showKeyboard
import com.all.pdfreader.pro.app.util.ToastUtils

class PdfSetPasswordDialog(
    private val onOkClick: (password: String) -> Unit = {}
) : DialogFragment() {
    private lateinit var binding: DialogPdfSetPasswordBinding

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

    override fun onStart() {
        super.onStart()
        isCancelable = false
        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)
        binding.etPassword.showKeyboard()
        setupListeners()
        setupTextWatchers()
    }

    private fun setupListeners() {
        binding.cancelBtn.setOnClickListener {
            dismiss()
        }

        binding.okBtn.setOnClickListener {
            val password = binding.etPassword.text.toString()
            val confirmPassword = binding.etConfirmPassword.text.toString()
            if (validatePassword(password, confirmPassword)) {
                onOkClick(password)
                dismiss()
            }
        }
    }

    private fun setupTextWatchers() {
        binding.etPassword.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) {}
            override fun afterTextChanged(s: Editable?) {
                validateInput()
            }
        })

        binding.etConfirmPassword.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) {}
            override fun afterTextChanged(s: Editable?) {
                validateInput()
            }
        })
    }

    private fun validateInput() {
        val password = binding.etPassword.text.toString()
        val confirmPassword = binding.etConfirmPassword.text.toString()

        binding.tilPassword.error = null
        binding.tilConfirmPassword.error = null

        if (password.isNotEmpty() && confirmPassword.isNotEmpty() && password != confirmPassword) {
            binding.tilConfirmPassword.error = getString(R.string.password_not_match)
        }
    }

    private fun validatePassword(password: String, confirmPassword: String): Boolean {
        binding.tilPassword.error = null
        binding.tilConfirmPassword.error = null

        // 不允许空密码
        if (password.isEmpty()) {
            binding.tilPassword.error = getString(R.string.password_not_empty)
            return false
        }

        // 密码长度验证
        if (password.length < 4) {
            binding.tilPassword.error = getString(R.string.password_too_short)
            return false
        }

        // 密码匹配验证
        if (password != confirmPassword) {
            binding.tilConfirmPassword.error = getString(R.string.password_not_match)
            return false
        }

        return true
    }

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