package io.nexilis.alpha.ui.main

import Attachments
import android.text.format.DateUtils
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.Send
import androidx.compose.material.icons.filled.AccessTime
import androidx.compose.material.icons.filled.Done
import androidx.compose.material.icons.filled.DoneAll
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import io.nexilis.alpha.ui.viewmodel.MainViewModel
import io.nexilis.service.core.BlueSky
import io.nexilis.service.core.WhiteTransparent
import io.nexilis.service.data.entities.Message
import io.nexilis.service.data.viewmodels.BuddyViewModel
import io.nexilis.service.data.viewmodels.MessageStatusViewModel
import io.nexilis.service.data.viewmodels.MessageViewModel

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun Chat(navController: NavHostController, pin: String, mainViewModel: MainViewModel) {
    var textInput by rememberSaveable(stateSaver = TextFieldValue.Saver) {
        mutableStateOf(TextFieldValue("", TextRange(0, 7)))
    }
    val buddyViewModel: BuddyViewModel = hiltViewModel()
    val me by buddyViewModel.me.observeAsState()
    val buddy by buddyViewModel.getBuddy(pin).observeAsState()
    val messageModel: MessageViewModel = hiltViewModel()
    val list by messageModel.getOpposite(pin).observeAsState()
    val messageStatusModel: MessageStatusViewModel = hiltViewModel()
    LaunchedEffect(buddy) {
        buddy?.first_name?.let {
            mainViewModel.setTitle("$it ${buddy?.last_name ?: ""}".trim())
        }
    }
    val state = rememberLazyListState()
    Column(
        modifier = Modifier
            .fillMaxSize()
            .onSizeChanged {

            }
            .background(color = MaterialTheme.colorScheme.surfaceContainer)
            .padding(start = 8.dp, end = 8.dp, bottom = 8.dp)
    ) {
        LazyColumn(
            modifier = Modifier.weight(1.0f),
            state = state,
            reverseLayout = true
        ) {
            items(count = list?.size ?: 0) {
                val message = list?.let { l ->
                    val m = l[it]
                    m
                }
                ListItem(modifier = Modifier.fillMaxWidth(), headlineContent = {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = if (message?.f_pin == me?.f_pin) Arrangement.End else Arrangement.Start
                    ) {
                        if (message?.f_pin == me?.f_pin) {
                            Spacer(modifier = Modifier.weight(0.2f))
                            Column(
                                modifier = Modifier
                                    .weight(weight = 0.8f, fill = false)
                            ) {
                                Text(
                                    modifier = Modifier
                                        .align(Alignment.End)
                                        .graphicsLayer {
//                                            shadowElevation = 2.dp.toPx()
                                            shape = RoundedCornerShape(16.dp)
                                            clip = true
                                        }
                                        .combinedClickable(onLongClick = {}, onClick = {})
                                        .background(color = MaterialTheme.colorScheme.primaryContainer)
                                        .padding(8.dp),
                                    text = list?.get(it)?.message_text ?: "",
                                    style = MaterialTheme.typography.bodyMedium,
                                )
                                Row(
                                    modifier = Modifier
                                        .padding(3.dp)
                                        .align(Alignment.End)
                                ) {
                                    Text(
                                        text = DateUtils.formatDateTime(
                                            LocalContext.current,
                                            list?.get(it)?.server_date ?: 0,
                                            DateUtils.FORMAT_SHOW_TIME
                                        ),
                                        color = MaterialTheme.colorScheme.onPrimaryContainer,
                                        style = MaterialTheme.typography.bodySmall,
                                    )
                                    Spacer(modifier = Modifier.width(6.dp))
                                    message?.message_id?.let {
                                        val messageStatus by messageStatusModel.get(it, pin)
                                            .observeAsState()
                                        Icon(
                                            imageVector = when (messageStatus?.status) {
                                                1, 2 -> Icons.Default.Done
                                                3 -> Icons.Default.DoneAll
                                                4 -> Icons.Default.DoneAll
                                                else -> Icons.Default.AccessTime
                                            },
                                            contentDescription = "",
                                            modifier = Modifier
                                                .align(Alignment.Bottom)
                                                .size(16.dp),
                                            tint = if (messageStatus?.status == 4) Color.BlueSky else Color.Gray
                                        )
                                    }

                                }
                            }
                        } else {
                            Column(
                                modifier = Modifier
                                    .weight(weight = 0.8f, fill = false)
                            ) {
                                Text(
                                    modifier = Modifier
                                        .align(Alignment.Start)
                                        .graphicsLayer {
//                                            shadowElevation = 2.dp.toPx()
                                            shape = RoundedCornerShape(16.dp)
                                            clip = true
                                        }
                                        .combinedClickable(onLongClick = {}, onClick = {})
                                        .background(color = MaterialTheme.colorScheme.surface)
                                        .padding(8.dp),
                                    text = list?.get(it)?.message_text ?: "",
                                    style = MaterialTheme.typography.bodyMedium,
                                )
                                Row(
                                    modifier = Modifier
                                        .padding(3.dp)
                                        .align(Alignment.End)
                                ) {
                                    Text(
                                        text = DateUtils.formatDateTime(
                                            LocalContext.current,
                                            list?.get(it)?.server_date ?: 0,
                                            DateUtils.FORMAT_SHOW_TIME
                                        ),
                                        color = MaterialTheme.colorScheme.onSurface,
                                        style = MaterialTheme.typography.bodySmall,
                                    )
                                }
                            }
                            Spacer(modifier = Modifier.weight(0.2f))
                        }
                    }
                }, colors = ListItemDefaults.colors(containerColor = Color.Transparent))
            }
        }
        TextField(
            modifier = Modifier
                .fillMaxWidth()
                .graphicsLayer {
//                    shadowElevation = 2.dp.toPx()
                    shape = CircleShape
                    clip = true
                }
                .imePadding(),
            value = textInput,
            onValueChange = { textInput = it },
            label = null,
            placeholder = {
                Text(text = "Typing here...", color = MaterialTheme.colorScheme.onSurface)
            },
            leadingIcon = {
                Attachments(
                    modifier = Modifier
                        .height(300.dp)
                        .fillMaxWidth()
                        .padding(start = 16.dp, end = 16.dp, bottom = 8.dp)
                        .graphicsLayer {
                            shape = RoundedCornerShape(16.dp)
                            clip = true
                        }
                        .background(Color.WhiteTransparent)
                )
            },
            trailingIcon = {
                Row {
                    IconButton(onClick = {
                        if (pin.trim().isEmpty()) {
                            return@IconButton
                        }
                        if (textInput.text.trim().isEmpty()) {
                            return@IconButton
                        }
                        me?.let {
                            messageModel.send(
                                Message(
                                    message_id = System.nanoTime().toString(),
                                    f_pin = it.f_pin,
                                    l_pin = pin,
                                    message_scope_id = "3", // 3: chat, 15: sms, 16: email
                                    server_date = System.currentTimeMillis(),
                                    status = "1",
                                    message_text = textInput.text,
                                    opposite_pin = pin,
                                    f_display_name = it.first_name + " " + it.last_name,
                                    message_large_text = textInput.text,
                                    message_text_plain = textInput.text
                                )
                            )
                            textInput = TextFieldValue("")
                        }
                    }) {
                        Icon(
                            imageVector = Icons.AutoMirrored.Filled.Send,
                            contentDescription = "",
                            tint = MaterialTheme.colorScheme.primary
                        )
                    }
                }
            },
            colors = TextFieldDefaults.colors(
                focusedContainerColor = MaterialTheme.colorScheme.surface,
                unfocusedContainerColor = MaterialTheme.colorScheme.surface,
                disabledContainerColor = MaterialTheme.colorScheme.surface,
                focusedIndicatorColor = Color.Transparent,
                unfocusedIndicatorColor = Color.Transparent,
                disabledIndicatorColor = Color.Transparent,
                errorIndicatorColor = Color.Transparent,
            ),
            keyboardOptions = KeyboardOptions(KeyboardCapitalization.Sentences),
            maxLines = 3
        )
    }
}

