package com.hikoncont

import android.content.Context
import android.graphics.Bitmap
import android.util.Log
import android.webkit.WebChromeClient
import android.webkit.WebView
import android.webkit.WebViewClient
import android.webkit.WebResourceRequest

/**
 * WebView管理器 - 参考 zuiqiang 的简洁实现
 * 极简配置，避免白屏问题
 */
class WebViewManager(private val context: Context) {
    
    companion object {
        private const val TAG = "WebViewManager"
    }
    
    private var webView: WebView? = null
    private var currentUrl: String = ""
    private var callback: WebViewCallback? = null
    
    /**
     * 设置回调
     */
    fun setCallback(callback: WebViewCallback) {
        this.callback = callback
    }
    
    /**
     * 初始化 WebView - 参考 zuiqiang 的简洁实现
     */
    fun initWebView(webView: WebView) {
        this.webView = webView
        
        // 🚀 极简配置 - 参考 zuiqiang 项目
        val settings = webView.settings
        settings.javaScriptEnabled = true
        settings.domStorageEnabled = true
        
        // 🚀 设置 WebViewClient - 参考 zuiqiang 的简洁实现
        webView.webViewClient = object : WebViewClient() {
            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                Log.i(TAG, "✅ WebView加载完成: $url")
                url?.let { currentUrl = it }
                callback?.onPageFinished(url ?: "")
            }
            
            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                super.onPageStarted(view, url, favicon)
            }
            
            override fun onReceivedError(view: WebView?, errorCode: Int, description: String?, failingUrl: String?) {
                // 静默处理错误
            }
        }
        
        // 🚀 设置 WebChromeClient - 参考 zuiqiang 的简洁实现，支持全屏视频
        webView.webChromeClient = object : WebChromeClient() {
            private var customView: android.view.View? = null
            private var customViewCallback: CustomViewCallback? = null
            
            override fun onProgressChanged(view: WebView?, newProgress: Int) {
                super.onProgressChanged(view, newProgress)
            }
            
            override fun onShowCustomView(view: android.view.View?, callback: CustomViewCallback?) {
                super.onShowCustomView(view, callback)
                Log.i(TAG, "🎬 进入全屏视频")
                
                customView = view
                customViewCallback = callback
                
                try {
                    val activity = context as? android.app.Activity
                    if (activity != null) {
                        // 隐藏 WebView 容器
                        val webViewContainer = activity.findViewById<android.view.View>(R.id.webViewContainer)
                        webViewContainer?.visibility = android.view.View.GONE
                        
                        // 显示全屏视频容器
                        val fullScreenContainer = activity.findViewById<android.widget.FrameLayout>(R.id.fullScreenVideoContainer)
                        fullScreenContainer?.visibility = android.view.View.VISIBLE
                        
                        // 将全屏视图添加到容器中
                        if (view != null && fullScreenContainer != null) {
                            fullScreenContainer.removeAllViews()
                            fullScreenContainer.addView(view)
                        }
                        
                        // 隐藏状态栏和导航栏
                        activity.window.decorView.systemUiVisibility = (
                            android.view.View.SYSTEM_UI_FLAG_FULLSCREEN or
                            android.view.View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
                            android.view.View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                        )
                        
                        Log.i(TAG, "✅ 全屏视频布局设置完成")
                    }
                } catch (e: Exception) {
                    Log.e(TAG, "❌ 设置全屏视频失败: ${e.message}")
                }
            }
            
            override fun onHideCustomView() {
                super.onHideCustomView()
                Log.i(TAG, "🎬 退出全屏视频")
                
                try {
                    val activity = context as? android.app.Activity
                    if (activity != null) {
                        // 显示 WebView 容器
                        val webViewContainer = activity.findViewById<android.view.View>(R.id.webViewContainer)
                        webViewContainer?.visibility = android.view.View.VISIBLE
                        
                        // 隐藏全屏视频容器
                        val fullScreenContainer = activity.findViewById<android.widget.FrameLayout>(R.id.fullScreenVideoContainer)
                        fullScreenContainer?.visibility = android.view.View.GONE
                        fullScreenContainer?.removeAllViews()
                        
                        // 恢复状态栏和导航栏
                        activity.window.decorView.systemUiVisibility = android.view.View.SYSTEM_UI_FLAG_VISIBLE
                        
                        Log.i(TAG, "✅ 全屏视频退出完成")
                    }
                } catch (e: Exception) {
                    Log.e(TAG, "❌ 退出全屏视频失败: ${e.message}")
                }
                
                customView = null
                customViewCallback?.onCustomViewHidden()
                customViewCallback = null
            }
            
            override fun onShowFileChooser(
                webView: WebView?, 
                filePathCallback: android.webkit.ValueCallback<Array<android.net.Uri>>?, 
                fileChooserParams: FileChooserParams?
            ): Boolean {
                Log.i(TAG, "📁 显示文件选择器")
                // 这里可以添加文件选择器的处理逻辑
                return true
            }
        }
        
        // 🚀 添加 JavaScript 接口
        webView.addJavascriptInterface(WebAppInterface(), "Android")
        
        Log.i(TAG, "✅ WebView 初始化完成（简洁版）")
    }
    
    /**
     * 显示 WebView
     */
    fun showWebView() {
        webView?.let { webView ->
            webView.visibility = android.view.View.VISIBLE
            Log.i(TAG, "✅ WebView 显示")
        }
    }
    
    /**
     * 隐藏 WebView
     */
    fun hideWebView() {
        webView?.let { webView ->
            webView.visibility = android.view.View.GONE
            Log.i(TAG, "✅ WebView 隐藏")
        }
    }
    
    /**
     * 加载 URL
     */
    fun loadUrl(url: String) {
        webView?.let { webView ->
            webView.loadUrl(url)
            Log.i(TAG, "🌐 加载URL: $url")
        }
    }
    
    /**
     * 获取当前 URL
     */
    fun getCurrentUrl(): String {
        return currentUrl
    }
    
    /**
     * 检查 WebView 是否可见
     */
    fun isVisible(): Boolean {
        return webView?.visibility == android.view.View.VISIBLE
    }
    
    /**
     * JavaScript 接口 - 参考 zuiqiang 的简洁实现
     */
    inner class WebAppInterface {
        @android.webkit.JavascriptInterface
        fun processWebClick(url: String) {
            Log.d(TAG, "🔗 JavaScript点击: $url")
            callback?.onWebClick(url)
        }
    }
    
    /**
     * WebView 回调接口
     */
    interface WebViewCallback {
        fun onPageFinished(url: String)
        fun onWebClick(url: String)
    }
}