package com.all.pdfreader.pdf.reader.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.pdf.reader.R
import com.all.pdfreader.pdf.reader.databinding.DialogPdfSetPasswordBinding
import com.all.pdfreader.pdf.reader.util.AnalyticsUtils
import com.all.pdfreader.pdf.reader.util.AppUtils.showKeyboard
import com.all.pdfreader.pdf.reader.util.ToastUtils

class PdfSetPasswordDialog() : DialogFragment() {

    companion object {
        fun newInstance(): PdfSetPasswordDialog {
            return PdfSetPasswordDialog()
        }
    }

    var onOkClick: ((password: String) -> Unit)? = null

    private lateinit var binding: DialogPdfSetPasswordBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 系统恢复时直接 dismiss 避免 crash
        if (savedInstanceState != null) {
            dismissAllowingStateLoss()
            return
        }
    }

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

    override fun onStart() {
        super.onStart()
        isCancelable = false
        dialog?.window?.apply {
            setBackgroundDrawable(Color.TRANSPARENT.toDrawable())
            val margin = resources.getDimensionPixelSize(R.dimen.dialog_margin)
            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()
        AnalyticsUtils.logEvent(AnalyticsUtils.Event.LOCK_TK_SHOW)
    }

    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?.invoke(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
    }
}
