package com.aiosman.ravenow.ui.login

import android.content.ContentValues.TAG
import android.content.res.Resources
import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.rememberScrollableState
import androidx.compose.foundation.gestures.scrollable
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.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.aiosman.ravenow.AppState
import com.aiosman.ravenow.AppStore
import com.aiosman.ravenow.ConstVars
import com.aiosman.ravenow.data.api.ErrorCode
import com.aiosman.ravenow.LocalAppTheme
import com.aiosman.ravenow.LocalNavController
import com.aiosman.ravenow.R
import com.aiosman.ravenow.data.AccountServiceImpl
import com.aiosman.ravenow.data.DictService
import com.aiosman.ravenow.data.DictServiceImpl
import com.aiosman.ravenow.data.ServiceException
import com.aiosman.ravenow.data.api.getErrorMessageCode
import com.aiosman.ravenow.data.api.showToast
import com.aiosman.ravenow.ui.NavigationRoute
import com.aiosman.ravenow.ui.composables.ActionButton
import com.aiosman.ravenow.ui.modifiers.noRippleClickable
import com.aiosman.ravenow.utils.GoogleLogin
import com.google.accompanist.systemuicontroller.rememberSystemUiController
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import com.airbnb.lottie.compose.LottieAnimation
import com.airbnb.lottie.compose.LottieCompositionSpec
import com.airbnb.lottie.compose.LottieConstants
import com.airbnb.lottie.compose.rememberLottieComposition

