package com.laseroptek.raman.ui.screens.home.dcd

import android.content.res.Configuration
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
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.shape.RoundedCornerShape
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
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.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
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 androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.laseroptek.raman.R
import com.laseroptek.raman.const.CMD
import com.laseroptek.raman.const.PURGE_STATUS
import com.laseroptek.raman.const.READ_WRITE
import com.laseroptek.raman.data.datasource.db.RamanDatabase
import com.laseroptek.raman.data.model.serial.DcdGasOnOff
import com.laseroptek.raman.data.model.serial.PurgeBubble
import com.laseroptek.raman.data.source.db.RamanDatabaseService
import com.laseroptek.raman.repository.DatabaseRepository
import com.laseroptek.raman.repository.PreferenceRepository
import com.laseroptek.raman.repository.SerialPortRepository
import com.laseroptek.raman.ui.common.button.ButtonWithGradientHIconAndText
import com.laseroptek.raman.ui.common.fullscreen.FullScreen
import com.laseroptek.raman.ui.screens.main.MainViewModel
import com.laseroptek.raman.ui.theme.RobotoTypography
import com.laseroptek.raman.utils.DefaultDispatcherProvider
import com.laseroptek.raman.utils.ext.dropShadow
import com.laseroptek.raman.utils.ext.px
import kotlinx.coroutines.launch
import timber.log.Timber

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DcdSettingPopup(
    mainViewModel: MainViewModel = hiltViewModel<MainViewModel>(),
    //dcdViewModel: DcdViewModel = hiltViewModel<DcdViewModel>(),
    title: String = stringResource(R.string.dcd_setting_title),
    onDismiss: () -> Unit = {},
) {
    val scope = rememberCoroutineScope()

    var showDcdOptionDialog by remember { mutableStateOf(false) }
    var showResetDcdCountDialog by remember { mutableStateOf(false) }
    var showPurgeProgressDialog by remember { mutableStateOf(false) }

    val gasChargeRate by mainViewModel.gasChargeRate.collectAsStateWithLifecycle()

    val selectedSprayDcdIndex by mainViewModel.selectedSprayDcdIndex.collectAsState()
    //val selectedOptionIndex by mainViewModel.selectedOptionIndex.collectAsState()

    Timber.d("Gas Charge: ${gasChargeRate.toInt()}%")

    //val optionValue = remember { mutableStateOf(mainViewModel.sprayDcdList[selectedSprayDcdIndex].copy()) }
    val sprayDcd by mainViewModel.sprayDcd.collectAsState()

    val dcdCount by mainViewModel.dcdCount.collectAsState()
    val dcdType by mainViewModel.dcdType.collectAsState()

    // 0: initial, 0x41(A: Accept), 0x42(B: Complete), 0x46(F: Fail/Refused)
    val purgeBubble by mainViewModel.purgeBubble.collectAsState()

    LaunchedEffect(Unit) {
        // init purgeBubble variable
        mainViewModel.setPurgeBubble(
            PurgeBubble(PURGE_STATUS.INIT)
        )

        //dcdViewModel.setSprayDcdList(mainViewModel.sprayDcdList)
        //dcdViewModel.setSelectedSprayDcdIndex(mainViewModel.selectedSprayDcdIndex.value)

        //Timber.d("sprayDcdList: ${dcdViewModel.sprayDcdList}")
        //Timber.d("selectedSprayDcdIndex: ${selectedSprayDcdIndex}")
    }

    FullScreen(contentAlignment= Alignment.Center) {
        Box {
            // Main Popup Content
            Column(
                modifier = Modifier
                    .size(574.px.dp, 372.px.dp)
                    .clip(RoundedCornerShape(16.px.dp))
                    .background(Color.White)
                    .dropShadow(
                        shape = RoundedCornerShape(topStart = 16.px.dp, bottomStart = 16.px.dp),
                        color = Color.Black.copy(alpha = 0.2f),
                        blur = 48.px.dp,
                        offsetX = 0.px.dp,
                        offsetY = 2.px.dp,
                        spread = 0.px.dp
                    )
                    .dropShadow(
                        shape = RoundedCornerShape(topStart = 16.px.dp, bottomStart = 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(start = 0.px.dp, end = 0.px.dp, top = 0.px.dp, bottom = 0.px.dp),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Top
            ) {
                // Close
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(30.px.dp)
                        .padding(top = 10.px.dp, end = 10.px.dp),
                    horizontalArrangement = Arrangement.End,
                    verticalAlignment = Alignment.Bottom,
                ) {
                    // Close
                    IconButton(
                        onClick = {
                            // onClickSave.invoke(false)
                            Timber.d("onDismiss")

                            //mainViewModel.setSelectedSprayDcdIndex( selectedSprayDcdIndex )
                            //mainViewModel.setSprayDcdList( dcdViewModel.sprayDcdList )

                            //Timber.d("selectedSprayDcdIndex: ${selectedSprayDcdIndex}")
                            //Timber.d("sprayDcdList: ${dcdViewModel.sprayDcdList}")

                            //mainViewModel.saveSprayDcdListToPreference()

                            onDismiss.invoke()
                        },
                        modifier = Modifier.size(32.px.dp, 32.px.dp)
                    ) {
                        Image(
                            painter = painterResource(id = R.drawable.ic_close),
                            contentDescription = null,
                            modifier = Modifier.size(20.px.dp),
                            contentScale = ContentScale.Crop
                        )
                    }
                }

                // Title
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(35.px.dp)
                        .padding(start = 20.px.dp),
                    horizontalArrangement = Arrangement.Start,
                    verticalAlignment = Alignment.Bottom
                ) {
                    // Cooler Image
                    Image(
                        painter = painterResource(id = R.drawable.ic_cooler_2x),
                        contentDescription = null,
                        modifier = Modifier
                            .size(35.px.dp),
                    )

                    Spacer(modifier = Modifier.width(2.px.dp))

                    // Title
                    Text(
                        text = title,
                        style = RobotoTypography.headlineSmall,
                        fontWeight = FontWeight.ExtraLight,
                        fontSize = 24.px.sp,
                        color = Color.Black,
                        textAlign = TextAlign.Center,
                    )
                }

                // Expected Value
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(20.px.dp)
                        .padding(end = 30.px.dp),
                    horizontalArrangement = Arrangement.End,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    // DCD Count / Expected Value
                    Text(
                        text = "%06d".format(dcdCount),
                        style = RobotoTypography.bodySmall,
                        fontWeight = FontWeight.Thin,
                        fontSize = 10.px.sp,
                        color = Color(0,0,0),
                    )
                    Text(
                        text = "/%06d".format(
                            (if (dcdType.canType == 700) 1 else 2) * (6000 * dcdType.lifeSpan).toInt()
                        ),
                        style = RobotoTypography.bodySmall,
                        fontWeight = FontWeight.Thin,
                        fontSize = 10.px.sp,
                        color = Color(82,82,91),
                    )
                }

                // { Spray & Delay } & Battery
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(210.px.dp)
                        .padding(start = 20.px.dp),
                    horizontalArrangement = Arrangement.Center,
                    verticalAlignment = Alignment.Top
                ) {
                    // Left { Spray & Delay }
                    Column(
                        modifier = Modifier
                            .fillMaxHeight()
                            .width(221.px.dp),
                        horizontalAlignment = Alignment.CenterHorizontally,
                        verticalArrangement = Arrangement.Top
                    ) {
                        // 1, 3, 5
                        for (i in 1..5 step 2) {
                            DcdBox(
                                id = i,
                                selNumber = selectedSprayDcdIndex,
                                sprayDcdList = mainViewModel.sprayDcdList,
                                onClickDcd = {
                                    mainViewModel.setSelectedSprayDcdIndex(i)
                                    val optionValue  = mainViewModel.sprayDcdList[i]
                                    mainViewModel.setSprayDcd(optionValue)
                                    mainViewModel.txPacket(READ_WRITE.WRITE, CMD.SPRAY_DCD, optionValue)

                                    scope.launch {
                                        mainViewModel.saveSprayDcdIndexToPreference()
                                        mainViewModel.saveSprayDcdToPreference()
                                    }

                                },
                                onClickOption = {
                                    mainViewModel.setSelectedSprayDcdIndex(i)
                                    val optionValue  = mainViewModel.sprayDcdList[i]
                                    mainViewModel.setSprayDcd(optionValue)

                                    scope.launch {
                                        mainViewModel.saveSprayDcdIndexToPreference()
                                        mainViewModel.saveSprayDcdToPreference()
                                    }

                                    showDcdOptionDialog = true
                                }
                            )
                            if (i < 5) {
                                Spacer(modifier = Modifier.weight(1f))
                            }
                        }
                    }

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

                    // Right { Spray & Delay }
                    Column(
                        modifier = Modifier
                            .fillMaxHeight()
                            .width(221.px.dp),
                        horizontalAlignment = Alignment.CenterHorizontally,
                        verticalArrangement = Arrangement.Top
                    ) {
                        // 2, 4, 6
                        for (i in 2..6 step 2) {
                            DcdBox(
                                id = i,
                                selNumber = selectedSprayDcdIndex,
                                sprayDcdList = mainViewModel.sprayDcdList,
                                onClickDcd = {
                                    mainViewModel.setSelectedSprayDcdIndex(i)
                                    val optionValue  = mainViewModel.sprayDcdList[i]
                                    mainViewModel.setSprayDcd(optionValue)
                                    mainViewModel.txPacket(READ_WRITE.WRITE, CMD.SPRAY_DCD, optionValue)

                                    scope.launch {
                                        mainViewModel.saveSprayDcdToPreference()
                                    }
                                },
                                onClickOption = {
                                    mainViewModel.setSelectedSprayDcdIndex(i)
                                    val optionValue = mainViewModel.sprayDcdList[i]
                                    mainViewModel.setSprayDcd(optionValue)

                                    scope.launch {
                                        mainViewModel.saveSprayDcdToPreference()
                                    }

                                    showDcdOptionDialog = true
                                }
                            )
                            if (i < 6) {
                                Spacer(modifier = Modifier.weight(1f))
                            }
                        }
                    }

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

                    // Battery (Percent)
                    GradientSlider(
                        modifier = Modifier
                            .fillMaxHeight()
                            .size(40.px.dp, 210.px.dp),
                        chargeRate = gasChargeRate.toInt()
                    )

                    // Icon
                    Column(
                        modifier = Modifier
                            .fillMaxHeight()
                            .width(50.px.dp)
                            .padding(start = 3.px.dp),
                        horizontalAlignment = Alignment.Start,
                        verticalArrangement = Arrangement.Center
                    ) {
                        Image(
                            painter = painterResource(id = R.drawable.ic_full),
                            contentDescription = "Button Icon",
                            modifier = Modifier.size(30.px.dp, 30.px.dp),
                            contentScale = ContentScale.Crop

                        )
                        Spacer(modifier = Modifier.weight(1f)) // Add space between icon and text
                        Image(
                            painter = painterResource(id = R.drawable.ic_empty),
                            contentDescription = "Button Icon",
                            modifier = Modifier.size(30.px.dp, 30.px.dp),
                            contentScale = ContentScale.Crop
                        )
                    }
                }

                Spacer(modifier = Modifier.height(20.px.dp))

                // { Valve - Purge - Spray } icons
                Row(modifier = Modifier
                    .fillMaxWidth()
                    .height(80.px.dp)
                    .padding(start = 20.px.dp, end = 30.px.dp),
                    horizontalArrangement = Arrangement.Center,
                    verticalAlignment = Alignment.Top
                ) {
                    // Purge Button
                    // purgeBubble - 0: initial, 0x41(A: Accept), 0x42(B: Complete), 0x46(F: Fail/Refused)
                    ButtonWithGradientHIconAndText(
                        modifier = Modifier
                            .size(97.px.dp, 40.px.dp)
                            .clip(RoundedCornerShape(20.px.dp))
                            .background(
                                brush = Brush.linearGradient(
                                    colorStops = arrayOf(
                                        0.0f to Color(234, 232, 235),
                                        1.0f to Color(255, 251, 255),
                                    )
                                ),
                                shape = RoundedCornerShape(20.px.dp)
                            )
                            .border(
                                8.px.dp,
                                brush = Brush.linearGradient(
                                    colorStops = arrayOf(
                                        0.0f to Color(250, 250, 250),
                                        1.0f to Color(233, 231, 234),
                                    )
                                ),
                                shape = RoundedCornerShape(20.px.dp)
                            )
                            .dropShadow(
                                shape = RoundedCornerShape(20.px.dp),
                                color = Color(0, 0, 0).copy(alpha = 0.09f),
                                blur = 12.px.dp,
                                offsetX = 0.px.dp,
                                offsetY = 4.px.dp,
                                spread = 0.px.dp
                            ),
                        title = "Purge",
                        painter = painterResource(id = R.drawable.ic_purge),
                        onClick = {
                            Timber.d("onClickPurge")

                            if (purgeBubble.value == PURGE_STATUS.ACCEPT) {
                                Timber.d("onClickPurge: PURGE_STATUS.ACTIVATE")
                                return@ButtonWithGradientHIconAndText
                            }

                            // init purgeBubble variable
                            mainViewModel.setPurgeBubble(
                                PurgeBubble(PURGE_STATUS.INIT)
                            )

                            // send tx
                            mainViewModel.txPacket(
                                READ_WRITE.WRITE,
                                CMD.PURGE_BUBBLE,
                                byteArrayOf(PURGE_STATUS.ACCEPT.toByte())
                            )

                            showPurgeProgressDialog = true
                        }
                    )

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


                    // Refresh Button
                    //if (chargeRate < 20f) {
                        ButtonWithGradientHIconAndText(
                            modifier = Modifier
                                .size(97.px.dp, 40.px.dp)
                                .clip(RoundedCornerShape(20.px.dp))
                                .background(
                                    brush = Brush.linearGradient(
                                        colorStops = arrayOf(
                                            0.0f to Color(234, 232, 235),
                                            1.0f to Color(255, 251, 255),
                                        )
                                    ),
                                    shape = RoundedCornerShape(20.px.dp)
                                )
                                .border(
                                    8.px.dp,
                                    brush = Brush.linearGradient(
                                        colorStops = arrayOf(
                                            0.0f to Color(250, 250, 250),
                                            1.0f to Color(233, 231, 234),
                                        )
                                    ),
                                    shape = RoundedCornerShape(20.px.dp)
                                )
                                .dropShadow(
                                    shape = RoundedCornerShape(20.px.dp),
                                    color = Color(0, 0, 0).copy(alpha = 0.09f),
                                    blur = 12.px.dp,
                                    offsetX = 0.px.dp,
                                    offsetY = 4.px.dp,
                                    spread = 0.px.dp
                                ),
                        title = "Refresh",
                        painter = painterResource(id = R.drawable.ic_refresh),
                        onClick = {
                            Timber.d("onClickRefresh")
                            // Perform action when button is clicked
                            // onClickPurge.invoke(!purgeStatus.value)

                            /*
                            Timber.d("onClickRefresh")
                            mainViewModel.txPacket(
                                READ_WRITE.WRITE,
                                CMD.PURGE_BUBBLE,
                                byteArrayOf(PURGE_STATUS.ACTIVATE.toByte())
                            )
                            */

                            // mainViewModel.setDcdCount(0)
                            // mainViewModel.setCanReplaced( false )

                            showResetDcdCountDialog = true
                        }
                    )
                    //}

                    // end if (canReplaced)

                    Spacer(modifier = Modifier.width(20.px.dp))

                    // Test Button
                    ButtonWithGradientHIconAndText(
                        modifier = Modifier
                            .size(97.px.dp, 40.px.dp)
                            .clip(RoundedCornerShape(20.px.dp))
                            .background(
                                brush = Brush.linearGradient(
                                    colorStops = arrayOf(
                                        0.0f to Color(234, 232, 235),
                                        1.0f to Color(255, 251, 255),
                                    )
                                ),
                                shape = RoundedCornerShape(20.px.dp)
                            )
                            .border(
                                8.px.dp,
                                brush = Brush.linearGradient(
                                    colorStops = arrayOf(
                                        0.0f to Color(250, 250, 250),
                                        1.0f to Color(233, 231, 234),
                                    )
                                ),
                                shape = RoundedCornerShape(20.px.dp)
                            )
                            .dropShadow(
                                shape = RoundedCornerShape(20.px.dp),
                                color = Color(0, 0, 0).copy(alpha = 0.09f),
                                blur = 12.px.dp,
                                offsetX = 0.px.dp,
                                offsetY = 4.px.dp,
                                spread = 0.px.dp
                            ),
                        title = "Test",
                        painter = painterResource(id = R.drawable.ic_spray),
                        onClick = {
                            Timber.d("onClickTest")
                            /* DCD Sparay : 0x07
                            val sprayDcd = mainViewModel.sprayDcdList[selectedSprayDcdIndex]

                            if (selectedSprayDcdIndex == 0) {
                                sprayDcd.status = 0x44  // off
                            } else {
                                sprayDcd.status = 0x41  // on
                            }

                            Timber.d("idx: ${selectedSprayDcdIndex}, sprayDcd: ${sprayDcd}")

                            mainViewModel.txPacket(READ_WRITE.WRITE, CMD.SPRAY_DCD, sprayDcd)

                            // sprayDCD 수신시 증가
                            //mainViewModel.setDcdCount( mainViewModel.dcdCount.value + 1 )
                            */

                            val data = DcdGasOnOff(status = 0x54)   // Test
                            mainViewModel.txPacket(READ_WRITE.WRITE, CMD.DCD_GAS, data)
                        }
                    )
                }
            }
        }

        ///////////////////////////////////////////////////////////////////////////////////////////
        // Popup

        if (showDcdOptionDialog) {
            DcdOptionDialog(
                //showDcdOptionDialog = mainViewModel.showDcdOptionDialog,
                optionValue = sprayDcd,   //mainViewModel.optionValue,
                //title = "Set the Option%d Value".format(mainViewModel.selectedOptionIndex.value),
                onClickSprayTime = { sprayTime ->
                    mainViewModel.setSprayDcd(
                        sprayDcd.copy(
                            sprayTime = sprayTime
                        )
                    )
                    mainViewModel.setSprayDcd(
                        selectedSprayDcdIndex,
                        sprayDcd
                    )

                    scope.launch {
                        mainViewModel.saveSprayDcdToPreference()
                    }
                },
                onClickSprayDelay = { sprayDelay ->
                    mainViewModel.setSprayDcd(
                        sprayDcd.copy(
                            sprayDelay = sprayDelay
                        )
                    )
                    mainViewModel.setSprayDcd(
                        selectedSprayDcdIndex,
                        sprayDcd
                    )

                    scope.launch {
                        mainViewModel.saveSprayDcdToPreference()
                    }
                },
                onClick = { ok ->
                    Timber.d("DcdOptionDialog -> ok: $ok")
                    if (ok) {
                        mainViewModel.setSprayDcd(
                            selectedSprayDcdIndex,
                            sprayDcd
                        )

                        mainViewModel.setSelectedSprayDcdIndex( selectedSprayDcdIndex )
                        //mainViewModel.setSprayDcdList( mainViewModel.sprayDcdList )

                        scope.launch {
                            mainViewModel.saveSprayDcdIndexToPreference()
                            mainViewModel.saveSprayDcdToPreference()
                            mainViewModel.saveSprayDcdListToPreference()
                        }

                    }

                    // save values to Preference
                    showDcdOptionDialog = false
                }
            )
        }

        if (showResetDcdCountDialog) {
            ResetDcdCountDialog(
                title = stringResource(R.string.reset_dcd_count_title),
                onClick = { okValue ->
                    Timber.d("ResetDcdCountDialog: $okValue")
                    if (okValue) {
                        mainViewModel.setDcdCount(0)
                    }
                    showResetDcdCountDialog = false
                }
            )
        }

        // Purge Progress
        if (showPurgeProgressDialog) {
            PurgeProgressDialog(
                onDismissRequest = {
                    showPurgeProgressDialog = false
                },
                purgeBubble = purgeBubble
            )
        }


    }
}


@Preview(
    apiLevel = 34,
    uiMode = Configuration.UI_MODE_NIGHT_NO,
    showBackground = false,
    //device = "spec:width=1920dp,height=1080dp,dpi=150,isRound=false,chinSize=0dp,orientation=landscape"
)
@Composable
fun PreviewDcdSettingPopup(
    mainViewModel:MainViewModel = MainViewModel(
        preferenceRepository = PreferenceRepository(LocalContext.current),
        serialPortRepository = SerialPortRepository.createWithFakeRepository(),
        databaseRepository = DatabaseRepository(RamanDatabaseService(RamanDatabase.getInstance(LocalContext.current))),
        dispatcherProvider = DefaultDispatcherProvider(),
        applicationContext = LocalContext.current
    )
) {
    DcdSettingPopup(
        mainViewModel = mainViewModel,
    )
}
