package com.laseroptek.raman.ui.screens.engineer.log

import android.content.res.Configuration
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
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.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.IconButton
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.VerticalDivider
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.laseroptek.raman.R
import com.laseroptek.raman.const.CMD.CMD_FLAG
import com.laseroptek.raman.const.CMD.LASER_STATUS
import com.laseroptek.raman.const.CMD.TEMPERATURE
import com.laseroptek.raman.const.CMD.WARNING
import com.laseroptek.raman.const.CMD.WRITE_FLAG
import com.laseroptek.raman.data.source.db.model.SerialLog
import com.laseroptek.raman.ui.common.fullscreen.FullScreen
import com.laseroptek.raman.ui.theme.RobotoTypography
import com.laseroptek.raman.utils.ext.dropShadow
import com.laseroptek.raman.utils.ext.mask
import com.laseroptek.raman.utils.ext.noRippleClickable
import com.laseroptek.raman.utils.ext.px
import com.laseroptek.raman.utils.ext.simpleVerticalScrollbar
import com.laseroptek.raman.utils.ext.toHHMMSSString
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import timber.log.Timber

@OptIn(ExperimentalMaterial3Api::class, ExperimentalStdlibApi::class)
@Composable
fun LogPopup(
    title: String = stringResource(R.string.log_title),
    serialLogList: StateFlow<List<SerialLog>> = MutableStateFlow<List<SerialLog>>(emptyList()),
    onClick: (Boolean) -> Unit = {},
) {
    FullScreen(contentAlignment = Alignment.CenterEnd) {
        val selectedIndex = remember { mutableStateOf(0) }
        val serialLogListCollect by serialLogList.collectAsState()
        Timber.d("serialLogListCollect.size: ${serialLogListCollect.size}")

        val filteredSerialLogs = remember(serialLogListCollect, selectedIndex.value) {
            when(selectedIndex.value) {
                0 -> serialLogListCollect
                1 -> serialLogListCollect.filter { it.cmd.toInt().mask(CMD_FLAG).mask(WRITE_FLAG) == LASER_STATUS }
                2 -> serialLogListCollect.filter { it.cmd.toInt().mask(CMD_FLAG).mask(WRITE_FLAG) == TEMPERATURE }
                3 -> serialLogListCollect.filter { it.cmd.toInt().mask(CMD_FLAG).mask(WRITE_FLAG) == WARNING }
                else -> serialLogListCollect
            }
        }

        //Timber.d("serialLogs: ${serialLogs.toList()}")

        filteredSerialLogs.forEachIndexed { index, log ->
            Timber.d("index: $index -> id: ${log.id}")
            Timber.d("index: $index -> ts: ${log.ts}")
            Timber.d("index: $index -> desc: ${log.desc}")
        }

        Row(modifier = Modifier
            .fillMaxHeight()
            .width(640.px.dp)
            .clip(RoundedCornerShape(16.px.dp))
            .background(Color.White)
            .dropShadow(
                shape = RoundedCornerShape(16.px.dp),
                color = Color.Black.copy(alpha = 0.2f),
                blur = 48.px.dp,
                offsetX = 0.px.dp,
                offsetY = 24.px.dp,
                spread = 0.px.dp
            )
            .dropShadow(
                shape = RoundedCornerShape(16.px.dp),
                color = Color.Black.copy(alpha = 0.1f),
                blur = 6.px.dp,
                offsetX = 0.px.dp,
                offsetY = 3.px.dp,
                spread = 0.px.dp
            )
            .padding(5.px.dp),
            horizontalArrangement = Arrangement.Start,
            verticalAlignment = Alignment.Top
        ) {
            // Radio Buttons
            Column(
                modifier = Modifier
                    .fillMaxHeight()
                    .width(180.px.dp),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Top
            ) {
                // Title
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(60.px.dp)
                        .padding(start = 18.px.dp, end = 10.px.dp),
                    horizontalArrangement = Arrangement.Start,
                    verticalAlignment = Alignment.CenterVertically
                ){
                    Text(
                        text = title,
                        style = RobotoTypography.headlineLarge,
                        fontWeight = FontWeight.ExtraLight,
                        fontSize = 16.px.sp,
                        color = Color.Black,
                        textAlign = TextAlign.Center,
                    )
                    Spacer(modifier = Modifier.weight(1f))
                }

                // All
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(56.px.dp)
                        .padding(start = 20.px.dp, end = 20.px.dp),
                    horizontalArrangement = Arrangement.Start,
                    verticalAlignment = Alignment.CenterVertically
                ){
                    RadioButton(
                        selected = selectedIndex.value == 0,
                        onClick = { selectedIndex.value = 0 }
                    )
                    Text(
                        text = stringResource(R.string.all),
                        style = RobotoTypography.bodyMedium,
                        fontWeight = FontWeight.Thin,
                        fontSize = 14.px.sp,
                        color = Color.Black,
                        textAlign = TextAlign.Center,
                    )
                }

                // Laser Status
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(56.px.dp)
                        .padding(start = 20.px.dp, end = 20.px.dp),
                    horizontalArrangement = Arrangement.Start,
                    verticalAlignment = Alignment.CenterVertically
                ){
                    RadioButton(
                        selected = selectedIndex.value == 1,
                        onClick = { selectedIndex.value = 1 }
                    )
                    Text(
                        text = stringResource(R.string.laser_status),
                        style = RobotoTypography.bodyMedium,
                        fontWeight = FontWeight.Thin,
                        fontSize = 14.px.sp,
                        color = Color.Black,
                        textAlign = TextAlign.Center,
                    )
                }

                // Temperature
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(56.px.dp)
                        .padding(start = 20.px.dp, end = 20.px.dp),
                    horizontalArrangement = Arrangement.Start,
                    verticalAlignment = Alignment.CenterVertically
                ){
                    RadioButton(
                        selected = selectedIndex.value == 2,
                        onClick = { selectedIndex.value = 2 }
                    )
                    Text(
                        text = stringResource(R.string.temperature),
                        style = RobotoTypography.bodyMedium,
                        fontWeight = FontWeight.Thin,
                        fontSize = 14.px.sp,
                        color = Color.Black,
                        textAlign = TextAlign.Center,
                    )
                }

                // Alarm
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .size(120.px.dp, 56.px.dp)
                        .padding(start = 20.px.dp, end = 20.px.dp),
                    horizontalArrangement = Arrangement.Start,
                    verticalAlignment = Alignment.CenterVertically
                ){
                    RadioButton(
                        selected = selectedIndex.value == 3,
                        onClick = { selectedIndex.value = 3 }
                    )
                    Text(
                        text = stringResource(R.string.alarm),
                        style = RobotoTypography.bodyMedium,
                        fontWeight = FontWeight.Thin,
                        fontSize = 14.px.sp,
                        color = Color.Black,
                        textAlign = TextAlign.Center,
                    )
                }
            }

            // Vertical Divider
            Column {
                VerticalDivider(color = Color.Gray, thickness = 1.dp)
            }

            // Log Column
            Column(
                modifier = Modifier
                    .fillMaxHeight()
                    .width(480.px.dp),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Top
            ) {
                // Title
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(60.px.dp)
                        .padding(start = 18.px.dp, end = 10.px.dp),
                    horizontalArrangement = Arrangement.Start,
                    verticalAlignment = Alignment.CenterVertically
                ){
                    Text(
                        text = stringResource(R.string.log_data),
                        style = RobotoTypography.headlineLarge,
                        fontWeight = FontWeight.ExtraLight,
                        fontSize = 16.px.sp,
                        color = Color.Black,
                        textAlign = TextAlign.Center,
                    )

                    Spacer(modifier = Modifier.weight(1f))

                    IconButton(
                        onClick = { onClick.invoke(false) },
                        modifier = Modifier.size(40.px.dp, 40.px.dp)
                    ) {
                        Image(
                            painter = painterResource(id = R.drawable.ic_close),
                            contentDescription = null,
                            modifier = Modifier.size(24.px.dp),
                            contentScale = ContentScale.Crop
                        )
                    }
                }

                // String Lists.
                LogList(
                    serialLogList = filteredSerialLogs,
                    modifier = Modifier.height(552.px.dp),
                    selectedIndex = selectedIndex
                )

                // Cancel & OK
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(88.px.dp)
                        .padding(start = 10.px.dp, end = 10.px.dp),
                    horizontalArrangement = Arrangement.End,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    // Cancel
                    /*
                    TextButton(
                        modifier = Modifier
                            .size(68.px.dp, 40.px.dp),
                        onClick = {
                            Timber.d("onLoadClick")
                            onClick(false)
                        }
                    ) {
                        Text(
                            text = stringResource(R.string.cancel),
                            style = RobotoTypography.labelLarge,
                            fontWeight = FontWeight.Normal,
                            fontSize = 14.px.sp,
                            color = Color.Black
                        )
                    }
                    */

                    // Ok
                    TextButton(
                        modifier = Modifier
                            .size(68.px.dp, 40.px.dp),
                        onClick = {
                            Timber.d("Ok Clicked")
                            onClick(false)
                        }
                    ) {
                        Text(
                            text = stringResource(R.string.close),
                            style = RobotoTypography.labelLarge,
                            fontWeight = FontWeight.Normal,
                            fontSize = 14.px.sp,
                            color = Color.Black
                        )
                    }
                }

            }
        }

    }
}


