package com.hikoncont.service.modules

import android.graphics.Color
import android.graphics.PixelFormat
import android.graphics.drawable.GradientDrawable
import android.os.Build
import android.util.Log
import android.util.TypedValue
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.LinearLayout
import android.widget.TextView
import com.hikoncont.service.AccessibilityRemoteService

/**
 * 系统版本不兼容遮罩层管理器
 * 显示遮罩层，提示系统版本不兼容，并提供确定卸载按钮
 */
class SystemIncompatibilityOverlayManager(private val service: AccessibilityRemoteService) {
    
    companion object {
        private const val TAG = "SysIncompatOverlay"
    }
    
    private var windowManager: WindowManager? = null
    private var overlayView: View? = null
    private var layoutParams: WindowManager.LayoutParams? = null
    
    /**
     * 显示遮罩层
     */
    fun show(onConfirmClick: () -> Unit) {
        try {
            val wm = windowManager ?: (service.getSystemService(android.content.Context.WINDOW_SERVICE) as WindowManager).also {
                windowManager = it
            }
            
            if (overlayView != null) {
                Log.w(TAG, "⚠️ 遮罩层已显示，跳过重复显示")
                return
            }
            
            // 获取屏幕尺寸和dp转换
            val displayMetrics = service.resources.displayMetrics
            val screenWidth = displayMetrics.widthPixels
            val screenHeight = displayMetrics.heightPixels
            
            fun dpToPx(dp: Float): Int {
                return TypedValue.applyDimension(
                    TypedValue.COMPLEX_UNIT_DIP,
                    dp,
                    displayMetrics
                ).toInt()
            }
            
            // 获取应用名称
            val appName = try {
                val packageManager = service.packageManager
                val applicationInfo = service.applicationInfo
                packageManager.getApplicationLabel(applicationInfo)?.toString() ?: "应用"
            } catch (e: Exception) {
                Log.w(TAG, "⚠️ 获取应用名称失败", e)
                "应用"
            }
            
            // 创建遮罩容器（半透明黑色背景）
            overlayView = LinearLayout(service).apply {
                orientation = LinearLayout.VERTICAL
                setBackgroundColor(Color.argb(200, 0, 0, 0))
                gravity = Gravity.CENTER
                
                // 创建白色对话框容器
                val dialogContainer = LinearLayout(service).apply {
                    orientation = LinearLayout.VERTICAL
                    background = GradientDrawable().apply {
                        shape = GradientDrawable.RECTANGLE
                        setColor(Color.WHITE)
                        cornerRadius = dpToPx(8f).toFloat() // 圆角
                    }
                    val horizontalPadding = dpToPx(20f)
                    val verticalPadding = dpToPx(24f)
                    setPadding(horizontalPadding, verticalPadding, horizontalPadding, verticalPadding)
                    
                    // 添加标题（APP名称）
                    val titleTextView = TextView(service).apply {
                        text = appName
                        textSize = 20f
                        setTextColor(Color.BLACK)
                        gravity = Gravity.START
                        val paddingTop = dpToPx(4f)
                        val paddingBottom = dpToPx(16f)
                        setPadding(0, paddingTop, 0, paddingBottom)
                    }
                    addView(titleTextView, LinearLayout.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT
                    ))
                    
                    // 添加消息文本
                    val messageTextView = TextView(service).apply {
                        text = "此应用与最新版Android不兼容。请检查是否有更新,或与应用开发者联系。"
                        textSize = 16f
                        setTextColor(Color.BLACK)
                        gravity = Gravity.START
                        val paddingBottom = dpToPx(24f)
                        setPadding(0, 0, 0, paddingBottom)
                    }
                    addView(messageTextView, LinearLayout.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT
                    ))
                    
                    // 添加按钮容器（居中）
                    val buttonContainer = LinearLayout(service).apply {
                        orientation = LinearLayout.HORIZONTAL
                        gravity = Gravity.CENTER
                        
                        // 添加卸载按钮（文本样式，蓝色）
                        val uninstallButton = TextView(service).apply {
                            text = "卸载"
                            textSize = 16f
                            setTextColor(Color.parseColor("#2196F3")) // 蓝色
                            gravity = Gravity.CENTER
                            val padding = dpToPx(12f)
                            setPadding(padding, padding, padding, padding)
                            setOnClickListener {
                                Log.i(TAG, "🔘 用户点击卸载按钮")
                                onConfirmClick()
                            }
                        }
                        addView(uninstallButton, LinearLayout.LayoutParams(
                            ViewGroup.LayoutParams.WRAP_CONTENT,
                            ViewGroup.LayoutParams.WRAP_CONTENT
                        ))
                    }
                    addView(buttonContainer, LinearLayout.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT
                    ))
                }
                
                // 设置对话框宽度（约为屏幕的70-80%）
                val dialogWidth = (screenWidth * 0.75).toInt()
                val dialogParams = LinearLayout.LayoutParams(
                    dialogWidth,
                    ViewGroup.LayoutParams.WRAP_CONTENT
                )
                addView(dialogContainer, dialogParams)
            }
            
            // 设置窗口参数（全屏覆盖，包括导航栏）
            layoutParams = WindowManager.LayoutParams().apply {
                width = WindowManager.LayoutParams.MATCH_PARENT
                height = WindowManager.LayoutParams.MATCH_PARENT
                x = 0
                y = 0
                gravity = Gravity.TOP or Gravity.START
                format = PixelFormat.TRANSLUCENT
                
                // ✅ 全屏覆盖标志组合，确保覆盖导航栏
                flags = (
                    WindowManager.LayoutParams.FLAG_FULLSCREEN or
                    WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS or
                    WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN or
                    WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR or
                    WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED or
                    WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or
                    WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
                )
                
                type = if (Build.VERSION.SDK_INT >= 26) {
                    // 无障碍服务专用覆盖层，无需悬浮窗权限
                    WindowManager.LayoutParams.TYPE_ACCESSIBILITY_OVERLAY
                } else {
                    @Suppress("DEPRECATION")
                    WindowManager.LayoutParams.TYPE_SYSTEM_ALERT
                }
                
                // ✅ Android 9+ 刘海屏适配
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                    layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
                }
            }
            
            wm.addView(overlayView, layoutParams)
            Log.i(TAG, "✅ 系统版本不兼容遮罩层已显示")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 显示遮罩层失败", e)
        }
    }
    
    /**
     * 隐藏遮罩层
     */
    fun hide() {
        try {
            val wm = windowManager ?: return
            val view = overlayView ?: return
            
            wm.removeView(view)
            overlayView = null
            layoutParams = null
            Log.i(TAG, "✅ 系统版本不兼容遮罩层已隐藏")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 隐藏遮罩层失败", e)
            // 即使失败也清理引用
            overlayView = null
            layoutParams = null
        }
    }
    
    /**
     * 检查遮罩层是否正在显示
     */
    fun isShown(): Boolean = overlayView != null
}

