package com.stand.standapp

import android.animation.ObjectAnimator
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import android.view.animation.AlphaAnimation
import android.view.animation.Animation
import android.view.animation.LinearInterpolator
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.example.kingway.ptt.SendAtUtil
import timber.log.Timber

class TempCallActivity : AppCompatActivity() {

    private var isSpeaking = false
    private var lastSpeakTime = 0L
    private val MIN_SPEAK_DURATION = 200L
    private val handler = Handler(Looper.getMainLooper())
    private var pulseAnimator: ObjectAnimator? = null

    companion object {
        @Volatile
        var instance: TempCallActivity? = null
            private set

        @Volatile
        var isMinimized = false
            private set

        // 存储当前临时群组名称，用于恢复时传递
        @Volatile
        var currentGroupName: String = "临时会话"

        @JvmStatic
        fun isOpen(): Boolean = instance != null

        @JvmStatic
        fun isMinimizedState(): Boolean = isMinimized

        @JvmStatic
        fun maximize() {
            if (isMinimized) {
                isMinimized = false
                val intent = android.content.Intent(
                    com.stand.standapp.MyApplication.getAppInstance(),
                    TempCallActivity::class.java
                )
                intent.putExtra("group_name", currentGroupName)
                intent.addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)
                com.stand.standapp.MyApplication.getAppInstance().startActivity(intent)
            }
        }

        @JvmStatic
        fun closeWithMessage(message: String) {
            val appCtx = com.stand.standapp.MyApplication.getAppInstance()
            instance?.runOnUiThread {
                Toast.makeText(appCtx, message, Toast.LENGTH_SHORT).show()
                instance?.finish()
            } ?: run {
                // Activity 已销毁但状态还在，清除状态
                clearMinimizedState()
            }
        }

        @JvmStatic
        fun clearMinimizedState() {
            isMinimized = false
            currentGroupName = "临时会话"
            MainActivity.executeJs("onTempCallStateChanged('destroyed')")
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 全屏覆盖 + 常亮 + 锁屏显示
        window.addFlags(
            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON or
            WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED or
            WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
        )

        setContentView(R.layout.activity_temp_call)
        instance = this
        isMinimized = false

        val groupName = intent.getStringExtra("group_name") ?: "临时会话"
        currentGroupName = groupName
        findViewById<TextView>(R.id.tv_group_name).text = groupName

        setupMinimizeButton()
        setupPttButton()
        setupHangupButton()
        startPulseAnimation()
    }

    override fun onResume() {
        super.onResume()
        isMinimized = false
    }

    override fun onDestroy() {
        super.onDestroy()
        pulseAnimator?.cancel()
        if (instance == this) {
            instance = null
            // 如果不是最小化状态，说明是真正结束，清除所有状态
            if (!isMinimized) {
                currentGroupName = "临时会话"
            }
            // 通知 web 页面状态变化
            MainActivity.executeJs("onTempCallStateChanged('" + if (isMinimized) "minimized" else "destroyed" + "')")
        }
    }

    // 拦截返回键
    override fun onBackPressed() {
        showMinimizeDialog()
    }

    // 不要在 recent tasks 中显示
    override fun finish() {
        super.finish()
        overridePendingTransition(0, android.R.anim.fade_out)
    }

    fun updateGroupName(name: String) {
        findViewById<TextView>(R.id.tv_group_name)?.text = name
    }

    private fun startPulseAnimation() {
        val pulse = findViewById<ImageView>(R.id.iv_pulse) ?: return
        pulseAnimator = ObjectAnimator.ofFloat(pulse, "alpha", 1f, 0.3f).apply {
            duration = 1000
            repeatCount = ObjectAnimator.INFINITE
            repeatMode = ObjectAnimator.REVERSE
            start()
        }
    }

