package com.aiosman.riderpro.ui.post

import android.net.Uri
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
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.heightIn
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.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material.LinearProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
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.drawBehind
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.PathEffect
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.core.content.FileProvider
import androidx.lifecycle.viewModelScope
import com.aiosman.riderpro.LocalNavController
import com.aiosman.riderpro.R
import com.aiosman.riderpro.ui.NavigationRoute
import com.aiosman.riderpro.ui.composables.CustomAsyncImage
import com.aiosman.riderpro.ui.composables.DraggableGrid
import com.aiosman.riderpro.ui.composables.RelPostCard
import com.aiosman.riderpro.ui.composables.StatusBarMaskLayout
import com.aiosman.riderpro.ui.modifiers.noRippleClickable
import com.google.accompanist.systemuicontroller.rememberSystemUiController
import kotlinx.coroutines.launch
import java.io.File


@Preview
@Composable
fun NewPostScreen() {
    val model = NewPostViewModel
    val systemUiController = rememberSystemUiController()
    val navController = LocalNavController.current
    val context = LocalContext.current
    LaunchedEffect(Unit) {
        systemUiController.setNavigationBarColor(color = Color.Transparent)
        model.init()
    }
    StatusBarMaskLayout(
        darkIcons = true,
        modifier = Modifier
            .fillMaxSize()
            .background(Color.White)
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
        ) {
            NewPostTopBar {
//                model.viewModelScope.launch {
//                    model.createMoment(context = context){ progress ->
//                        // 更新进度条
//                        uploadProgress = progress
//                    }
//                    navController.popBackStack()
//                }
            }
            NewPostTextField("Share your adventure…", NewPostViewModel.textContent) {
                NewPostViewModel.textContent = it
            }
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp)
            ) {
                model.relMoment?.let {
                    Text("Share with")
                    Spacer(modifier = Modifier.height(8.dp))
                    Box(
                        modifier = Modifier
                            .clip(RoundedCornerShape(8.dp))
                            .background(color = Color(0xFFEEEEEE))
                            .padding(24.dp)
                    ) {
                        RelPostCard(
                            momentEntity = it,
                            modifier = Modifier.fillMaxWidth()
                        )
                    }
                }
            }

            AddImageGrid()
//            AdditionalPostItem()
        }
    }
}

@Composable
fun NewPostTopBar(onSendClick: () -> Unit = {}) {
    val navController = LocalNavController.current
    val context = LocalContext.current
    val model = NewPostViewModel
    var showProgressBar by remember { mutableStateOf(false) }
    var uploadProgress by remember { mutableStateOf(0f) }
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 18.dp, vertical = 10.dp)
    ) {
        Row(
            modifier = Modifier.align(Alignment.CenterStart),
        ) {
            Image(
                painter = painterResource(id = R.drawable.rider_pro_back_icon),
                contentDescription = "Back",
                modifier = Modifier
                    .size(24.dp)
                    .noRippleClickable {
                        navController.popBackStack()
                    }
            )
            Spacer(modifier = Modifier.weight(1f))
            Icon(
                painter = painterResource(id = R.drawable.rider_pro_video_share),
                tint = Color.Black,
                contentDescription = "Send",
                modifier = Modifier
                    .size(32.dp)
                    .noRippleClickable {
                        // 检查输入
                        val errorMessage = model.validateMoment()
                        if (errorMessage != null) {
                            Toast.makeText(context, errorMessage, Toast.LENGTH_SHORT).show()
                            return@noRippleClickable
                        }
                        // 点击发送按钮后立即导航回主页
                        navController.popBackStack()
                        // 显示进度条
                        showProgressBar = true

                        // 在后台启动协程处理上传逻辑
                        model.viewModelScope.launch {
                            model.createMoment(context = context) { progress ->
                                // 更新进度条
                                uploadProgress = progress
                            }
                            // 上传完成后隐藏进度条
                            showProgressBar = false
                        }
                    }
            )
        }

        // 在底部添加一个进度条
        AnimatedVisibility(
            visible = showProgressBar,
            modifier = Modifier
                .align(Alignment.BottomCenter)
                .fillMaxWidth()
        ) {
            LinearProgressIndicator(
                progress = uploadProgress,
                modifier = Modifier
                    .fillMaxWidth()
                    .height(4.dp)
            )
        }
    }
}

