package com.syaroful.agrilinkvocpro.control_feature.presentation.history

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
import androidx.compose.runtime.Composable
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.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import com.syaroful.agrilinkvocpro.control_feature.core.state.ControlState
import com.syaroful.agrilinkvocpro.control_feature.core.utils.getRelativeTime
import com.syaroful.agrilinkvocpro.control_feature.data.model.ActuatorHistoryResponse
import com.syaroful.agrilinkvocpro.core.components.DefaultErrorComponent
import com.syaroful.agrilinkvocpro.presentation.theme.MainGreen
import org.koin.androidx.compose.koinViewModel

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ControlHistoryScreen(
    controlHistoryViewModel: ControlHistoryViewModel = koinViewModel(),
    navController: NavController
) {
    val historyState by controlHistoryViewModel.historyState.collectAsState()

    val isRefreshing = remember { mutableStateOf(false) }

    Scaffold(
        topBar = {
            TopAppBar(
                title = {
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally,
                        modifier = Modifier.fillMaxWidth()
                    ) {
                        Text("Riwayat Kontrol Aktuator", style = MaterialTheme.typography.titleMedium)
                    }
                },
                navigationIcon = {
                    IconButton(onClick = {
                        navController.popBackStack()
                    }) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
                    }
                },
            )
        },

    ) { innerPadding ->
        PullToRefreshBox(
            isRefreshing = isRefreshing.value,
            onRefresh = {
                isRefreshing.value = true
                controlHistoryViewModel.getActuatorHistory()
            },
        ) {
            LazyColumn(
                modifier = Modifier
                    .padding(innerPadding)
                    .fillMaxWidth(),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center
            ) {
                when (historyState) {
                    is ControlState.Error -> {
                        isRefreshing.value = false
                        item {
                            DefaultErrorComponent(
                                message = (historyState as ControlState.Error).message,
                                label = "Oops!",
                            )
                        }
                    }

                    is ControlState.Success -> {
                        isRefreshing.value = false
                        val data =
                            (historyState as ControlState.Success<ActuatorHistoryResponse>).data?.data
                        if (!data.isNullOrEmpty()) {
                            val reversedData = data.reversed()
                            items(reversedData) { historyData ->
                                ListItem(
                                    leadingContent = {
                                        Text("${historyData?.actuatorId}")
                                    },
                                    headlineContent = {
                                        val state =
                                            if (historyData?.action == "ON") "Diaktifkan oleh " else "Dinonaktifkan oleh "
                                        Text(text = "$state ${historyData?.triggeredBy}")
                                    },
                                    supportingContent = {
                                        Text(
                                            text = getRelativeTime(historyData?.createdAt.toString())
                                        )
                                    },
                                    trailingContent = {
                                        Text("${historyData?.action}",
                                            color = if (historyData?.action == "ON") MainGreen else Color.Red
                                        )
                                    },
                                    shadowElevation = 2.dp

                                )
                            }
                        } else {
                            item {
                                Text("Tidak ada data riwayat kontrol")
                            }
                        }
                    }

                    is ControlState.Loading -> {
                        item {
                            CircularProgressIndicator(
                                color = MainGreen
                            )
                        }
                    }

                    else -> {}
                }
            }
        }
    }
}