@Preview
@Composable
fun LoginPage() {
    val navController = LocalNavController.current
    val context = LocalContext.current
    val coroutineScope = rememberCoroutineScope()
    val accountService = AccountServiceImpl()
    val statusBarController = rememberSystemUiController()
    val AppColors = LocalAppTheme.current
    val dictService: DictService = DictServiceImpl()
    var showGoogleLogin by remember {
        mutableStateOf(false)
    }
    suspend fun checkGoogleLoginEnable() {
        try {
            val result = dictService.getDistList(
                listOf(
                    ConstVars.DICT_KEY_ENABLE_GOOGLE_LOGIN,
                    ConstVars.DICT_KEY_GOOGLE_LOGIN_CLIENT_ID
                )
            )
            val enableDictItem = result.find { it.key == ConstVars.DICT_KEY_ENABLE_GOOGLE_LOGIN }
            val clientIdDictItem = result.find { it.key == ConstVars.DICT_KEY_GOOGLE_LOGIN_CLIENT_ID }
            if (enableDictItem != null && clientIdDictItem != null) {
                AppState.googleClientId = clientIdDictItem.value as? String
                showGoogleLogin = enableDictItem.value == true
            } else {
                showGoogleLogin = false
            }
            AppState.enableGoogleLogin = showGoogleLogin
        } catch (_: Exception) {

        }
    }
    LaunchedEffect(Unit) {
        statusBarController.setStatusBarColor(Color.Transparent, darkIcons = !AppState.darkMode)
        checkGoogleLoginEnable()
    }


    fun googleLogin() {
        val clientId = AppState.googleClientId
        if (clientId == null) {
            Toast.makeText(context, "Google login is not enabled", Toast.LENGTH_SHORT).show()
            return
        }
        coroutineScope.launch {
            try {
                GoogleLogin(context, clientId) {
                    coroutineScope.launch {
                        try {
                            accountService.regiterUserWithGoogleAccount(it)
                        } catch (e: ServiceException) {
                            when (e.errorType) {
                                ErrorCode.USER_EXIST ->
                                    Toast.makeText(
                                        context,
                                        context.getErrorMessageCode(e.errorType.code),
                                        Toast.LENGTH_SHORT
                                    ).show()

                                else -> {
                                    e.errorType.showToast(context)
                                }
                            }
                            Log.e(TAG, "Failed to register with google", e)
                            return@launch
                        } catch (e: Exception) {
                            Log.e(TAG, "Failed to register with google", e)
                            return@launch
                        }
                        // 获取用户信息
                        // 获取 token
                        val authResp = accountService.loginUserWithGoogle(it)
                        if (authResp.token != null) {
                            coroutineScope.launch(Dispatchers.Main) {
                                Toast.makeText(
                                    context,
                                    "Successfully registered",
                                    Toast.LENGTH_SHORT
                                )
                                    .show()
                            }
                        }
                        AppStore.apply {
                            token = authResp.token
                            this.rememberMe = true
                            isGuest = false  // 清除游客状态
                            saveData()
                        }
                        // 获取token 信息
                        try {
                            AppState.initWithAccount(coroutineScope, context)
                        } catch (e: Exception) {
                            Log.e(TAG, "Failed to init with account", e)
                        } catch (e: ServiceException) {
                            coroutineScope.launch(Dispatchers.Main) {
                                Toast.makeText(context, "Failed to get account", Toast.LENGTH_SHORT)
                                    .show()
                            }
                        }
                        coroutineScope.launch(Dispatchers.Main) {
                            navController.navigate(NavigationRoute.Index.route) {
                                popUpTo(NavigationRoute.Login.route) { inclusive = true }
                            }
                        }
                    }

                }
            } catch (e: Exception) {
                Toast.makeText(context, e.message, Toast.LENGTH_SHORT).show()
            }

        }
    }

    fun guestLogin() {
        coroutineScope.launch {
            try {
                // 生成设备ID
                val deviceId = android.provider.Settings.Secure.getString(
                    context.contentResolver,
                    android.provider.Settings.Secure.ANDROID_ID
                ) ?: "unknown_device"
                
                // 获取设备信息
                val deviceInfo = "${android.os.Build.MANUFACTURER} ${android.os.Build.MODEL}"
                
                // 调用游客登录API
                val authResp = accountService.guestLogin(deviceId, deviceInfo)
                
                // 保存token和游客状态
                AppStore.apply {
                    token = authResp.token
                    isGuest = true
                    rememberMe = true
                    saveData()
                }
                
//                // 显示成功提示
//                coroutineScope.launch(Dispatchers.Main) {
//                    Toast.makeText(
//                        context,
//                        "游客登录成功",
//                        Toast.LENGTH_SHORT
//                    ).show()
//                }
                
                // 初始化应用状态（游客模式会自动跳过推送和TRTC初始化）
                try {
                    AppState.initWithAccount(coroutineScope, context)
                } catch (e: Exception) {
                    Log.e(TAG, "Failed to init with guest account", e)
                    // 游客模式下初始化失败不是致命错误，可以继续
                }
                
                // 导航到主页
                coroutineScope.launch(Dispatchers.Main) {
                    navController.navigate(NavigationRoute.Index.route) {
                        popUpTo(NavigationRoute.Login.route) { inclusive = true }
                    }
                }
                
            } catch (e: ServiceException) {
                coroutineScope.launch(Dispatchers.Main) {
                    Toast.makeText(
                        context,
                        "游客登录失败: ${e.message}",
                        Toast.LENGTH_SHORT
                    ).show()
                }
                Log.e(TAG, "Guest login failed", e)
            } catch (e: Exception) {
                coroutineScope.launch(Dispatchers.Main) {
                    Toast.makeText(
                        context,
                        "游客登录失败",
                        Toast.LENGTH_SHORT
                    ).show()
                }
                Log.e(TAG, "Guest login failed", e)
            }
        }
    }

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(AppColors.background)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 24.dp)
                .padding(top = 60.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Box(
                modifier = Modifier
                    .size(30.dp)

                    .noRippleClickable {
                        guestLogin()
                    },
                contentAlignment = Alignment.Center
            ) {
                Image(
                    painter = painterResource(id = R.drawable.rider_pro_close),
                    contentDescription = "Close",
                    modifier = Modifier.size(24.dp),
                    colorFilter = ColorFilter.tint(AppColors.text)
                )
            }
        }


        Spacer(modifier = Modifier.height(20.dp))
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(horizontal = 24.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Spacer(modifier = Modifier.weight(1f))
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(400.dp)

            ) {
                val lottieFile = "login.lottie"
                LottieAnimation(
                    composition = rememberLottieComposition(LottieCompositionSpec.Asset(lottieFile)).value,
                    iterations = LottieConstants.IterateForever,
                    modifier = Modifier.fillMaxSize()
                )
            }
            Image(
                painter = painterResource(if(AppState.darkMode)  R.mipmap.login_paipia_dark else R.mipmap.login_paipia_light),
                contentDescription = "",
                modifier = Modifier
                    .size(width = 140.dp, height = 30.dp)
            )
            Spacer(modifier = Modifier.height(10.dp))
            Text(
                text = stringResource(R.string.join_party_carnival),
                fontSize = 17.sp,
                color = AppColors.text.copy(alpha = 0.6f),
                fontWeight = FontWeight.W600,
            )
