package com.syaroful.agrilinkvocpro.plant_disease_detection_feature.presentation.detail

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.Card
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
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.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.syaroful.agrilinkvocpro.R
import com.syaroful.agrilinkvocpro.core.components.AppButton
import com.syaroful.agrilinkvocpro.core.components.DefaultErrorComponent
import com.syaroful.agrilinkvocpro.plant_disease_detection_feature.core.AppConstant
import com.syaroful.agrilinkvocpro.plant_disease_detection_feature.presentation.camera.CameraViewModel
import com.syaroful.agrilinkvocpro.presentation.theme.MainGreen
import org.koin.androidx.compose.koinViewModel

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DetailScreen(
    cameraViewModel: CameraViewModel,
    onBack: () -> Unit = {}
) {
    val diagnosisViewModel: PlantDiagnosisViewModel = koinViewModel()

    val bitmap by cameraViewModel.bitmap.collectAsState()
    val diagnosisState by diagnosisViewModel.state.collectAsState()
    val saveLoading by diagnosisViewModel.saveLoadingState.collectAsState()

    LaunchedEffect(bitmap) {
        if (bitmap != null && diagnosisState == null) {
            diagnosisViewModel.analyzePlant(bitmap = bitmap!!, prompt = AppConstant().prompt)
        }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = {
                    Text(
                        "Deteksi Penyakit Tanaman",
                        modifier = Modifier.fillMaxWidth(),
                        textAlign = TextAlign.Center
                    )
                },
                navigationIcon = {
                    IconButton(onClick = onBack) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
                    }
                }
            )
        }
    ) { innerPadding ->
        Box(
            modifier = Modifier
                .verticalScroll(rememberScrollState())
                .fillMaxSize()
                .padding(innerPadding)
                .padding(24.dp),
            contentAlignment = Alignment.TopCenter
        ) {
            Column(
                modifier = Modifier.fillMaxSize(),
                verticalArrangement = Arrangement.spacedBy(
                    10.dp,
                    Alignment.Top
                )
            ) {
                bitmap?.let {
                    Card(
                        modifier = Modifier
                            .fillMaxWidth()
                            .heightIn(max = 180.dp),
                        shape = RoundedCornerShape(8.dp),
                    ) {
                        Image(
                            modifier = Modifier.fillMaxSize(),
                            bitmap = it.asImageBitmap(),
                            contentDescription = "Gambar Tanaman",
                            contentScale = ContentScale.Crop, // Make image fill the Card
                        )
                    }
                }
                when (val result = diagnosisState) {
                    null -> {
                        Box(
                            modifier = Modifier.align(Alignment.CenterHorizontally)
                        ) {
                            CircularProgressIndicator(color = MainGreen)
                        }
                    }

                    else -> {
                        if (result.isFailure) {
                            DefaultErrorComponent(
                                painter = painterResource(id = R.drawable.mascot_confused),
                                label = "Oops!",
                                message = result.exceptionOrNull()?.message.toString()
                            )
                        } else if (result.isSuccess) {
                            val data = result.getOrNull()
                            if (data?.diagnosis == "Sehat") {
                                Box(
                                    modifier = Modifier
                                        .background(
                                            color = Color.Green,
                                            shape = RoundedCornerShape(4.dp)
                                        )
                                        .padding(vertical = 4.dp, horizontal = 8.dp)
                                ) {
                                    Text(
                                        text = "Tanaman Sehat",
                                        color = Color.White,
                                        style = MaterialTheme.typography.labelMedium
                                    )
                                }
                            } else if (data?.diagnosis != null) {
                                Box(
                                    modifier = Modifier
                                        .background(
                                            color = Color.Red,
                                            shape = RoundedCornerShape(4.dp)
                                        )
                                        .padding(vertical = 4.dp, horizontal = 8.dp)
                                ) {
                                    Text(
                                        text = "Terkena Penyakit",
                                        color = Color.White,
                                        style = MaterialTheme.typography.labelMedium
                                    )
                                }
                                Text(
                                    text = "Penyakit Terdeteksi :",
                                    style = MaterialTheme.typography.bodySmall,
                                    color = Color(0xFFFF3D3D)
                                )
                                Text(
                                    data.diagnosis,
                                    style = MaterialTheme.typography.headlineSmall
                                )
                                Text(
                                    text = "Penyebab :",
                                    style = MaterialTheme.typography.bodySmall,
                                    color = Color(0xFFFF3D3D)
                                )
                                Text(
                                    data.cause ?: "Unknown",
                                    style = MaterialTheme.typography.titleSmall
                                )
                                TextCardComponent(
                                    label = "Informasi Umum",
                                ) {
                                    Text(
                                        modifier = Modifier.fillMaxWidth(),
                                        text = data.description ?: "Unknown",
                                        style = MaterialTheme.typography.bodyMedium
                                    )
                                }
                                TextCardComponent(
                                    label = "Pengobatan",
                                ) {
                                    data.treatment?.forEach {
                                        Column {
                                            Text(
                                                it.method ?: "Unknown",
                                                style = MaterialTheme.typography.labelLarge
                                            )
                                            Text(
                                                it.description ?: "Unknown",
                                                style = MaterialTheme.typography.bodySmall
                                            )
                                            HorizontalDivider()
                                        }
                                    }
                                }
                                TextCardComponent(
                                    label = "Pencegahan",
                                ) {
                                    data.prevention?.forEach {
                                        Column {
                                            Text(
                                                it,
                                                style = MaterialTheme.typography.bodySmall
                                            )
                                            HorizontalDivider()
                                        }
                                    }
                                }
                                AppButton(
                                    label = if (saveLoading) "Menyimpan..." else "Simpan Hasil Deteksi",
                                    isEnable = !saveLoading
                                ) {
                                    diagnosisViewModel.saveResultToLocal(data, bitmap!!)
                                }
                            } else {
                                Text("Gagal parsing response")
                            }
                        }
                    }
                }
            }
        }
    }
}

@Composable
fun TextCardComponent(
    label: String,
    content: @Composable () -> Unit
) {
    Column(
        modifier = Modifier
            .background(
                color = MaterialTheme.colorScheme.surfaceContainer,
                shape = RoundedCornerShape(8.dp)
            )
            .padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(
            10.dp,
            Alignment.Top
        ),
        horizontalAlignment = Alignment.Start,
    ) {
        Text(
            modifier = Modifier.fillMaxWidth(),
            text = label,
            style = MaterialTheme.typography.titleMedium
        )
        content()
    }
}

