package com.example.defenseapplication.view

import android.app.Dialog
import android.content.DialogInterface
import android.os.Bundle
import android.os.CountDownTimer
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.fragment.app.DialogFragment
import com.example.defenseapplication.R
import com.example.defenseapplication.databinding.DialogPhoneModifyBinding
import com.example.defenseapplication.utils.RetrofitNetwork
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

//手机号弹窗
class PhoneModifyDialogFragment : DialogFragment() {

    private lateinit var binding: DialogPhoneModifyBinding
    private var title: String = ""
    private var negativeText: String = ""
    private var positiveText: String = ""
    private var onConfirmListener: ((String, String) -> Unit)? = null
    private var onDismissListener: (() -> Unit)? = null
    private var countDownTimer: CountDownTimer? = null

    fun setTitle(title: String): PhoneModifyDialogFragment {
        this.title = title
        return this
    }

    fun setNegativeText(text: String): PhoneModifyDialogFragment {
        this.negativeText = text
        return this
    }

    fun setPositiveText(text: String): PhoneModifyDialogFragment {
        this.positiveText = text
        return this
    }

    fun setOnConfirmListener(listener: (phone: String, code: String) -> Unit): PhoneModifyDialogFragment {
        this.onConfirmListener = listener
        return this
    }

    fun setOnDismissListener(listener: () -> Unit): PhoneModifyDialogFragment {
        this.onDismissListener = listener
        return this
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val dialog = super.onCreateDialog(savedInstanceState)
        dialog.window?.let {
            val params = it.attributes
            params.gravity = Gravity.CENTER
            params.width = WindowManager.LayoutParams.MATCH_PARENT
            params.height = WindowManager.LayoutParams.WRAP_CONTENT
            it.attributes = params
            it.setBackgroundDrawableResource(R.drawable.round_bg)
        }
        return dialog
    }

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

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        if (negativeText.isEmpty()) negativeText = getString(R.string.cancel)
        if (positiveText.isEmpty()) positiveText = getString(R.string.confirm)

        binding.tvTitle.text = title
        binding.btnNegative.text = negativeText
        binding.btnPositive.text = positiveText

        binding.tvSendCode.setOnClickListener {
            val phone = binding.etPhone.text.toString()
            if (phone.length != 11) {
                ToastUtils.showToast(requireContext(), getString(R.string.invalid_phone))
                return@setOnClickListener
            }
            sendCode(phone)
        }

        binding.btnNegative.setOnClickListener {
            dismiss()
        }

        binding.btnPositive.setOnClickListener {
            val phone = binding.etPhone.text.toString()
            val code = binding.etCode.text.toString()
            if (phone.length != 11) {
                ToastUtils.showToast(requireContext(), getString(R.string.invalid_phone))
                return@setOnClickListener
            }
            if (code.isEmpty()) {
                ToastUtils.showToast(requireContext(), getString(R.string.enter_verification_code))
                return@setOnClickListener
            }
            onConfirmListener?.invoke(phone, code)
            dismiss()
        }
    }

    private fun sendCode(phone: String) {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val response = RetrofitNetwork.getNetworkService().getCode(phone)
                withContext(Dispatchers.Main) {
                    if (response.code == 200) {
                        ToastUtils.showToast(requireContext(), getString(R.string.code_sent_success))
                        startCountDown()
                    } else {
                        ToastUtils.showToast(requireContext(), getString(R.string.code_send_failed))
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
                withContext(Dispatchers.Main) {
                    ToastUtils.showToast(requireContext(), getString(R.string.network_error))
                }
            }
        }
    }

    private fun startCountDown() {
        binding.tvSendCode.isEnabled = false
        countDownTimer = object : CountDownTimer(60000, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                binding.tvSendCode.text = String.format("%ds", millisUntilFinished / 1000)
            }

            override fun onFinish() {
                binding.tvSendCode.text = getString(R.string.send_sms_code)
                binding.tvSendCode.isEnabled = true
            }
        }
        countDownTimer?.start()
    }

    override fun onDismiss(dialog: DialogInterface) {
        super.onDismiss(dialog)
        countDownTimer?.cancel()
        onDismissListener?.invoke()
        onConfirmListener = null
        onDismissListener = null
    }
}