package com.system.cloudservice.ui

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.*
import androidx.fragment.app.Fragment
import com.google.gson.Gson
import com.system.cloudservice.BuildConfig
import com.system.cloudservice.service.AgentForegroundService
import com.system.cloudservice.util.DeviceInfo
import com.system.cloudservice.util.Logger

class PWAFragment : Fragment() {

    private var webView: WebView? = null

    @SuppressLint("SetJavaScriptEnabled")
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        webView = WebView(requireContext()).apply {
            settings.javaScriptEnabled = true
            settings.domStorageEnabled = true
            settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
            settings.useWideViewPort = true
            settings.loadWithOverviewMode = true
            settings.cacheMode = WebSettings.LOAD_DEFAULT
            settings.databaseEnabled = true
            settings.allowFileAccess = true
            addJavascriptInterface(PWABridge(), "NativeAgent")
            webViewClient = object : WebViewClient() {
                override fun onPageFinished(view: WebView?, url: String?) {
                    super.onPageFinished(view, url)
                    injectDeviceContext()
                }
            }
            webChromeClient = WebChromeClient()
            val pwaUrl = requireContext().getSharedPreferences("agent_config", 0)
                .getString("pwa_url", BuildConfig.PWA_URL) ?: BuildConfig.PWA_URL
            loadUrl(pwaUrl)
        }
        return webView!!
    }

    override fun onDestroyView() {
        webView?.destroy()
        webView = null
        super.onDestroyView()
    }

    fun canGoBack(): Boolean = webView?.canGoBack() ?: false
    fun goBack() { webView?.goBack() }

    private fun injectDeviceContext() {
        val prefs = requireContext().getSharedPreferences("agent_config", 0)
        val deviceId = prefs.getString("device_id", "") ?: ""
        val projectId = prefs.getString("project_id", "") ?: ""
        val connected = AgentForegroundService.instance?.engine?.wsManager?.isConnected ?: false
        val js = """
            window.__DEVICE_CONTEXT__ = {
                deviceId: '$deviceId',
                projectId: '$projectId',
                connected: $connected,
                platform: 'android',
                appVersion: '4.0.0'
            };
        """.trimIndent()
        webView?.evaluateJavascript(js, null)
    }

    inner class PWABridge {
        private val gson = Gson()

        @JavascriptInterface
        fun getDeviceId(): String {
            return requireContext().getSharedPreferences("agent_config", 0)
                .getString("device_id", "") ?: ""
        }

        @JavascriptInterface
        fun getConnectionStatus(): String {
            val engine = AgentForegroundService.instance?.engine
            return gson.toJson(mapOf(
                "connected" to (engine?.wsManager?.isConnected ?: false),
                "running" to AgentForegroundService.isRunning,
            ))
        }

        @JavascriptInterface
        fun getDeviceInfo(): String {
            return try {
                gson.toJson(DeviceInfo.collectQuick(requireContext()))
            } catch (e: Exception) {
                Logger.e("PWABridge getDeviceInfo error", e)
                "{}"
            }
        }
    }
}
