package com.example.design_system

import android.annotation.SuppressLint
import android.app.Activity
import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.activity.compose.BackHandler
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.viewinterop.AndroidView
import com.example.core.model.PrintEntity
import com.example.design_system.util.PspJavaScriptInterface
import com.example.design_system.util.WebViewManager
import com.example.design_system.util.snackbar.SnackbarController
import com.example.design_system.util.snackbar.SnackbarEvent

import kotlinx.coroutines.launch

@SuppressLint("JavascriptInterface")
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PspWebView(
    url: String,
    modifier: Modifier = Modifier,
    onPayClick: (amount: Long, id: String?) -> Unit,
    onDeviceInfo: () -> String,
    onPrintClick: (printEntities: List<PrintEntity>) -> Unit,
) {

    val canGoBack = remember { mutableStateOf(false) }
    val scope = rememberCoroutineScope()
    val context = LocalContext.current
    var lastBackTime by remember { mutableLongStateOf(0L) }
    var webView by remember { mutableStateOf<WebView?>(null) }


    // Use rememberUpdatedState to ensure the bridge always calls the latest callbacks
    val currentOnPayClick by rememberUpdatedState(onPayClick)
    val currentOnPrintClick by rememberUpdatedState(onPrintClick)
    val currentOnDeviceInfo by rememberUpdatedState(onDeviceInfo)

    val bridge = remember {
        PspJavaScriptInterface(
            onPayClick = { amount, id -> currentOnPayClick(amount, id) },
            onPrintClick = { entities -> currentOnPrintClick(entities) },
            onDeviceInfo = { currentOnDeviceInfo() }
        )
    }

    BackHandler {
        if (canGoBack.value) {
            webView?.goBack()
        } else {
            val now = System.currentTimeMillis()
            if (now - lastBackTime < 2000) {
                (context as? Activity)?.finish()
            } else {
                lastBackTime = now
                scope.launch {
                    SnackbarController.sendEvent(
                        SnackbarEvent(
                            message = "برای خروج، دوباره بر روی بازگشت کلیک کنید."
                        )
                    )
                }
            }
        }
    }

    DisposableEffect(Unit) {
        webView = WebViewManager.getWebView(context)
        onDispose {
            webView?.let { WebViewManager.releaseWebView(it) }
        }
    }

    AndroidView(
        modifier = modifier,
        factory = { ctx ->
            (webView ?: WebViewManager.getWebView(ctx)).apply {
                layoutParams = ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT
                )
                overScrollMode = View.OVER_SCROLL_NEVER
                webViewClient = object : WebViewClient() {
                    override fun onPageFinished(view: WebView?, url: String?) {
                        super.onPageFinished(view, url)
                        canGoBack.value = view?.canGoBack() ?: false
                    }
                }
                
                addJavascriptInterface(bridge, "NativeBridge")
                
                loadUrl(url)
            }
        },
        update = {
            it.loadUrl(url)
        }
    )

}
