package com.gensee.multi_instance.ui.page

import android.content.Context
import androidx.activity.compose.BackHandler
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.detectTransformGestures
import androidx.compose.foundation.gestures.draggable
import androidx.compose.foundation.gestures.rememberDraggableState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.ArrowForward
import androidx.compose.material.icons.filled.Done
import androidx.compose.material3.Button
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CheckboxDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
import androidx.compose.material3.RadioButtonDefaults
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.gensee.common.GenseeConfig
import com.gensee.multi_instance.DemoConfig
import com.gensee.multi_instance.ui.DemoInitParam
import com.gensee.multi_instance.ui.viewmodel.InitParamsViewModel
import com.gensee.multi_instance.utils.FileHelper
import com.gensee.player.Player
import com.gensee.player.VideoRate
import com.gensee.vod.VodMr
import com.google.gson.Gson
import kotlinx.coroutines.launch
import org.burnoutcrew.reorderable.ReorderableItem
import org.burnoutcrew.reorderable.detectReorderAfterLongPress
import org.burnoutcrew.reorderable.rememberReorderableLazyGridState
import org.burnoutcrew.reorderable.reorderable

/**
 *  author : guohaonan
 *  date : 2024/1/22 17:54
 *  description :
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SettingPage(
    last: (() -> Unit)? = null,
    next: (() -> Unit)? = null,
    viewModel: InitParamsViewModel = viewModel()
) {

    val scope = rememberCoroutineScope()
    val snackbarHostState = remember { SnackbarHostState() }
    val context = LocalContext.current
    val infoList = viewModel.videoInfoList

    // 记住解码方式状态
    val (selectedDecodeMethod, onDecodeMethodSelected) = remember { mutableStateOf("软解") }

    val showdoc = remember { mutableStateOf(DemoConfig.isShowDoc) }
    val isMultiPlayer = remember { mutableStateOf(GenseeConfig.isMultiPlayer) }
    val isHls = remember { mutableStateOf(GenseeConfig.isForceFlv) }
    GenseeConfig.isPVHardDecode = false


    val preloadAmount = remember { mutableStateOf(TextFieldValue("" + DemoConfig.preloadNum)) }

    val autoSwipe = remember { mutableStateOf(DemoConfig.isAutoSwipeEnabled) }
    val autoSwipeInterval = remember { mutableStateOf(TextFieldValue("" + DemoConfig.autoSwipeIntervalMs)) }

    Scaffold(
        topBar = {
            TopAppBar(
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.primary,
                    titleContentColor = Color.White,
                ),
                title = {
                    Text("设置页面")
                },
                navigationIcon = {
                    IconButton(onClick = {
                        last?.invoke()
                    }) {
                        Icon(
                            imageVector = Icons.Filled.ArrowBack,
                            contentDescription = "Localized description",
                            tint = Color.White
                        )
                    }
                },
                actions = {
                    IconButton(onClick = {
                        next?.invoke()
                    }) {
                        Icon(
                            imageVector = Icons.Default.Done,
                            contentDescription = "Localized description",
                            tint = Color.White
                        )
                    }
                },

                )
        },
        snackbarHost = {
            SnackbarHost(hostState = snackbarHostState)
        },

        ) { innerPadding ->
        Box(
            modifier = Modifier
                .fillMaxSize()
                .padding(innerPadding)
        ) {

            Column(modifier = Modifier.padding(start = 15.dp, top = 25.dp)) {
                // 导出数据为JSON按钮
                Button(
                    onClick = {
                        val success = exportJson(context, infoList)

                        val msg = if (success) {
                            "成功导出json，目录为documents/output.json"
                        } else {
                            "导出失败"
                        }
                        scope.launch {
                            snackbarHostState.showSnackbar(msg)
                        }
                    },
                    modifier = Modifier
                        .width(190.dp)
                        .height(50.dp)
                ) {
                    Text(text = "导出数据为JSON")
                }

                // 清除缓存按钮
                Spacer(modifier = Modifier.height(20.dp))
                Button(
                    onClick = {
                        VodMr.getIns().initCachDir(context)
                        val success = VodMr.getIns().clearCacheFile()
                        val msg = if (success) {
                            "清除成功"
                        } else {
                            "清除失败"
                        }
                        scope.launch {
                            snackbarHostState.showSnackbar(msg)
                        }

                    },
                    modifier = Modifier
                        .width(130.dp)
                        .height(50.dp)
                ) {
                    Text(text = "清除缓存")
                }

                // 预加载数量输入框
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.padding(top = 20.dp)
                ) {
                    Text(text = "预加载数量：")
                    TextField(
                        value = preloadAmount.value,
                        onValueChange = {

                            // 只允许输入数字
                            if (it.text.length <= 2) {
                                preloadAmount.value = it
                                if (!it.text.isBlank()) {
                                    DemoConfig.preloadNum = it.text.toInt()
                                }

                            }
                        },
                        modifier = Modifier
                            .padding(start = 20.dp)
                            .width(100.dp),
                        keyboardOptions = KeyboardOptions.Default.copy(
                            keyboardType = KeyboardType.Number
                        ),
                        singleLine = true
                    )
                }

                // 解码方式
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.padding(top = 20.dp),
                ) {
                    Text(text = "解码方式：")

                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        modifier = Modifier.padding(start = 20.dp)
                    ) {
                        RadioButton(
                            selected = selectedDecodeMethod == "软解",
                            onClick = {
                                onDecodeMethodSelected("软解")
                                GenseeConfig.isPVHardDecode = false
                            },
                            colors = RadioButtonDefaults.colors(
                                selectedColor = MaterialTheme.colorScheme.primary
                            )
                        )
                        Text(text = "软解")
                    }

                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        modifier = Modifier.padding(start = 20.dp)
                    ) {
                        RadioButton(
                            selected = selectedDecodeMethod == "硬解",
                            onClick = {
                                onDecodeMethodSelected("硬解")
                                GenseeConfig.isPVHardDecode = true
                            },
                            colors = RadioButtonDefaults.colors(
                                selectedColor = MaterialTheme.colorScheme.primary
                            )
                        )
                        Text(text = "硬解")
                    }
                }

                // 直播是否显示文档
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.padding(top = 20.dp)
                ) {
                    Text(text = "直播是否显示文档：")

                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        modifier = Modifier.padding(start = 20.dp)
                    ) {
                        RadioButton(
                            selected = showdoc.value,
                            onClick = {
                                showdoc.value = true
                                DemoConfig.isShowDoc = true
                            },
                            colors = RadioButtonDefaults.colors(
                                selectedColor = MaterialTheme.colorScheme.primary
                            )
                        )
                        Text(text = "是")
                    }

                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        modifier = Modifier.padding(start = 20.dp)
                    ) {
                        RadioButton(
                            selected = !showdoc.value,
                            onClick = {
                                showdoc.value = false
                                DemoConfig.isShowDoc = false
                            },
                            colors = RadioButtonDefaults.colors(
                                selectedColor = MaterialTheme.colorScheme.primary
                            )
                        )
                        Text(text = "否")
                    }
                }

                // 播放模式
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.padding(top = 20.dp)
                ) {
                    Text(text = "播放模式：")

                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        modifier = Modifier.padding(start = 20.dp)
                    ) {
                        RadioButton(
                            selected = !isMultiPlayer.value,
                            onClick = {
                                isMultiPlayer.value = false
                                GenseeConfig.isMultiPlayer = false
                            },
                            colors = RadioButtonDefaults.colors(
                                selectedColor = MaterialTheme.colorScheme.primary
                            )
                        )
                        Text(text = "单实例")
                    }

                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        modifier = Modifier.padding(start = 20.dp)
                    ) {
                        RadioButton(
                            selected = isMultiPlayer.value,
                            onClick = {
                                isMultiPlayer.value = true
                                GenseeConfig.isMultiPlayer = true
                            },
                            colors = RadioButtonDefaults.colors(
                                selectedColor = MaterialTheme.colorScheme.primary
                            )
                        )
                        Text(text = "多实例")
                    }
                }

                // 流格式
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.padding(top = 20.dp)
                ) {
                    Text(text = "视频流格式：")

                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        modifier = Modifier.padding(start = 20.dp)
                    ) {
                        RadioButton(
                            selected = !isHls.value,
                            onClick = {
                                isHls.value = false
                                GenseeConfig.isForceFlv = false
                            },
                            colors = RadioButtonDefaults.colors(
                                selectedColor = MaterialTheme.colorScheme.primary
                            )
                        )
                        Text(text = "RTMP")
                    }

                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        modifier = Modifier.padding(start = 20.dp)
                    ) {
                        RadioButton(
                            selected = isHls.value,
                            onClick = {
                                isHls.value = true
                                GenseeConfig.isForceFlv = true
                            },
                            colors = RadioButtonDefaults.colors(
                                selectedColor = MaterialTheme.colorScheme.primary
                            )
                        )
                        Text(text = "HLS")
                    }
                }

                // 自动滑动压测
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.padding(top = 20.dp)
                ) {
                    Checkbox(
                        checked = autoSwipe.value,
                        onCheckedChange = {
                            autoSwipe.value = it
                            DemoConfig.isAutoSwipeEnabled = it
                        },
                        colors = CheckboxDefaults.colors(
                            checkedColor = MaterialTheme.colorScheme.primary
                        )
                    )
                    Text(text = "自动滑动压测")
                }

                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.padding(top = 10.dp)
                ) {
                    Text(text = "滑动间隔(ms)：")
                    TextField(
                        value = autoSwipeInterval.value,
                        onValueChange = {
                            if (it.text.length <= 5 && it.text.all { c -> c.isDigit() }) {
                                autoSwipeInterval.value = it
                                if (!it.text.isBlank()) {
                                    DemoConfig.autoSwipeIntervalMs = it.text.toLong()
                                }
                            }
                        },
                        enabled = autoSwipe.value,
                        modifier = Modifier
                            .padding(start = 20.dp)
                            .width(120.dp),
                        keyboardOptions = KeyboardOptions.Default.copy(
                            keyboardType = KeyboardType.Number
                        ),
                        singleLine = true
                    )
                }

            }
        }
    }


}

private fun exportJson(context: Context, infoList: List<DemoInitParam>): Boolean {
    if (infoList.isEmpty()) {
        return false
    }
    val json = Gson().toJson(infoList)

    return FileHelper.writeTextToSdCard(
        context,
        "/output.json",
        json
    )
}