//            Spacer(modifier = Modifier.height(8.dp))
//            Text(
//                "Rave Now",
//                fontSize = 28.sp,
//                fontWeight = FontWeight.W900,
//                color = AppColors.text
//            )
//            Spacer(modifier = Modifier.height(16.dp))
//            Text(
//                "Your Night Starts Here",
//                fontSize = 20.sp,
//                fontWeight = FontWeight.W700,
//                color = AppColors.text
//            )
            //登录tab
            Spacer(modifier = Modifier.height(35.dp))
            ActionButton(
                modifier = Modifier.fillMaxWidth(),
                text = stringResource(R.string.login_upper),
                color = if (AppState.darkMode) Color.Black else Color.White,
                backgroundColor = if (AppState.darkMode) Color.White else Color.Black
            ) {
                    navController.navigate(
                        NavigationRoute.UserAuth.route,
                )
            }
           //谷歌登录tab
                Spacer(modifier = Modifier.height(16.dp))
                ActionButton(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(52.dp)
                        .border(
                            width = 1.5.dp,
                            color = if (AppState.darkMode) Color.White else Color.Black,
                            shape = RoundedCornerShape(24.dp)
                        ),
                    text = stringResource(R.string.sign_in_with_google),
                    color = if (AppState.darkMode) Color.White else Color.Black,
                    backgroundColor = if (AppState.darkMode) Color.Black else Color.White,
                    leading = {
                        Image(
                            painter = painterResource(id = R.mipmap.rider_pro_signup_google),
                            contentDescription = "Google",
                            modifier = Modifier.size(18.dp),
                        )
                    },
                    expandText = true,
                    contentPadding = PaddingValues(vertical = 8.dp, horizontal = 10.dp)
                ) {
                    googleLogin()
                }

            //注册tab
            Spacer(modifier = Modifier.height(24.dp))
            Text(
                text = stringResource(R.string.sign_up_upper),
                color = AppColors.text.copy(alpha = 0.5f),
                fontSize = 16.sp,
                textAlign = TextAlign.Center,
                modifier = Modifier
                    .fillMaxWidth()
                    .noRippleClickable {
                        navController.navigate(
                            NavigationRoute.EmailSignUp.route,
                        )
                    }
            )
//            // 游客登录按钮
//            Spacer(modifier = Modifier.height(16.dp))
//            ActionButton(
//                modifier = Modifier.fillMaxWidth(),
//                text = "游客模式",
//                color = AppColors.text.copy(alpha = 0.7f),
//            ) {
//                guestLogin()
//            }
            Spacer(modifier = Modifier.height(70.dp))
        }
    }
}


@Composable
fun MovingImageWall(resources: Resources) {
    val AppColors = LocalAppTheme.current
    val imageList1 = remember {
        mutableStateListOf(
            R.drawable.wall_1_1,
            R.drawable.wall_1_2,
            R.drawable.wall_1_3,
            R.drawable.wall_1_1,
            R.drawable.wall_1_2,
            R.drawable.wall_1_3
        )
    }
    val imageList2 = remember {
        mutableStateListOf(
            R.drawable.wall_2_1,
            R.drawable.wall_2_2,
            R.drawable.wall_2_3,
            R.drawable.wall_2_1,
            R.drawable.wall_2_2,
            R.drawable.wall_2_3
        )
    }
    val imageList3 = remember {
        mutableStateListOf(
            R.drawable.wall_3_1,
            R.drawable.wall_3_2,
            R.drawable.wall_3_3,
            R.drawable.wall_3_1,
            R.drawable.wall_3_2,
            R.drawable.wall_3_3
        )
    }

    val density = resources.displayMetrics.density // 获取屏幕密度
    val imageHeight = 208.dp
    val imageHeightPx = imageHeight.value * density // 将 dp 转换为像素
    val resetThreshold = imageHeightPx
    // 使用 remember 保存动画状态，并在应用停止时重置
    // 每次 recomposition 时重置 offset
    var offset1 by remember { mutableFloatStateOf(-resetThreshold * 3) }
    var offset2 by remember { mutableFloatStateOf(0f) }
    var offset3 by remember { mutableFloatStateOf(-resetThreshold * 3) }

    val coroutineScope = rememberCoroutineScope()

    // 使用 LaunchedEffect 在每次 recomposition 时启动动画
    LaunchedEffect(Unit) {
        coroutineScope.launch {
            animateImageWall(imageList1, offset1, speed = 1f, resources = resources) {
                offset1 = it
            }
        }
        coroutineScope.launch {
            animateImageWall(
                imageList2,
                offset2,
                speed = 1.5f,
                reverse = true,
                resources = resources
            ) { offset2 = it }
        }
        coroutineScope.launch {
            animateImageWall(imageList3, offset3, speed = 2f, resources = resources) {
                offset3 = it
            }
        }
    }

    Box(
        modifier = Modifier
            .fillMaxWidth()
    ) {
        val scrollState1 = rememberScrollState()
        val scrollableState1 = rememberScrollableState { delta ->
            // 消耗所有滚动事件，阻止用户滚动
            delta
        }
        val scrollState2 = rememberScrollState()
        val scrollableState2 = rememberScrollableState { delta ->
            // 消耗所有滚动事件，阻止用户滚动
            delta
        }
        val scrollState3 = rememberScrollState()
        val scrollableState3 = rememberScrollableState { delta ->
            // 消耗所有滚动事件，阻止用户滚动
            delta
        }
        Row(
            modifier = Modifier
                .fillMaxWidth()
        ) {
            // 第1列
            ImageColumn(
                imageList1, offset1,
                Modifier
                    .verticalScroll(scrollState1)
                    .scrollable(
                        state = scrollableState1,
                        orientation = Orientation.Vertical
                    )
                    .weight(1f)
            )
            // 第2列
            ImageColumn(
                imageList2, offset2,
                Modifier
                    .verticalScroll(scrollState2)
                    .scrollable(
                        state = scrollableState2,
                        orientation = Orientation.Vertical
                    )
                    .weight(1f), reverse = true
            )
            // 第3列
            ImageColumn(
                imageList3, offset3,
                Modifier
                    .verticalScroll(scrollState3)
                    .scrollable(
                        state = scrollableState3,
                        orientation = Orientation.Vertical
                    )
                    .weight(1f)
            )
        }

        // 白色叠加层
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .fillMaxHeight()
                .background(AppColors.background.copy(alpha = 0.3f)),
            contentAlignment = Alignment.BottomCenter
        ) {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(500.dp)
                    .background(
                        Brush.verticalGradient(
                            colors = listOf(
                                Color.Transparent,
                                AppColors.background
                            ),
                            startY = 0f,
                            endY = 500f
                        )
                    )
            )
        }
    }
}

