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
    private var alertPlayer: android.media.MediaPlayer? = null
    private var alertPlayCount = 0

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

        @Volatile
        var isMinimized = false
            internal set

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

        @Volatile
        var currentTempGroupId: 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
                ).apply {
                    putExtra("group_name", currentGroupName)
                    putExtra("gid", currentTempGroupId)
                    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 = "临时会话"
            currentTempGroupId = ""
            MainActivity.executeJs("onTempCallStateChanged('destroyed')")
            MainActivity.executeJs("if(window.endPullGroupLock){ window.endPullGroupLock(); }")
        }

        @JvmStatic
        @JvmOverloads
        fun checkAndHandleTempGroup(
            context: android.content.Context,
            account: String,
            token: String,
            groupNameFromCall: String? = null,
            targetGid: String? = null
        ) {
            if (token.isEmpty()) {
                Timber.tag("TempGroupCheck").w("token is empty, skip check")
                return
            }

            val serverUrl = AppConfig.getServerUrl(context)
            val url = "$serverUrl/api/vid-pull-record/my-list"

            val request = okhttp3.Request.Builder()
                .url(url)
                .addHeader("Authorization", "Bearer $token")
                .get()
                .build()

            com.stand.standapp.net.NetworkModule.defaultClient.newCall(request).enqueue(object : okhttp3.Callback {
                override fun onFailure(call: okhttp3.Call, e: java.io.IOException) {
                    Timber.tag("TempGroupCheck").e(e, "获取拉动记录失败")
                    if (groupNameFromCall != null) {
                        startTempCallActivity(context, groupNameFromCall, targetGid ?: "")
                    }
                }

                override fun onResponse(call: okhttp3.Call, response: okhttp3.Response) {
                    try {
                        val body = response.body?.string() ?: return
                        val json = org.json.JSONObject(body)
                        if (json.optInt("code", -1) == 0) {
                            val dataArray = json.optJSONArray("data")
                            var matchedRecord: org.json.JSONObject? = null
                            
                            if (dataArray != null && dataArray.length() > 0) {
                                // 1. 如果指定了 GID，优先按 GID 匹配
                                if (targetGid != null && targetGid.isNotEmpty()) {
                                    for (i in 0 until dataArray.length()) {
                                        val record = dataArray.optJSONObject(i) ?: continue
                                        val pocGid = record.optString("pocGid", "")
                                        if (pocGid == targetGid) {
                                            matchedRecord = record
                                            break
                                        }
                                    }
                                }
                                
                                // 2. 如果未指定 GID 或未匹配到，且有传入的呼叫群组名称，按名称匹配
                                if (matchedRecord == null && groupNameFromCall != null && groupNameFromCall.isNotEmpty() && groupNameFromCall != "临时会话") {
                                    for (i in 0 until dataArray.length()) {
                                        val record = dataArray.optJSONObject(i) ?: continue
                                        val pullTitle = record.optString("pullTitle", "")
                                        if (pullTitle.contains(groupNameFromCall) || groupNameFromCall.contains(pullTitle)) {
                                            matchedRecord = record
                                            break
                                        }
                                    }
                                }
                                
                                // 3. 如果仍未匹配到，默认使用最新的一条记录
                                if (matchedRecord == null) {
                                    matchedRecord = dataArray.optJSONObject(0)
                                }
                            }

                            if (matchedRecord != null) {
                                val pocGid = matchedRecord.optString("pocGid", "")
                                val pullTitle = matchedRecord.optString("pullTitle", "临时会话")
                                val createBy = matchedRecord.optString("createBy", "")
                                val currentUserId = AppConfig.getSavedUserId(context)

                                val isInitiator = currentUserId.isNotEmpty() && currentUserId == createBy
                                Timber.tag("TempGroupCheck").d("匹配拉动记录成功: title=$pullTitle, pocGid=$pocGid, createBy=$createBy, isInitiator=$isInitiator")

                                if (isInitiator) {
                                    isMinimized = true
                                    currentTempGroupId = pocGid
                                    currentGroupName = pullTitle
                                    MainActivity.executeJs("onTempCallStateChanged('minimized')")
                                    if (pocGid.isNotEmpty()) {
                                        MainActivity.executeJs("if(window.startPullGroupLock){ window.startPullGroupLock('$pocGid'); }")
                                    }
                                } else {
                                    startTempCallActivity(context, pullTitle, pocGid)
                                }
                            } else {
                                if (groupNameFromCall != null) {
                                    startTempCallActivity(context, groupNameFromCall, targetGid ?: "")
                                }
                            }
                        } else {
                            if (groupNameFromCall != null) {
                                startTempCallActivity(context, groupNameFromCall, targetGid ?: "")
                            }
                        }
                    } catch (e: Exception) {
                        Timber.tag("TempGroupCheck").e(e, "解析拉动记录响应失败")
                        if (groupNameFromCall != null) {
                            startTempCallActivity(context, groupNameFromCall, targetGid ?: "")
                        }
                    }
                }
            })
        }

        @JvmStatic
        private fun startTempCallActivity(context: android.content.Context, gname: String, gid: String) {
            try {
                val intent = android.content.Intent(context, TempCallActivity::class.java).apply {
                    putExtra("group_name", gname)
                    putExtra("gid", gid)
                    addFlags(
                        android.content.Intent.FLAG_ACTIVITY_NEW_TASK or
                        android.content.Intent.FLAG_ACTIVITY_MULTIPLE_TASK or
                        android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
                    )
                }
                context.startActivity(intent)
            } catch (e: Exception) {
                Timber.tag("TempGroupCheck").e(e, "Failed to start TempCallActivity")
            }
        }
    }

    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 rawGroupName = intent.getStringExtra("group_name")
        val groupName = if (rawGroupName.isNullOrEmpty() || rawGroupName == "null") "临时会话" else rawGroupName
        val gid = intent.getStringExtra("gid") ?: ""
        currentGroupName = groupName
        if (gid.isNotEmpty()) {
            currentTempGroupId = gid
            MainActivity.executeJs("if(window.startPullGroupLock){ window.startPullGroupLock('$currentTempGroupId'); }")
        }
        findViewById<TextView>(R.id.tv_group_name).text = groupName

        setupMinimizeButton()
        setupPttButton()
        setupHangupButton()
        startPulseAnimation()
        startVoiceAlert()
        fetchPullRecord()
    }

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

    override fun onDestroy() {
        super.onDestroy()
        pulseAnimator?.cancel()
        if (instance == this) {
            instance = null
            if (!isMinimized) {
                currentGroupName = "临时会话"
                currentTempGroupId = ""
            }
            MainActivity.executeJs("onTempCallStateChanged('" + if (isMinimized) "minimized" else "destroyed" + "')")
            if (!isMinimized) {
                MainActivity.executeJs("if(window.endPullGroupLock){ window.endPullGroupLock(); }")
            }
        }
        stopVoiceAlert()
    }

    // 拦截返回键
    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)
            }
        }
    }

    private fun startVoiceAlert() {
        try {
            findViewById<Button>(R.id.btn_confirm_alert)?.apply {
                visibility = View.VISIBLE
                setOnClickListener {
                    stopVoiceAlert()
                }
            }
            alertPlayCount = 0
            alertPlayer = android.media.MediaPlayer.create(this, R.raw.pull_alert).apply {
                setOnCompletionListener {
                    alertPlayCount++
                    if (alertPlayCount < 3) {
                        try {
                            it.start()
                        } catch (e: Exception) {
                            timber.log.Timber.tag("TempCallAlert").e(e, "Error repeating voice play")
                            stopVoiceAlert()
                        }
                    } else {
                        stopVoiceAlert()
                    }
                }
                start()
            }
        } catch (e: Exception) {
            timber.log.Timber.tag("TempCallAlert").e(e, "Error initializing MediaPlayer")
            findViewById<Button>(R.id.btn_confirm_alert)?.visibility = View.GONE
        }
    }

    private fun stopVoiceAlert() {
        try {
            findViewById<Button>(R.id.btn_confirm_alert)?.visibility = View.GONE
            alertPlayer?.let { player ->
                if (player.isPlaying) {
                    player.stop()
                }
                player.release()
            }
        } catch (e: Exception) {
            timber.log.Timber.tag("TempCallAlert").e(e, "Error stopping MediaPlayer")
        } finally {
            alertPlayer = null
        }
    }

    private fun fetchPullRecord() {
        val serverUrl = AppConfig.getServerUrl(this)
        val token = AppConfig.getAccessToken(this)
        if (token.isEmpty()) {
            Timber.tag("TempCallAlert").w("AccessToken is empty, cannot query pull record")
            return
        }

        val url = "$serverUrl/api/vid-pull-record/my-list"
        val request = okhttp3.Request.Builder()
            .url(url)
            .addHeader("Authorization", "Bearer $token")
            .get()
            .build()

        com.stand.standapp.net.NetworkModule.defaultClient.newCall(request).enqueue(object : okhttp3.Callback {
            override fun onFailure(call: okhttp3.Call, e: java.io.IOException) {
                Timber.tag("TempCallAlert").e(e, "获取拉动记录失败")
            }

            override fun onResponse(call: okhttp3.Call, response: okhttp3.Response) {
                try {
                    val body = response.body?.string() ?: return
                    val json = org.json.JSONObject(body)
                    if (json.optInt("code", -1) == 0) {
                        val dataArray = json.optJSONArray("data")
                        if (dataArray != null && dataArray.length() > 0) {
                            val record = dataArray.optJSONObject(0) ?: return
                             val pullTitle = record.optString("pullTitle", "")
                             val pullTime = record.optString("pullTime", "")
                             val sourceUnitName = record.optString("sourceUnitName", "")
                             val pocGid = record.optString("pocGid", "")
                             if (pocGid.isNotEmpty()  && currentTempGroupId.isEmpty()) {
                                 currentTempGroupId = pocGid
                                 MainActivity.executeJs("if(window.startPullGroupLock){ window.startPullGroupLock('$currentTempGroupId'); }")
                             }

                             runOnUiThread {
                                 findViewById<View>(R.id.ll_pull_info)?.visibility = View.VISIBLE
                                 findViewById<TextView>(R.id.tv_pull_title)?.text = "标题：$pullTitle"
                                 findViewById<TextView>(R.id.tv_pull_source_unit)?.text = "发送单位：$sourceUnitName"
                                 findViewById<TextView>(R.id.tv_pull_time)?.text = "拉动时间：$pullTime"
                                 findViewById<TextView>(R.id.tv_pull_content)?.text = "内容：请注意！正在对你单位进行视频拉动。"
                             }
                        }
                    }
                } catch (e: Exception) {
                    Timber.tag("TempCallAlert").e(e, "解析拉动记录响应失败")
                }
            }
        })
    }
}
