package com.aiosman.riderpro.ui.composables

import android.net.http.SslError
import android.webkit.SslErrorHandler
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.text.ClickableText
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import com.aiosman.riderpro.ConstVars
import com.aiosman.riderpro.R
import com.aiosman.riderpro.data.DictService
import com.aiosman.riderpro.data.DictServiceImpl
import kotlinx.coroutines.launch

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PolicyCheckbox(
    checked: Boolean = false,
    error: Boolean = false,
    onCheckedChange: (Boolean) -> Unit,
) {
    var showModal by remember { mutableStateOf(false) }
    var modalSheetState = androidx.compose.material3.rememberModalBottomSheetState(
        skipPartiallyExpanded = true,
    )
    var scope = rememberCoroutineScope()
    val dictService: DictService = DictServiceImpl()
    var policyUrl by remember { mutableStateOf("") }
    fun openPolicyModel() {
        scope.launch {
            try {
                val resp = dictService.getDictByKey(ConstVars.DICT_KEY_PRIVATE_POLICY_URL)
                policyUrl = resp.value
                showModal = true

            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

    }
    if (showModal) {
        ModalBottomSheet(
            onDismissRequest = {
                showModal = false
            },
            sheetState = modalSheetState,
            windowInsets = WindowInsets(0),
            containerColor = Color.White,
        ) {
            WebViewDisplay(
                url = policyUrl
            )
        }
    }
    Row {
        Checkbox(
            checked = checked,
            onCheckedChange = {
                onCheckedChange(it)
            },
            size = 16
        )
        val text = buildAnnotatedString {
            val keyword = stringResource(R.string.private_policy_keyword)
            val template = stringResource(R.string.private_policy_template)
            append(template)
            append(" ")
            withStyle(style = SpanStyle(color = if (error) Color.Red else Color.Black)) {
                append(keyword)
            }

            addStyle(
                style = SpanStyle(
                    color = Color.Red,
                    textDecoration = TextDecoration.Underline
                ),
                start = template.length + 1,
                end = template.length + keyword.length + 1
            )
            append(".")
        }
        ClickableText(
            text = text,
            modifier = Modifier.padding(start = 8.dp),
            onClick = {
                openPolicyModel()
            },
            style = TextStyle(
                fontSize = 12.sp,
                color = if (error) Color.Red else Color.Black
            )
        )
    }
}

@Composable
fun WebViewDisplay(modifier: Modifier = Modifier, url: String) {
    LazyColumn(
        modifier = modifier.fillMaxSize()
    ) {
        item {
            AndroidView(
                factory = { context ->
                    WebView(context).apply {
                        webViewClient = object : WebViewClient() {
                            override fun onReceivedSslError(
                                view: WebView?,
                                handler: SslErrorHandler?,
                                error: SslError?
                            ) {
                                handler?.proceed() // 忽略证书错误
                            }
                        }
                        settings.apply {
                            domStorageEnabled = true
                            mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
                        }
                        loadUrl(url)
                    }
                },
                modifier = modifier.fillMaxSize()
            )
        }
    }

}