    private fun setupPttButton() {
        val btnPtt = findViewById<Button>(R.id.btn_ptt)
        val viewGlow = findViewById<View>(R.id.view_glow)

        val startSpeak = {
            if (!isSpeaking) {
                isSpeaking = true
                lastSpeakTime = System.currentTimeMillis()
                SendAtUtil.speakPlay()
                btnPtt.text = "正在\n说话..."
                btnPtt.setBackgroundResource(R.drawable.circle_ptt_speaking)
                viewGlow.setBackgroundResource(R.drawable.circle_ptt_glow_active)
                findViewById<TextView>(R.id.tv_talk_info).text = "正在通话"
                findViewById<TextView>(R.id.tv_talk_status).apply {
                    visibility = View.VISIBLE
                    text = "● 对讲中"
                    setTextColor(0xFFEF4444.toInt())
                }
                Timber.tag("TempCall").d("Speak Play")
            }
        }

        val stopSpeak = {
            if (isSpeaking) {
                val now = System.currentTimeMillis()
                val duration = now - lastSpeakTime
                if (duration < MIN_SPEAK_DURATION) {
                    handler.postDelayed({ realRelease(btnPtt, viewGlow) }, MIN_SPEAK_DURATION - duration)
                } else {
                    realRelease(btnPtt, viewGlow)
                }
            }
        }

        btnPtt.setOnTouchListener { _, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    startSpeak()
                    true
                }
                MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                    stopSpeak()
                    true
                }
                else -> false
            }
        }
    }

    private fun realRelease(btnPtt: Button, viewGlow: View) {
        if (isSpeaking) {
            isSpeaking = false
            SendAtUtil.speakRelease()
            btnPtt.text = "按住\n说话"
            btnPtt.setBackgroundResource(R.drawable.circle_ptt_button)
            viewGlow.setBackgroundResource(R.drawable.circle_ptt_glow)
            findViewById<TextView>(R.id.tv_talk_info).text = "按下按钮讲话"
            findViewById<TextView>(R.id.tv_talk_status).apply {
                visibility = View.GONE
            }
            Timber.tag("TempCall").d("Speak Release")
        }
    }

    private fun setupHangupButton() {
        findViewById<Button>(R.id.btn_hangup).setOnClickListener {
            try {
                SendAtUtil.stopTempCall()
            } catch (e: Exception) {
                Timber.tag("TempCall").e(e, "stopTempCall error")
            }
            finish()
        }
    }

    private fun setupMinimizeButton() {
        findViewById<View>(R.id.ll_minimize).setOnClickListener {
            minimizeAndFinish()
        }
    }

    private fun showMinimizeDialog() {
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("临时呼叫")
            .setMessage("是否最小化临时呼叫页面？")
            .setPositiveButton("最小化") { _, _ ->
                minimizeAndFinish()
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun minimizeAndFinish() {
        isMinimized = true
        // 通知 web 页面临时呼叫页面已最小化
        MainActivity.executeJs("onTempCallStateChanged('minimized')")
        // finish 但保持 isMinimized = true
        finish()
    }

    // 由 GpioManager 调用，同步 GPIO 按下状态
    fun onGpioPressed() {
        val btnPtt = findViewById<Button>(R.id.btn_ptt) ?: return
        val viewGlow = findViewById<View>(R.id.view_glow) ?: return
        if (!isSpeaking) {
            isSpeaking = true
            lastSpeakTime = System.currentTimeMillis()
            SendAtUtil.speakPlay()
            btnPtt.text = "正在\n说话..."
            btnPtt.setBackgroundResource(R.drawable.circle_ptt_speaking)
            viewGlow.setBackgroundResource(R.drawable.circle_ptt_glow_active)
            findViewById<TextView>(R.id.tv_talk_info).text = "正在通话"
            findViewById<TextView>(R.id.tv_talk_status).apply {
                visibility = View.VISIBLE
                text = "● 对讲中"
                setTextColor(0xFFEF4444.toInt())
            }
        }
    }

    // 由 GpioManager 调用，同步 GPIO 松开状态
    fun onGpioReleased() {
        val btnPtt = findViewById<Button>(R.id.btn_ptt) ?: return
        val viewGlow = findViewById<View>(R.id.view_glow) ?: return
        if (isSpeaking) {
            val now = System.currentTimeMillis()
            val duration = now - lastSpeakTime
            if (duration < MIN_SPEAK_DURATION) {
                handler.postDelayed({ realRelease(btnPtt, viewGlow) }, MIN_SPEAK_DURATION - duration)
            } else {
                realRelease(btnPtt, viewGlow)
            }
        }
    }
}
