package com.gh.gamecenter.setting.compose.activity

import android.annotation.SuppressLint
import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.os.*
import android.preference.PreferenceManager
import androidx.compose.foundation.*
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.*
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.constraintlayout.compose.ChainStyle
import androidx.constraintlayout.compose.ConstraintLayout
import com.therouter.TheRouter
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.exposure.meta.MetaUtil
import com.gh.gamecenter.common.utils.DialogHelper
import com.gh.gamecenter.common.utils.PackageFlavorHelper
import com.gh.gamecenter.common.utils.copyTextAndToast
import com.gh.gamecenter.core.provider.*
import com.gh.gamecenter.core.provider.IUpdateManagerProvider
import com.gh.gamecenter.core.provider.IWebProvider
import com.gh.gamecenter.core.utils.StringUtils
import com.gh.gamecenter.core.utils.TimeUtils
import com.gh.gamecenter.setting.compose.R
import com.gh.gamecenter.setting.compose.base.ComposeBaseActivity
import com.gh.gamecenter.setting.compose.ui.component.*
import com.gh.gamecenter.setting.compose.ui.theme.HaloTheme
import com.lightgame.utils.RuntimeUtils
import com.lightgame.utils.Utils
import java.util.*
import kotlin.jvm.java

class ComposeAboutActivity : ComposeBaseActivity() {

