package com.narutohuo.xindazhou.common.dialog

import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.DialogFragment
import com.google.android.material.button.MaterialButton
import com.google.android.material.textfield.TextInputEditText
import com.narutohuo.xindazhou.common.R
import com.narutohuo.xindazhou.common.config.ServerConfigManager

/**
 * 服务器配置对话框
 * 用于开发测试时配置服务器地址
 */
class ServerConfigDialog : DialogFragment() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.dialog_server_config, container, false)
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val dialog = super.onCreateDialog(savedInstanceState)
        dialog.setTitle("服务器配置")
        return dialog
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val etServerUrl = view.findViewById<TextInputEditText>(R.id.etServerUrl)
        val btnSave = view.findViewById<MaterialButton>(R.id.btnSave)
        val btnReset = view.findViewById<MaterialButton>(R.id.btnReset)
        val btnCancel = view.findViewById<MaterialButton>(R.id.btnCancel)

        // 显示当前服务器IP
        val currentIp = ServerConfigManager.getServerIp()
        etServerUrl?.setText(currentIp)
        etServerUrl?.hint = "请输入服务器IP地址（如：192.168.1.107）"

        // 保存按钮
        btnSave?.setOnClickListener {
            val ip = etServerUrl?.text?.toString()?.trim()
            if (ip.isNullOrEmpty()) {
                Toast.makeText(requireContext(), "服务器IP不能为空", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            ServerConfigManager.setServerIp(ip)
            Toast.makeText(requireContext(), "服务器IP已更新，请重启应用生效", Toast.LENGTH_LONG).show()
            dismiss()
        }

        // 重置按钮
        btnReset?.setOnClickListener {
            ServerConfigManager.resetToDefault()
            etServerUrl?.setText(ServerConfigManager.getServerIp())
            Toast.makeText(requireContext(), "已重置为默认IP", Toast.LENGTH_SHORT).show()
        }

        // 取消按钮
        btnCancel?.setOnClickListener {
            dismiss()
        }
    }
}