@Composable
fun ImageColumn(
    imageList: List<Int>,
    offset: Float,
    modifier: Modifier,
    reverse: Boolean = false
) {
    val imageCount = imageList.size
    val imageHeight = 208.dp
    var currentImage by remember { mutableStateOf(0) }
    val totalHeight = imageHeight.value * imageCount // 计算总高度
    Column(modifier = modifier) {
        for (i in 0 until imageCount) {
            Box(
                modifier = Modifier
                    .width(156.dp)
                    .height(208.dp)
                    .scale(1f)
                    .graphicsLayer {
                        val translation = if (reverse) {
                            offset
                        } else {
                            offset
                        }
                        translationY = translation
                    }
                    .clip(RoundedCornerShape(16.dp)),
                contentAlignment = Alignment.Center) {
                Image(
                    painter = painterResource(id = imageList[(currentImage + i) % imageCount]),
                    contentDescription = "背景图片",
                    modifier = Modifier
                        .width(156.dp)
                        .height(208.dp)
                        .scale(0.9f)
                        .clip(RoundedCornerShape(16.dp)),
                    contentScale = ContentScale.Crop
                )
            }

        }
    }
}

suspend fun animateImageWall(
    imageList: MutableList<Int>,
    initialOffset: Float,
    speed: Float, // speed 现在以像素为单位
    reverse: Boolean = false,
    resources: Resources, // 添加 resources 参数
    onUpdate: (Float) -> Unit,
) {
    val density = resources.displayMetrics.density // 获取屏幕密度
    var currentOffset = initialOffset
    val imageCount = imageList.size
    val imageHeight = 208.dp
    val imageHeightPx = imageHeight.value * density // 将 dp 转换为像素
    val resetThreshold = imageHeightPx
    Log.d(TAG, "speed: $speed")
    Log.d(TAG, "resetThreshold: $resetThreshold")
    while (true) {
        onUpdate(currentOffset)
        if (reverse) {
            currentOffset -= speed
//            Log.d(TAG, "currentOffset: $currentOffset")
            if (currentOffset <= -resetThreshold * 3) { // 检查是否向上超出阈值
                // 使用 imageHeightPx 进行计算
                // 复位
                currentOffset = initialOffset
            }
        } else {
            currentOffset += speed

            if (currentOffset >= 0) { // 检查是否向上超出阈值
                Log.d(TAG, "currentOffset: $currentOffset")
                // 使用 imageHeightPx 进行计算
                // 复位
                currentOffset = initialOffset
            }
            // 使用 imageHeightPx 进行计算
        }
        delay(16)
    }
}