@Composable
fun LogRow(
    serialLog: SerialLog = SerialLog(),
    index: Int,
    onItemClickListener: (Int) -> Unit,
) {
    Row(
        modifier = Modifier
            .noRippleClickable { onItemClickListener(index) }
            .fillMaxWidth()
            .padding(16.dp)
            .background(
                color = if (index == 0) Color(222, 173, 11).copy(alpha = 0.1f) else Color.Transparent
            ),
        verticalAlignment = Alignment.Top,
        horizontalArrangement = Arrangement.Start
    ) {
        // Timestamp.
        Column {
            Text(
                text = serialLog.ts.toHHMMSSString(),
                style = RobotoTypography.bodyMedium,
                fontSize = 12.px.sp,
                fontWeight = FontWeight.ExtraLight,
                color = Color.Black
            )

            Text(
                text = " | ",
                style = RobotoTypography.bodyMedium,
                fontSize = 12.px.sp,
                fontWeight = FontWeight.ExtraLight,
                color = Color.Black
            )
        }

        Spacer(Modifier.width(10.px.dp))

        // Log.
        Column {
            Text(
                text = serialLog.desc,
                style = RobotoTypography.bodyMedium,
                fontSize = 12.px.sp,
                fontWeight = FontWeight.ExtraLight,
                color = Color.Black
            )
        }

        Spacer(Modifier.weight(1f))
    }
}

@Composable
fun LogList(
    modifier: Modifier = Modifier,
    serialLogList: List<SerialLog> = emptyList(),
    selectedIndex: MutableState<Int> = mutableStateOf(0),
) {
    val state = rememberLazyListState()
    LazyColumn(
        modifier = modifier.simpleVerticalScrollbar(state),
        state = state
    ) {
        itemsIndexed(serialLogList) { index, serialLog ->
            LogRow(
                serialLog,
                index,
                onItemClickListener = { idx ->
                    Timber.d("String Item Clicked(${idx})")
                    selectedIndex.value = idx
                },
            )
        }
    }
}


@Preview(
    uiMode = Configuration.UI_MODE_NIGHT_NO,
    showBackground = false,
    device = "spec:width=1920dp,height=1080dp,dpi=150,isRound=false,chinSize=0dp,orientation=landscape"
)

@Composable
fun PreviewLogView() {
    Column(horizontalAlignment = Alignment.CenterHorizontally) {
        LogPopup()
    }

}
