package com.za.ui.order_report

import android.content.Intent
import android.os.Build
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
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.wrapContentWidth
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.LocationOn
import androidx.compose.material3.BottomSheetScaffold
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.rememberBottomSheetScaffoldState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import com.za.base.BaseActivity
import com.za.base.theme.bgColor
import com.za.base.theme.white95
import com.za.base.view.CommonButton
import com.za.base.view.HeadView
import com.za.ext.finish
import com.za.ext.navigationActivity
import com.za.servicing.R
import com.za.ui.map_search.MapSearchActivity
import com.za.ui.map_search.PoiData
import kotlinx.coroutines.launch

class OrderReportActivity : BaseActivity() {
    @Composable
    override fun ContentView() {
        OrderReportScreen()
    }
}

private val PrimaryBlue = Color(0xFF1A73E8)  // 更新为 Google Blue
private val TextGrey = Color(0xFF5F6368)

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun OrderReportScreen(vm: OrderReportVm = viewModel()) {
    val uiState by vm.uiState.collectAsStateWithLifecycle()
    val scaffoldState = rememberBottomSheetScaffoldState()
    val scope = rememberCoroutineScope()
    val context = LocalContext.current
    val localSoftwareKeyboardController = LocalSoftwareKeyboardController.current
    LaunchedEffect(Unit) {
        vm.dispatch(OrderReportVm.Action.Init)
        scaffoldState.bottomSheetState.expand()
    }

    if (uiState.success == true) {
        context.finish()
    }

    val result = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {
        val poiData = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            it.data?.getSerializableExtra("poiData", PoiData::class.java)
        } else {
            it.data?.getSerializableExtra("poiData") as PoiData?
        }
        if (poiData != null) {
            vm.updateState(uiState.copy(reportContent = poiData.name))
        }
    }

    BottomSheetScaffold(topBar = {
        HeadView(title = "添加报备", onBack = { context.finish() }, action = {
            Icon(imageVector = ImageVector.vectorResource(R.drawable.sv_history),
                contentDescription = "",tint = Color.White,
                modifier = Modifier.clickable {
                    context.navigationActivity(HistoryReportActivity::class.java)
                }.height(40.dp).padding(10.dp))
        })
    }, sheetPeekHeight = 100.dp, scaffoldState = scaffoldState, sheetContainerColor = bgColor, sheetContent = {
        LazyVerticalGrid(columns = GridCells.Fixed(3), horizontalArrangement = Arrangement.Center, verticalArrangement = Arrangement.Center, modifier = Modifier.padding(bottom = 20.dp)) {
            itemsIndexed(uiState.reportList ?: arrayListOf()) { index, item ->
                Box(modifier = Modifier
                    .size(120.dp, 70.dp)
                    .padding(2.dp)
                    .background(color = white95, shape = RoundedCornerShape(8.dp))
                    .border(width = 1.dp, color = if (uiState.selectReportItem?.reportType == item.reportType) {
                        Color.White
                    } else {
                        Color.Transparent
                    }, shape = RoundedCornerShape(8.dp))
                    .padding(10.dp)
                    .clickable {
                        scope.launch {
                            if (scaffoldState.bottomSheetState.hasExpandedState) {
                                scaffoldState.bottomSheetState.partialExpand()
                                vm.dispatch(OrderReportVm.Action.SelectReportItem(item))
                            }
                        }
                    }, contentAlignment = Alignment.Center) {
                    Text(text = item.reportType ?: "", color = Color.Black, fontSize = 13.sp)
                }
            }
        }
    }) {
        Column(modifier = Modifier
            .fillMaxSize()
            .padding(horizontal = 20.dp), horizontalAlignment = Alignment.CenterHorizontally) {
            Spacer(modifier = Modifier.height(30.dp))

            AnimatedVisibility(uiState.selectReportItem == null) {
                CommonButton(text = "请选择报备类型") {
                    scope.launch {
                        scaffoldState.bottomSheetState.expand()
                    }
                }
            }

            AnimatedVisibility(uiState.selectReportItem != null) {
                Column(modifier = Modifier
                    .wrapContentWidth()
                    .clickable {
                        scope.launch {
                            localSoftwareKeyboardController?.hide()
                            scaffoldState.bottomSheetState.expand()
                        }
                    }
                    .background(color = Color.White, shape = RoundedCornerShape(8.dp))
                    .padding(10.dp), horizontalAlignment = Alignment.Start, verticalArrangement = Arrangement.Center) {
                    Text("当前报备类型:", fontSize = 13.sp, color = Color.Gray)
                    Spacer(Modifier.height(10.dp))
                    Box(modifier = Modifier.fillMaxWidth()) {
                        Text(text = uiState.selectReportItem?.reportType
                            ?: "", fontSize = 18.sp, color = Color.Black, fontWeight = FontWeight.Bold)
                    }
                }
            }

            Spacer(modifier = Modifier.height(20.dp))
            AnimatedVisibility(uiState.selectReportItem != null) {
                OutlinedTextField(
                    value = uiState.reportContent ?: "",
                    onValueChange = { vm.updateState(uiState.copy(reportContent = it)) },
                    label = { Text("备注内容") },
                    modifier = Modifier.fillMaxWidth(),
                    minLines = 3,
                    textStyle = TextStyle.Default.copy(fontSize = 16.sp, color = Color.Black),
                    shape = RoundedCornerShape(12.dp),
                    trailingIcon = {
                        if (uiState.selectReportItem?.reportType?.contains("事发地") == true
                            || uiState.selectReportItem?.reportType?.contains("目的地") == true
                        )
                            Icon(imageVector = Icons.Default.LocationOn, contentDescription = null,
                                tint = PrimaryBlue,
                                modifier = Modifier
                                    .size(24.dp)
                                    .clickable {
                                        result.launch(Intent(context, MapSearchActivity::class.java))
                                    })
                    },
                    prefix = { Text("${uiState.selectReportItem?.reportTemplate?.replace("_", "")}", fontSize = 13.sp) },
                    colors = OutlinedTextFieldDefaults.colors(focusedBorderColor = PrimaryBlue, unfocusedBorderColor = PrimaryBlue.copy(alpha = 0.5f), focusedLabelColor = PrimaryBlue, unfocusedLabelColor = TextGrey),
                )
            }

            Spacer(modifier = Modifier.height(20.dp))
            AnimatedVisibility(uiState.selectReportItem != null) {
                CommonButton("提交报备") {
                    vm.dispatch(OrderReportVm.Action.Submit)
                }
            }
        }
    }
}

@Preview
@Composable
fun OrderReportPreview(modifier: Modifier = Modifier) {
    OrderReportScreen()
}