    @SuppressLint("UnusedMaterialScaffoldPaddingParameter")
    @Composable
    override fun Content() {
        var updateVersionText by remember {
            mutableStateOf("")
        }
        var updateAvailable by remember {
            mutableStateOf(false)
        }
        var deviceContent by remember {
            mutableStateOf("")
        }

        val updateManager = TheRouter.get(IUpdateManagerProvider::class.java)
        val updateHandler = object : Handler(Looper.getMainLooper()) {
            override fun handleMessage(msg: Message) {
                super.handleMessage(msg)
                if (msg.what == 0) {
                    val version = msg.obj as String
                    updateVersionText = StringUtils.buildString("发现新版本 V", version)
                    updateAvailable = true
                } else if (msg.what == 1) {
                    updateVersionText = getString(R.string.toast_upload_latest)
                    updateAvailable = false
                }
            }
        }
        updateManager?.checkUpdate(
            this@ComposeAboutActivity,
            true,
        ) // 检查更新

        Scaffold(
            topBar = {
                SettingTopAppBar(getString(R.string.title_about)) {
                    onBackPressed()
                }
            }, modifier = Modifier.fillMaxSize(),
            backgroundColor = HaloTheme.colors.background
        ) {
            val packageUtils = TheRouter.get(IPackageUtilsProvider::class.java)
            val webActivity = TheRouter.get(IWebProvider::class.java)

            Column {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(220.dp),
                    verticalArrangement = Arrangement.Center,
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    var clickCount = 0
                    Image(
                        painter = painterResource(id = R.mipmap.logo_for_in_app_display),
                        contentDescription = null,
                        modifier = Modifier
                            .size(78.dp)
                            .pointerInput(Unit) {
                                detectTapGestures(
                                    onLongPress = {
                                        if (PackageFlavorHelper.IS_TEST_FLAVOR) {
                                            DialogHelper.showDialog(
                                                this@ComposeAboutActivity,
                                                "重选接口环境",
                                                "是否要清空应用数据并重选接口环境\n(清空后数据后需要手动再打开 APP)",
                                                "是",
                                                "否",
                                                {
                                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                                                        (getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager).clearApplicationUserData()
                                                    }
                                                },
                                                extraConfig = DialogHelper.Config(
                                                    centerTitle = true,
                                                    centerContent = true
                                                )
                                            )
                                        } else {
                                            val appProvider = TheRouter.get(IAppProvider::class.java)
                                            Utils.toast(this@ComposeAboutActivity, appProvider?.getChannel())
                                        }
                                    },
                                    onPress = {
                                        if (deviceContent.isNotEmpty()) return@detectTapGestures
                                        if (clickCount == 5) {
                                            val sb = StringBuilder()
                                            val meta = MetaUtil.getMeta()
                                            sb.append("OAID: ").append(meta.oaid).append("\n")
                                            sb.append("ANDROID_ID: ").append(MetaUtil.getAndroidId()).append("\n")
                                            sb.append("GID: ").append(meta.gid).append("\n")
                                            sb.append("USER_ID: ").append(meta.userId).append("\n")
                                            sb.append("CHANNEL: ").append(meta.channel).append("\n")
                                            sb.append("APP_VERSION: ").append(meta.appVersion)
                                            val content = sb.toString().apply { copyTextAndToast("复制成功！") }
                                            deviceContent = content
                                        } else {
                                            clickCount++
                                        }
                                    })
                            })
                    Space(13.dp)
                    Text(
                        text = getString(R.string.app_name),
                        color = HaloTheme.colors.textTitle,
                        fontSize = 23.sp,
                        fontWeight = FontWeight.Bold
                    )
                    Space(2.dp)
                    Text(
                        text = "V" + packageUtils?.getGhVersionName(),
                        color = HaloTheme.colors.textSubtitleDesc,
                        fontSize = 12.sp,
                        modifier = Modifier.pointerInput(Unit) {
                            detectTapGestures(onLongPress = {
                                RuntimeUtils.getInstance()
                                    .toastLong(this@ComposeAboutActivity, getString(R.string.toast_upload_latest))
                            })
                        })
                }
                SettingItem(
                    getString(R.string.about_version_update),
                    content = updateVersionText,
                    contentColor = if (updateAvailable) HaloTheme.colors.themeFont else HaloTheme.colors.textSubtitleDesc
                ) {
                    updateManager?.checkUpdate(
                        this@ComposeAboutActivity,
                        true,
                    ) // 检查更新
                }
                SettingDivider()
                SettingItem("用户协议", showArrow = true) {
                    startActivity(
                        webActivity?.getWebIntent(
                            this@ComposeAboutActivity,
                            getString(com.gh.gamecenter.common.R.string.disclaimer_title),
                            getString(com.gh.gamecenter.common.R.string.disclaimer_url)
                        )
                    )
                }
                SettingDivider()
                SettingItem("隐私政策", showArrow = true) {
                    startActivity(
                        webActivity?.getWebIntent(
                            this@ComposeAboutActivity,
                            getString(com.gh.gamecenter.common.R.string.privacy_policy_title),
                            getString(com.gh.gamecenter.common.R.string.privacy_policy_url)
                        )
                    )
                }
                SettingDivider()
                SettingItem("官方抖音", showArrow = true, content = "光环助手APP") {
                    val url = getString(R.string.gh_douyin_url)
                    url.copyTextAndToast(String.format(Locale.CHINA, "已成功复制%s ，打开抖音可直达", url))
                    val directUtils = TheRouter.get(IDirectProvider::class.java)
                    directUtils?.directDouyin(this@ComposeAboutActivity, "1402577827140941")
                }
                if (deviceContent.isNotEmpty()) {
                    Text(
                        text = deviceContent,
                        lineHeight = 21.sp,
                        fontSize = 14.sp,
                        textAlign = TextAlign.Center,
                        modifier = Modifier
                            .fillMaxWidth()
                            .wrapContentHeight()
                            .padding(0.dp, 8.dp, 0.dp, 0.dp)
                    )
                }
                ConstraintLayout(
                    modifier = Modifier
                        .fillMaxWidth()
                        .fillMaxHeight()
                ) {
                    val (copyrightCN, copyrightEn, icpDesc, icpHref) = createRefs()
                    val serverTime = PreferenceManager.getDefaultSharedPreferences(this@ComposeAboutActivity)
                        .getLong("server_time", 1587693163L)
                    val year = TimeUtils.getFormatTime(serverTime, "yyyy")
                    Text(text = "Copyright $year GHZhuShou Team All Rights Reserved.",
                        fontSize = 11.sp,
                        color = HaloTheme.colors.textSubtitleDesc,
                        modifier = Modifier.constrainAs(copyrightEn) {
                            bottom.linkTo(icpDesc.top, 16.dp)
                            start.linkTo(parent.start)
                            end.linkTo(parent.end)
                        })

                    Text(text = "光环工作室 版权所有",
                        fontSize = 11.sp,
                        color = HaloTheme.colors.textSubtitleDesc,
                        modifier = Modifier
                            .constrainAs(copyrightCN) {
                                bottom.linkTo(copyrightEn.top, 16.dp)
                                start.linkTo(parent.start)
                                end.linkTo(parent.end)
                            })

                    Text(text = getString(com.gh.gamecenter.common.R.string.icp_serial_numb_desc),
                        fontSize = 11.sp,
                        color = HaloTheme.colors.textSubtitleDesc,
                        modifier = Modifier
                            .constrainAs(icpDesc) {
                                bottom.linkTo(parent.bottom, 32.dp)
                                start.linkTo(parent.start)
                                end.linkTo(icpHref.start)
                            })

                    Text(text = getString(com.gh.gamecenter.common.R.string.icp),
                        fontSize = 11.sp,
                        color = HaloTheme.colors.themeFont,
                        modifier = Modifier
                            .padding(start = 8.dp)
                            .constrainAs(icpHref) {
                                bottom.linkTo(parent.bottom, 32.dp)
                                start.linkTo(icpDesc.end)
                                end.linkTo(parent.end)
                                top.linkTo(icpDesc.top)
                            }
                            .clickable {
                                val directUtils = TheRouter.get(IDirectProvider::class.java)
                                directUtils?.directToExternalBrowser(
                                    this@ComposeAboutActivity,
                                    getString(com.gh.gamecenter.common.R.string.icp_url)
                                )
                            })

                    createHorizontalChain(icpDesc, icpHref, chainStyle = ChainStyle.Packed)
                }
            }
        }
    }

    companion object {
        fun getIntent(context: Context?, isUpdate: Boolean): Intent {
            return Intent(context, ComposeAboutActivity::class.java).apply {
                putExtra(EntranceConsts.KEY_VERSION_UPDATE, isUpdate)
            }
        }
    }
}