package com.aiosman.riderpro.ui.index.tabs.profile

import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
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.WindowInsets
import androidx.compose.foundation.layout.asPaddingValues
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.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.staggeredgrid.LazyVerticalStaggeredGrid
import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.pullrefresh.PullRefreshIndicator
import androidx.compose.material.pullrefresh.pullRefresh
import androidx.compose.material.pullrefresh.rememberPullRefreshState
import androidx.compose.material3.Icon
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.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
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 androidx.paging.PagingData
import androidx.paging.compose.collectAsLazyPagingItems
import com.aiosman.riderpro.AppState
import com.aiosman.riderpro.ConstVars
import com.aiosman.riderpro.LocalNavController
import com.aiosman.riderpro.R
import com.aiosman.riderpro.entity.AccountProfileEntity
import com.aiosman.riderpro.entity.MomentEntity
import com.aiosman.riderpro.ui.NavigationRoute
import com.aiosman.riderpro.ui.composables.CustomAsyncImage
import com.aiosman.riderpro.ui.composables.DropdownMenu
import com.aiosman.riderpro.ui.composables.MenuItem
import com.aiosman.riderpro.ui.composables.StatusBarSpacer
import com.aiosman.riderpro.ui.composables.pickupAndCompressLauncher
import com.aiosman.riderpro.ui.composables.toolbar.CollapsingToolbarScaffold
import com.aiosman.riderpro.ui.composables.toolbar.ScrollStrategy
import com.aiosman.riderpro.ui.composables.toolbar.rememberCollapsingToolbarScaffoldState
import com.aiosman.riderpro.ui.index.tabs.profile.composable.EmptyMomentPostUnit
import com.aiosman.riderpro.ui.index.tabs.profile.composable.GalleryItem
import com.aiosman.riderpro.ui.index.tabs.profile.composable.MomentPostUnit
import com.aiosman.riderpro.ui.index.tabs.profile.composable.OtherProfileAction
import com.aiosman.riderpro.ui.index.tabs.profile.composable.SelfProfileAction
import com.aiosman.riderpro.ui.index.tabs.profile.composable.UserContentPageIndicator
import com.aiosman.riderpro.ui.index.tabs.profile.composable.UserItem
import com.aiosman.riderpro.ui.modifiers.noRippleClickable
import com.aiosman.riderpro.ui.post.NewPostViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import java.io.File

