package com.aiosman.riderpro.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.gestures.Orientation
import androidx.compose.foundation.gestures.rememberScrollableState
import androidx.compose.foundation.gestures.scrollable
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.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.unit.dp
import androidx.compose.ui.unit.sp
import com.aiosman.riderpro.AppState
import com.aiosman.riderpro.AppStore
import com.aiosman.riderpro.LocalNavController
import com.aiosman.riderpro.R
import com.aiosman.riderpro.data.AccountServiceImpl
import com.aiosman.riderpro.data.ServiceException
import com.aiosman.riderpro.ui.NavigationRoute
import com.aiosman.riderpro.ui.composables.ActionButton
import com.aiosman.riderpro.ui.modifiers.noRippleClickable
import com.aiosman.riderpro.utils.GoogleLogin
import com.google.accompanist.systemuicontroller.rememberSystemUiController
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

@Composable
fun LoginPage() {
    val navController = LocalNavController.current
    val context = LocalContext.current
    val coroutineScope = rememberCoroutineScope()
    val accountService = AccountServiceImpl()
    val statusBarController = rememberSystemUiController()
    LaunchedEffect(Unit) {
        statusBarController.setStatusBarColor(Color.Transparent, darkIcons = true)
    }

    fun googleLogin() {
        coroutineScope.launch {
            try {
                GoogleLogin(context) {
                    coroutineScope.launch {
                        try {
                            accountService.regiterUserWithGoogleAccount(it)
                        } 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
                            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()
            }

        }
    }
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.White)
    ) {
        Box(
            modifier = Modifier
                .fillMaxSize()
        ) {
            val localContext = LocalContext.current // 获取 Context
            MovingImageWall(localContext.resources) // 将 resources 传递给 MovingImageWall
        }
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(horizontal = 24.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Spacer(modifier = Modifier.weight(1f))
            Image(
                painter = painterResource(id = R.mipmap.rider_pro_color_logo),
                contentDescription = "Rider Pro",
                modifier = Modifier
                    .size(52.dp)
            )
            Spacer(modifier = Modifier.height(32.dp))
            Text(
                "Connecting Riders",
                fontSize = 28.sp,
                fontWeight = FontWeight.W900
            )
            Text("Worldwide", fontSize = 28.sp, fontWeight = FontWeight.W900)
            Spacer(modifier = Modifier.height(32.dp))
            ActionButton(
                modifier = Modifier.fillMaxWidth(),
                text = stringResource(R.string.sign_up_upper),
                color = Color.White,
                backgroundColor = Color(0xffda3832)
            ) {
                navController.navigate(
                    NavigationRoute.EmailSignUp.route,
                )
            }
            Spacer(modifier = Modifier.height(16.dp))
            ActionButton(
                modifier = Modifier.fillMaxWidth(),
                text = stringResource(R.string.sign_in_with_google),
                color = Color.Black,
                leading = {
                    Image(
                        painter = painterResource(id = R.drawable.rider_pro_google),
                        contentDescription = "Google",
                        modifier = Modifier.size(36.dp)
                    )
                },
                expandText = true,
                contentPadding = PaddingValues(vertical = 8.dp, horizontal = 8.dp)
            ) {
                googleLogin()
            }
            Spacer(modifier = Modifier.height(24.dp))
            Box(
                contentAlignment = Alignment.Center,
                modifier = Modifier.fillMaxWidth()
            ) {
                Text(
                    stringResource(R.string.login_upper),
                    fontSize = 17.sp,
                    fontWeight = FontWeight.W900,
                    color = Color(0xff333333),
                    modifier = Modifier.noRippleClickable {
                        navController.navigate(
                            NavigationRoute.UserAuth.route,
                        )
                    }
                )
            }
            Spacer(modifier = Modifier.height(70.dp))
        }
    }
}


@Composable
fun MovingImageWall(resources: Resources) {
    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(Color.White.copy(alpha = 0.3f)),
            contentAlignment = Alignment.BottomCenter
        ) {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(500.dp)
                    .background(
                        Brush.verticalGradient(
                            colors = listOf(
                                Color.Transparent,
                                Color.White
                            ),
                            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)
    }
}