package com.syaroful.agrilinkvocpro.plant_disease_detection_feature.presentation.history

import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
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.Row
import androidx.compose.foundation.layout.Spacer
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.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import com.syaroful.agrilinkvocpro.R
import com.syaroful.agrilinkvocpro.core.components.DefaultErrorComponent
import com.syaroful.agrilinkvocpro.plant_disease_detection_feature.core.component.DiseaseDetectionBanner
import com.syaroful.agrilinkvocpro.plant_disease_detection_feature.core.extention.toBitmap
import com.syaroful.agrilinkvocpro.plant_disease_detection_feature.core.extention.toFormattedDate
import com.syaroful.agrilinkvocpro.plant_disease_detection_feature.data.local.entity.PlantDiagnosisEntity
import com.syaroful.agrilinkvocpro.presentation.theme.MainGreen

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HistoryScreen(
    navController: NavHostController,
    viewModel: HistoryViewModel
) {
    val diagnoses by viewModel.diagnoses.collectAsState()
    val fillAndPadding = Modifier
        .fillMaxWidth()
        .padding(horizontal = 16.dp)

    Scaffold(
        topBar = {
            TopAppBar(
                title = {
                    Text(
                        "Deteksi Penyakit Tanaman",
                        style = MaterialTheme.typography.titleMedium,
                        modifier = Modifier.fillMaxWidth(),
                        textAlign = TextAlign.Center
                    )
                },
            )
        }
    ) { innerPadding ->
        val baseModifier = fillAndPadding.then(Modifier.padding(innerPadding))

        if (diagnoses.isEmpty()) {
            Column(
                modifier = baseModifier,
                verticalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                DiseaseDetectionBanner()
                StartDiagnosisButton { navController.navigate("camera_screen") }
                DefaultErrorComponent(
                    label = "Waduh!",
                    message = "Ga ada data sama sekali, coba tambahkan",
                    painter = painterResource(id = R.drawable.mascot_surprised)
                )
            }
        } else {
            LazyColumn(
                modifier = baseModifier,
                verticalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                item { DiseaseDetectionBanner() }
                item { StartDiagnosisButton { navController.navigate("camera_screen") } }
                item {
                    Text(
                        "Riwayat Deteksi",
                        style = MaterialTheme.typography.titleMedium
                    )
                }
                items(diagnoses) { diagnosis ->
                    DiagnosisListItem(diagnosis, navController)
                }
            }
        }
    }
}

@Composable
private fun StartDiagnosisButton(onClick: () -> Unit) {
    Button(
        modifier = Modifier.fillMaxWidth(),
        onClick = onClick,
        colors = ButtonDefaults.buttonColors(
            containerColor = Color.Transparent,
            contentColor = MainGreen
        ),
        shape = RoundedCornerShape(8.dp),
        border = BorderStroke(color = MainGreen, width = 1.dp)
    ) {
        Text("Mulai diagnosis")
    }
}

@Composable
private fun DiagnosisListItem(
    diagnosis: PlantDiagnosisEntity,
    navController: NavHostController
) {
    Box(
        modifier = Modifier
            .clickable {
                navController.currentBackStackEntry?.savedStateHandle?.set("plantData", diagnosis)
                navController.navigate("detail-history/${diagnosis.id}")
            }
            .fillMaxWidth()
            .background(
                color = MaterialTheme.colorScheme.surfaceContainer,
                shape = RoundedCornerShape(8.dp)
            )
    ) {
        Row(modifier = Modifier.padding(12.dp).fillMaxWidth()) {
            Box(
                modifier = Modifier
                    .size(80.dp)
                    .clip(RoundedCornerShape(4.dp))
            ) {
                Image(
                    bitmap = diagnosis.image.toBitmap().asImageBitmap(),
                    contentDescription = "Diagnosis Image"
                )
            }
            Spacer(modifier = Modifier.width(8.dp))
            Column(
                modifier = Modifier.height(80.dp),
                verticalArrangement = Arrangement.SpaceBetween
            ) {
                Text(
                    "Diagnosis: ${diagnosis.diagnosis}",
                    style = MaterialTheme.typography.labelLarge,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
                Text(
                    diagnosis.description,
                    style = MaterialTheme.typography.bodySmall,
                    maxLines = 2,
                    overflow = TextOverflow.Ellipsis
                )
                Row {
                    Image(
                        modifier = Modifier.size(14.dp),
                        painter = painterResource(R.drawable.ic_calendar),
                        contentDescription = "Date Icon",
                        colorFilter = ColorFilter.tint(Color.Gray)
                    )
                    Spacer(modifier = Modifier.width(4.dp))
                    Text(
                        diagnosis.timestamp.toFormattedDate(),
                        style = MaterialTheme.typography.bodySmall,
                    )
                }
            }
        }
    }
}