@Composable
fun NewPostTextField(hint: String, value: String, onValueChange: (String) -> Unit) {

    Box(modifier = Modifier.fillMaxWidth()) {
        BasicTextField(
            value = value,
            onValueChange = onValueChange,
            modifier = Modifier
                .fillMaxWidth()
                .heightIn(200.dp)
                .padding(horizontal = 18.dp, vertical = 10.dp)

        )
        if (value.isEmpty()) {
            Text(
                text = hint,
                color = Color.Gray,
                modifier = Modifier.padding(horizontal = 18.dp, vertical = 10.dp)
            )
        }
    }
}


@Composable
fun AddImageGrid() {
    val navController = LocalNavController.current
    val context = LocalContext.current
    val model = NewPostViewModel

    val pickImagesLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.GetMultipleContents()
    ) { uris ->
        if (uris.isNotEmpty()) {
            model.imageList += uris.map {
                ImageItem(
                    uri = it.toString(),
                    id = java.util.UUID.randomUUID().toString()
                )
            }
        }
    }

    val takePictureLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.TakePicture()
    ) { success ->
        if (success) {
            model.imageList += ImageItem(
                uri = model.currentPhotoUri.toString(),
                id = java.util.UUID.randomUUID().toString()
            )
        }
    }

    val stroke = Stroke(
        width = 2f,
        pathEffect = PathEffect.dashPathEffect(floatArrayOf(10f, 10f), 0f)
    )
    DraggableGrid(
        items = NewPostViewModel.imageList,
        onMove = { from, to ->
            NewPostViewModel.imageList = NewPostViewModel.imageList.toMutableList().apply {
                add(to, removeAt(from))
            }
        },
        lockedIndices = listOf(

        ),
        onDragModeEnd = {},
        onDragModeStart = {},
        additionalItems = listOf(

        ),
        getItemId = { it.id }
    ) { item, isDrag ->
        Box(
            modifier = Modifier
        ) {
            CustomAsyncImage(
                LocalContext.current,
                item.uri,
                contentDescription = "Image",
                modifier = Modifier
                    .fillMaxWidth()
                    .aspectRatio(1f)
                    .noRippleClickable {
                        navController.navigate(NavigationRoute.NewPostImageGrid.route)
                    },
                contentScale = ContentScale.Crop
            )
            if (isDrag) {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(Color(0x66000000))
                )
            }
        }
    }
    LazyVerticalGrid(
        columns = GridCells.Fixed(3),
        contentPadding = PaddingValues(16.dp),
        modifier = Modifier
            .fillMaxWidth()
            .padding(18.dp),
        horizontalArrangement = Arrangement.spacedBy(8.dp),
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        item {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .aspectRatio(1f)
                    .drawBehind {
                        val strokeWidth = 1.dp.toPx()
                        val dashLength = 10f
                        val dashGap = 10f
                        val pathEffect = PathEffect.dashPathEffect(floatArrayOf(dashLength, dashGap))
                        drawRoundRect(
                            color = Color(0xFFD6D6D6),
                            style = Stroke(strokeWidth, pathEffect = pathEffect),
                            cornerRadius = CornerRadius(8.dp.toPx())
                        )
                    }
                    .noRippleClickable {
                        pickImagesLauncher.launch("image/*")
                    },
            ) {
                Icon(
                    painter = painterResource(id = R.drawable.rider_pro_new_post_add_pic),
                    contentDescription = "Add Image",
                    modifier = Modifier
                        .size(48.dp)
                        .align(Alignment.Center),
                    tint = Color(0xFFD6D6D6)

                )
            }
        }
        item {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .aspectRatio(1f)
                    .drawBehind {
                        val strokeWidth = 1.dp.toPx()
                        val dashLength = 10f
                        val dashGap = 10f
                        val pathEffect = PathEffect.dashPathEffect(floatArrayOf(dashLength, dashGap))
                        drawRoundRect(
                            color = Color(0xFFD6D6D6),
                            style = Stroke(strokeWidth, pathEffect = pathEffect),
                            cornerRadius = CornerRadius(8.dp.toPx())
                        )
                    }
                    .noRippleClickable {
                        val photoFile = File(context.cacheDir, "photo.jpg")
                        val photoUri: Uri = FileProvider.getUriForFile(
                            context,
                            "${context.packageName}.fileprovider",
                            photoFile
                        )
                        model.currentPhotoUri = photoUri
                        takePictureLauncher.launch(photoUri)
                    },
            ) {
                Icon(
                    painter = painterResource(id = R.drawable.rider_pro_camera),
                    contentDescription = "Take Photo",
                    modifier = Modifier
                        .size(48.dp)
                        .align(Alignment.Center),
                    tint = Color(0xFFD6D6D6)
                )
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AdditionalPostItem() {
    val model = NewPostViewModel
    val navController = LocalNavController.current
    var isShowLocationModal by remember { mutableStateOf(false) }
    fun onSelectLocationClick() {
        isShowLocationModal = true
    }
    if (isShowLocationModal) {
        ModalBottomSheet(
            onDismissRequest = {
                isShowLocationModal = false
            },
            containerColor = Color.White

        ) {
            // Sheet content
            SelectLocationModal(
                onClose = {
                    isShowLocationModal = false
                }
            ) {
                isShowLocationModal = false
                NewPostViewModel.searchPlaceAddressResult = it
            }
        }
    }
    Column(
        modifier = Modifier.fillMaxWidth()
    ) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 16.dp, horizontal = 24.dp)
                .clickable(
                    indication = null,
                    interactionSource = remember { MutableInteractionSource() }
                ) {
                    onSelectLocationClick()
                }
        ) {
            NewPostViewModel.searchPlaceAddressResult?.let {
                SelectedLocation(it) {
                    NewPostViewModel.searchPlaceAddressResult = null
                }
            } ?: Row(
                verticalAlignment = Alignment.CenterVertically
            ) {
                Image(
                    painter = painterResource(id = R.drawable.rider_pro_add_location),
                    contentDescription = "Location",
                    modifier = Modifier.size(24.dp)
                )
                Spacer(modifier = Modifier.width(12.dp))
                Text("Add Location", color = Color(0xFF333333))
                Spacer(modifier = Modifier.weight(1f))
                Image(
                    painter = painterResource(id = R.drawable.rider_pro_nav_next),
                    contentDescription = "Add Location",
                    modifier = Modifier.size(24.dp)
                )
            }
        }
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 16.dp, horizontal = 24.dp)
                .clickable(
                    indication = null,
                    interactionSource = remember { MutableInteractionSource() }
                ) {
                    navController.navigate("EditModification")
                }
        ) {
            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {
                Image(
                    painter = painterResource(id = R.drawable.rider_pro_modification),
                    contentDescription = "Modification List",
                    modifier = Modifier.size(24.dp)
                )
                Spacer(modifier = Modifier.width(12.dp))
                Text("Modification List", color = Color(0xFF333333))
                Spacer(modifier = Modifier.weight(1f))
                Image(
                    painter = painterResource(id = R.drawable.rider_pro_nav_next),
                    contentDescription = "Modification List",
                    modifier = Modifier.size(24.dp)
                )
            }

        }
    }
}

@Composable
fun SelectedLocation(
    searchPlaceAddressResult: SearchPlaceAddressResult,
    onRemoveLocation: () -> Unit
) {
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 16.dp)
    ) {
        Row(
            verticalAlignment = Alignment.CenterVertically,
        ) {
            Column(
                modifier = Modifier
                    .weight(1f)
                    .padding(end = 16.dp)
            ) {
                Text(searchPlaceAddressResult.name, fontWeight = FontWeight.Bold)
                Spacer(modifier = Modifier.height(4.dp))
                Text(searchPlaceAddressResult.address, color = Color(0xFF9a9a9a))
            }
            Image(
                painter = painterResource(id = R.drawable.rider_pro_close),
                contentDescription = "Next",
                modifier = Modifier
                    .size(24.dp)
                    .clickable(
                        indication = null,
                        interactionSource = remember { MutableInteractionSource() }
                    ) {
                        onRemoveLocation()
                    }
            )

        }
    }
}