@OptIn(ExperimentalFoundationApi::class, ExperimentalMaterialApi::class)
@Composable
fun ProfileV3(
    onUpdateBanner: ((Uri, File, Context) -> Unit)? = null,
    profile: AccountProfileEntity? = null,
    onLogout: () -> Unit = {},
    onFollowClick: () -> Unit = {},
    onChatClick: () -> Unit = {},
    sharedFlow: SharedFlow<PagingData<MomentEntity>> = MutableStateFlow<PagingData<MomentEntity>>(
        PagingData.empty()
    ).asStateFlow(),
    isSelf: Boolean = true
) {
    val model = MyProfileViewModel
    val state = rememberCollapsingToolbarScaffoldState()
    val pagerState = rememberPagerState(pageCount = { 2 })
    var enabled by remember { mutableStateOf(true) }
    val statusBarPaddingValues = WindowInsets.systemBars.asPaddingValues()
    var expanded by remember { mutableStateOf(false) }
    var minibarExpanded by remember { mutableStateOf(false) }
    val context = LocalContext.current
    val scope = rememberCoroutineScope()
    val navController = LocalNavController.current
    var bannerHeight = 400
    val pickBannerImageLauncher = pickupAndCompressLauncher(
        context,
        scope,
        maxSize = ConstVars.BANNER_IMAGE_MAX_SIZE,
        quality = 100
    ) { uri, file ->
        onUpdateBanner?.invoke(uri, file, context)
    }
    val moments = sharedFlow.collectAsLazyPagingItems()
    val refreshState = rememberPullRefreshState(model.refreshing, onRefresh = {
        model.loadProfile(pullRefresh = true)
    })
    var miniToolbarHeight by remember { mutableStateOf(0) }
    val density = LocalDensity.current
    Box(
        modifier = Modifier.pullRefresh(refreshState)
    ) {
        CollapsingToolbarScaffold(
            modifier = Modifier
                .fillMaxSize()
                .background(Color(0xfff8f8f8)),
            state = state,
            scrollStrategy = ScrollStrategy.ExitUntilCollapsed,
            toolbarScrollable = true,
            enabled = enabled,
            toolbar = { toolbarScrollState ->
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(miniToolbarHeight.dp)
                        // 保持在最低高度和当前高度之间
                        .background(Color(0xfff8f8f8))

                ) {
                }
                // header
                Box(
                    modifier = Modifier
                        .parallax(0.5f)
                        .fillMaxWidth()
                        .height(600.dp)
                        .verticalScroll(toolbarScrollState)
                ) {
                    Box(
                        modifier = Modifier.fillMaxSize()
                    ) {
                        Column(
                            modifier = Modifier
                                .fillMaxWidth()
                                .graphicsLayer {
                                    alpha = state.toolbarState.progress
                                }
                        ) {
                            // banner
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .height(bannerHeight.dp)
                            ) {
                                Box(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .let {
                                            if (isSelf) {
                                                it.noRippleClickable {
                                                    Intent(Intent.ACTION_PICK).apply {
                                                        type = "image/*"
                                                        pickBannerImageLauncher.launch(this)
                                                    }
                                                }
                                            } else {
                                                it
                                            }
                                        }
                                        .shadow(
                                            elevation = 6.dp,
                                            shape = RoundedCornerShape(
                                                bottomStart = 32.dp,
                                                bottomEnd = 32.dp
                                            )
                                        )
                                ) {
                                    val banner = profile?.banner

                                    if (banner != null) {
                                        CustomAsyncImage(
                                            LocalContext.current,
                                            banner,
                                            modifier = Modifier
                                                .fillMaxSize(),
                                            contentDescription = "",
                                            contentScale = ContentScale.Crop
                                        )
                                    } else {
                                        Image(
                                            painter = painterResource(id = R.drawable.rider_pro_moment_demo_2),
                                            modifier = Modifier
                                                .fillMaxSize(),
                                            contentDescription = "",
                                            contentScale = ContentScale.Crop
                                        )
                                    }
                                }
                                if (isSelf) {
                                    Box(
                                        modifier = Modifier
                                            .align(Alignment.TopEnd)
                                            .padding(
                                                top = statusBarPaddingValues.calculateTopPadding(),
                                                start = 8.dp,
                                                end = 8.dp
                                            )
                                    ) {
                                        Box(
                                            modifier = Modifier
                                                .padding(16.dp)
                                                .clip(RoundedCornerShape(8.dp))
                                                .shadow(
                                                    elevation = 20.dp
                                                )
                                                .background(Color.White.copy(alpha = 0.7f))
                                        ) {
                                            Icon(
                                                painter = painterResource(id = R.drawable.rider_pro_more_horizon),
                                                contentDescription = "",
                                                modifier = Modifier.noRippleClickable {
                                                    expanded = true
                                                },
                                                tint = Color.Black
                                            )
                                        }
                                        DropdownMenu(
                                            expanded = expanded,
                                            onDismissRequest = { expanded = false },
                                            width = 250,
                                            menuItems = listOf(
                                                MenuItem(
                                                    stringResource(R.string.logout),
                                                    R.mipmap.rider_pro_logout
                                                ) {
                                                    expanded = false
                                                    scope.launch {
                                                        onLogout()
                                                        navController.navigate(NavigationRoute.Login.route) {
                                                            popUpTo(NavigationRoute.Index.route) {
                                                                inclusive = true
                                                            }
                                                        }
                                                    }
                                                },
                                                MenuItem(
                                                    stringResource(R.string.change_password),
                                                    R.mipmap.rider_pro_change_password
                                                ) {
                                                    expanded = false
                                                    scope.launch {
                                                        navController.navigate(NavigationRoute.ChangePasswordScreen.route)
                                                    }
                                                },
                                                MenuItem(
                                                    stringResource(R.string.favourites),
                                                    R.drawable.rider_pro_favourite
                                                ) {
                                                    expanded = false
                                                    scope.launch {
                                                        navController.navigate(NavigationRoute.FavouriteList.route)
                                                    }
                                                }
                                            )
                                        )
                                    }
                                }

                            }
                            Box(
                                modifier = Modifier.fillMaxWidth()
                            ) {
                                // user info
                                Column(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                ) {
                                    Spacer(modifier = Modifier.height(16.dp))
                                    // 个人信息
                                    Box(
                                        modifier = Modifier.padding(horizontal = 16.dp)
                                    ) {
                                        profile?.let {
                                            UserItem(it)
                                        }
                                    }
                                    Spacer(modifier = Modifier.height(20.dp))
                                    profile?.let {
                                        Box(
                                            modifier = Modifier.padding(horizontal = 16.dp)
                                        ) {
                                            if (isSelf) {
                                                SelfProfileAction {
                                                    navController.navigate(NavigationRoute.AccountEdit.route)
                                                }
                                            } else {
                                                if (it.id != AppState.UserId) {
                                                    OtherProfileAction(
                                                        it,
                                                        onFollow = {
                                                            onFollowClick()
                                                        },
                                                        onChat = {
                                                            onChatClick()
                                                        }
                                                    )
                                                }

                                            }

                                        }
                                    }

                                    // collapsed bar


                                }

                            }

                        }
                    }


                }
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .graphicsLayer {
                            alpha = 1 - state.toolbarState.progress
                        }
                        .onGloballyPositioned {
                            miniToolbarHeight = with(density) {
                                it.size.height.toDp().value.toInt()
                            }
                        }
                ) {
                    StatusBarSpacer()
                    Row(
                        modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        CustomAsyncImage(
                            LocalContext.current,
                            profile?.avatar,
                            modifier = Modifier
                                .size(48.dp)
                                .clip(CircleShape),
                            contentDescription = "",
                            contentScale = ContentScale.Crop
                        )
                        Spacer(modifier = Modifier.width(16.dp))
                        androidx.compose.material3.Text(
                            text = profile?.nickName ?: "",
                            fontSize = 16.sp,
                            fontWeight = FontWeight.W600,
                            color = Color.Black
                        )
                        Spacer(modifier = Modifier.weight(1f))
                        if (isSelf) {
                            Box(
                                modifier = Modifier
                            ) {
                                Box(
                                    modifier = Modifier
                                        .padding(16.dp)
                                ) {
                                    Icon(
                                        painter = painterResource(id = R.drawable.rider_pro_more_horizon),
                                        contentDescription = "",
                                        modifier = Modifier.noRippleClickable {
                                            minibarExpanded = true
                                        },
                                        tint = Color.Black
                                    )
                                }
                                DropdownMenu(
                                    expanded = minibarExpanded,
                                    onDismissRequest = { minibarExpanded = false },
                                    width = 250,
                                    menuItems = listOf(
                                        MenuItem(
                                            stringResource(R.string.logout),
                                            R.mipmap.rider_pro_logout
                                        ) {
                                            minibarExpanded = false
                                            scope.launch {
                                                onLogout()
                                                navController.navigate(NavigationRoute.Login.route) {
                                                    popUpTo(NavigationRoute.Index.route) {
                                                        inclusive = true
                                                    }
                                                }
                                            }
                                        },
                                        MenuItem(
                                            stringResource(R.string.change_password),
                                            R.mipmap.rider_pro_change_password
                                        ) {
                                            minibarExpanded = false
                                            scope.launch {
                                                navController.navigate(NavigationRoute.ChangePasswordScreen.route)
                                            }
                                        },
                                        MenuItem(
                                            stringResource(R.string.favourites),
                                            R.drawable.rider_pro_favourite
                                        ) {
                                            minibarExpanded = false
                                            scope.launch {
                                                navController.navigate(NavigationRoute.FavouriteList.route)
                                            }
                                        }
                                    )
                                )
                            }
                        }

                    }
                    Spacer(modifier = Modifier.height(8.dp))
                }
            }
        ) {
            Column {
                UserContentPageIndicator(
                    pagerState = pagerState,
                )
                Spacer(modifier = Modifier.height(8.dp))
                HorizontalPager(
                    state = pagerState,
                ) { idx ->
                    when (idx) {
                        0 ->
                            LazyVerticalStaggeredGrid(
                                columns = StaggeredGridCells.Fixed(2),
                                modifier = Modifier.fillMaxSize(),
                                horizontalArrangement = Arrangement.spacedBy(
                                    8.dp
                                ),
                                verticalItemSpacing = 8.dp,
                                contentPadding = PaddingValues(8.dp)
                            ) {
                                if (isSelf) {
                                    items(1) {
                                        Box(
                                            modifier = Modifier
                                                .fillMaxWidth()
                                                .aspectRatio(0.75f)
                                                .clip(
                                                    RoundedCornerShape(8.dp)
                                                )
                                                .background(Color.White)
                                                .padding(8.dp)
                                                .noRippleClickable {
                                                    NewPostViewModel.asNewPost()
                                                    navController.navigate(NavigationRoute.NewPost.route)
                                                }
                                        ) {
                                            Box(
                                                modifier = Modifier
                                                    .fillMaxSize()
                                                    .clip(
                                                        RoundedCornerShape(8.dp)
                                                    )
                                                    .background(Color(0xfff5f5f5))
                                            ) {
                                                Icon(
                                                    Icons.Default.Add,
                                                    contentDescription = "",
                                                    modifier = Modifier
                                                        .size(32.dp)
                                                        .align(Alignment.Center)
                                                )
                                            }
                                        }
                                    }
                                }
                                items(moments.itemCount) { idx ->
                                    val moment = moments[idx] ?: return@items
                                    GalleryItem(moment, idx)
                                }
                                items(2) {
                                    Spacer(modifier = Modifier.height(120.dp))
                                }
                            }
                        1 ->
                            LazyColumn(
                                modifier = Modifier
                                    .fillMaxSize()
                            ) {
                                if (moments.itemCount == 0 && isSelf) {
                                    item {
                                        EmptyMomentPostUnit()
                                    }
                                }
                                item {
                                    for (idx in 0 until moments.itemCount) {
                                        val moment = moments[idx]
                                        moment?.let {
                                            MomentPostUnit(it)
                                        }
                                    }
                                }
                                item {
                                    Spacer(modifier = Modifier.height(120.dp))
                                }
                            }
                    }
                }
            }

        }
        PullRefreshIndicator(model.refreshing, refreshState, Modifier.align(Alignment.TopCenter))
    }
}
