/**
 * SettingsFragment.kt
 * SkyLink Android - 设置界面片段
 *
 * 提供应用设置和网络诊断功能
 *
 * @author flowzl
 * @date 2026-01-19
 */

package com.skylink.app.ui

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.*
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.skylink.app.R
import com.skylink.app.utils.PingUtil
import kotlinx.coroutines.launch

class SettingsFragment : Fragment() {

    companion object {
        private const val TAG = "SettingsFragment"
    }

    // ========================================================================
    // UI 组件
    // ========================================================================

    private var udpPortEditText: EditText? = null
    private var hostEditText: EditText? = null
    private var pingCountSpinner: Spinner? = null
    private var timeoutSpinner: Spinner? = null
    private var singlePingButton: Button? = null
    private var multiplePingButton: Button? = null
    private var resultTextView: TextView? = null
    private var progressBar: ProgressBar? = null
    private var clearButton: Button? = null

    private var currentUdpPort = 9999
    private var currentHost = "192.168.1.1"
    private var currentPingCount = 4
    private var currentTimeout = 5

    // ========================================================================
    // 生命周期方法
    // ========================================================================

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

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

    // ========================================================================
    // UI 初始化
    // ========================================================================

    private fun initUI(view: View) {
        udpPortEditText = view.findViewById(R.id.udp_port_input)
        hostEditText = view.findViewById(R.id.host_input)
        pingCountSpinner = view.findViewById(R.id.ping_count_spinner)
        timeoutSpinner = view.findViewById(R.id.timeout_spinner)
        singlePingButton = view.findViewById(R.id.single_ping_button)
        multiplePingButton = view.findViewById(R.id.multiple_ping_button)
        resultTextView = view.findViewById(R.id.result_text)
        progressBar = view.findViewById(R.id.ping_progress)
        clearButton = view.findViewById(R.id.clear_button)

        // 设置初始值
        udpPortEditText?.setText(currentUdpPort.toString())
        hostEditText?.setText(currentHost)

        // 设置 Spinner 选项
        setupSpinners()

        // 隐藏进度条
        progressBar?.visibility = View.GONE
    }

    private fun setupSpinners() {
        // Ping 次数 Spinner
        val countOptions = arrayOf("1", "2", "4", "8", "16")
        val countAdapter = ArrayAdapter(
            requireContext(),
            android.R.layout.simple_spinner_item,
            countOptions
        )
        countAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        pingCountSpinner?.adapter = countAdapter
        pingCountSpinner?.setSelection(2) // 默认选择 4

        // 超时时间 Spinner
        val timeoutOptions = arrayOf("1秒", "3秒", "5秒", "10秒")
        val timeoutAdapter = ArrayAdapter(
            requireContext(),
            android.R.layout.simple_spinner_item,
            timeoutOptions
        )
        timeoutAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        timeoutSpinner?.adapter = timeoutAdapter
        timeoutSpinner?.setSelection(2) // 默认选择 5 秒
    }

    private fun setupListeners() {
        // UDP 端口输入监听
        udpPortEditText?.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?) {
                currentUdpPort = s?.toString()?.toIntOrNull() ?: 9999
            }
        })

        // 主机输入监听
        hostEditText?.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?) {
                currentHost = s?.toString() ?: "192.168.1.1"
            }
        })

        // Ping 次数 Spinner 监听
        pingCountSpinner?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                currentPingCount = when (position) {
                    0 -> 1
                    1 -> 2
                    2 -> 4
                    3 -> 8
                    4 -> 16
                    else -> 4
                }
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {}
        }

        // 超时时间 Spinner 监听
        timeoutSpinner?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                currentTimeout = when (position) {
                    0 -> 1
                    1 -> 3
                    2 -> 5
                    3 -> 10
                    else -> 5
                }
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {}
        }

        // 单个主机 Ping 按钮
        singlePingButton?.setOnClickListener {
            if (currentHost.isEmpty()) {
                Toast.makeText(context, "请输入主机地址", Toast.LENGTH_SHORT).show()
            } else {
                performSinglePing()
            }
        }

        // 多个主机 Ping 按钮
        multiplePingButton?.setOnClickListener {
            performMultiplePing()
        }

        // 清空结果按钮
        clearButton?.setOnClickListener {
            resultTextView?.text = ""
        }
    }

    // ========================================================================
    // Ping 功能实现
    // ========================================================================

    private fun performSinglePing() {
        lifecycleScope.launch {
            showProgress(true)
            resultTextView?.text = "正在 Ping $currentHost..."

            val result = PingUtil.ping(currentHost, currentPingCount, currentTimeout)

            showProgress(false)

            val resultText = if (result.isSuccess) {
                """
                    ✅ Ping 成功!
                    主机: ${result.host}
                    最小延迟: ${result.minTime} ms
                    最大延迟: ${result.maxTime} ms
                    平均延迟: ${result.avgTime} ms
                    丢包率: ${String.format("%.1f", result.packetLoss)}%
                """.trimIndent()
            } else {
                """
                    ❌ Ping 失败
                    主机: ${result.host}
                    错误: ${result.errorMessage}
                """.trimIndent()
            }

            resultTextView?.text = resultText
        }
    }

    private fun performMultiplePing() {
        lifecycleScope.launch {
            showProgress(true)
            resultTextView?.text = "正在 Ping 多个常见地址...\n"

            val commonHosts = listOf(
                "8.8.8.8",           // Google DNS
                "1.1.1.1",           // Cloudflare DNS
                "114.114.114.114",   // 国内 DNS
                "192.168.1.1"        // 本地网关
            )

            val results = PingUtil.pingMultipleParallel(commonHosts, currentPingCount, currentTimeout)

            showProgress(false)

            val resultText = StringBuilder("📊 多主机 Ping 结果:\n\n")
            results.forEach { result ->
                if (result.isSuccess) {
                    resultText.append("✅ ${result.host}\n")
                    resultText.append("   延迟: ${result.avgTime} ms (${result.minTime}~${result.maxTime} ms)\n")
                    resultText.append("   丢包: ${String.format("%.1f", result.packetLoss)}%\n\n")
                } else {
                    resultText.append("❌ ${result.host}\n")
                    resultText.append("   错误: ${result.errorMessage}\n\n")
                }
            }

            resultTextView?.text = resultText.toString()
        }
    }

    private fun showProgress(show: Boolean) {
        progressBar?.visibility = if (show) View.VISIBLE else View.GONE
        singlePingButton?.isEnabled = !show
        multiplePingButton?.isEnabled = !show
    }
}
