//Muhammad Fadzel Hadean Rukrus
//202310715220
package com.example.tiptime

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.tiptime.ui.theme.TipTimeTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        enableEdgeToEdge()
        super.onCreate(savedInstanceState)
        setContent {
            TipTimeTheme {
                Surface(modifier = Modifier.fillMaxSize()) {
                    BMIApp()
                }
            }
        }
    }
}

@Composable
fun BMIApp() {
    var started by remember { mutableStateOf(false) }

    if (!started) {
        GetStartedScreen(onStart = { started = true })
    } else {
        BMICalculatorScreen()
    }
}

@Composable
fun GetStartedScreen(onStart: () -> Unit) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(24.dp),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        // === Logo Aplikasi ===
        Image(
            painter = painterResource(id = R.drawable.logobmi  ), // logo.png di drawable
            contentDescription = "App Logo",
            modifier = Modifier
                .size(150.dp)
                .padding(bottom = 24.dp)
        )



        // === Tombol Mulai ===
        Button(
            onClick = onStart,
            modifier = Modifier
                .fillMaxWidth(0.6f)
                .height(50.dp)
        ) {
            Text("Mulai Sekarang")
        }
    }
}

@Composable
fun BMICalculatorScreen() {
    var height by remember { mutableStateOf("") }
    var weight by remember { mutableStateOf("") }
    var useMetric by remember { mutableStateOf(true) }

    val heightVal = height.toDoubleOrNull() ?: 0.0
    val weightVal = weight.toDoubleOrNull() ?: 0.0
    val bmiVal = calculateBMIValue(heightVal, weightVal, useMetric)
    val bmiText = String.format("%.2f", bmiVal)
    val category = calculateBMICategory(bmiVal)
    val imageRes = getCategoryImage(category)

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(24.dp)
            .verticalScroll(rememberScrollState()),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(
            text = "Kalkulator BMI",
            style = MaterialTheme.typography.headlineLarge,
            modifier = Modifier.padding(top = 40.dp, bottom = 16.dp)
        )

        OutlinedTextField(
            value = height,
            onValueChange = { height = it },
            label = { Text("Tinggi Badan (${if (useMetric) "cm" else "inch"})") },
            keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(
                keyboardType = KeyboardType.Number,
                imeAction = ImeAction.Next
            ),
            modifier = Modifier
                .fillMaxWidth()
                .padding(bottom = 16.dp)
        )

        OutlinedTextField(
            value = weight,
            onValueChange = { weight = it },
            label = { Text("Berat Badan (${if (useMetric) "kg" else "lb"})") },
            keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(
                keyboardType = KeyboardType.Number,
                imeAction = ImeAction.Done
            ),
            modifier = Modifier
                .fillMaxWidth()
                .padding(bottom = 16.dp)
        )

        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 8.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text("Gunakan sistem satuan:")
            Button(onClick = { useMetric = !useMetric }) {
                Text(if (useMetric) "Metric (SI)" else "US (USC)")
            }
        }

        Spacer(modifier = Modifier.height(24.dp))

        Text(
            text = "BMI Anda: $bmiText",
            style = MaterialTheme.typography.headlineMedium,
            modifier = Modifier.padding(bottom = 8.dp)
        )
        Text(
            text = "Kategori: $category",
            style = MaterialTheme.typography.titleMedium,
            color = when (category) {
                "Kurus" -> MaterialTheme.colorScheme.primary
                "Normal" -> MaterialTheme.colorScheme.tertiary
                "Gemuk" -> MaterialTheme.colorScheme.secondary
                else -> MaterialTheme.colorScheme.error
            }
        )

        if (imageRes != null) {
            Spacer(modifier = Modifier.height(20.dp))
            Image(
                painter = painterResource(id = imageRes),
                contentDescription = category,
                modifier = Modifier
                    .fillMaxWidth()
                    .height(250.dp)
            )
        }

        Spacer(modifier = Modifier.height(40.dp))
        Divider()
        Text(
            text = "Tentang Pengembang",
            style = MaterialTheme.typography.titleLarge,
            modifier = Modifier.padding(top = 24.dp, bottom = 8.dp)
        )
        Text(
            text = "Dikembangkan oleh Fadzel\nUniversitas Bhayangkara Jakarta Raya\n© 2025",
            style = MaterialTheme.typography.bodyMedium,
            textAlign = TextAlign.Center
        )
    }
}

private fun calculateBMIValue(height: Double, weight: Double, useMetric: Boolean): Double {
    if (height <= 0.0 || weight <= 0.0) return 0.0
    val heightInMeters = if (useMetric) height / 100 else height * 0.0254
    val weightInKg = if (useMetric) weight else weight * 0.453592
    return weightInKg / (heightInMeters * heightInMeters)
}

private fun calculateBMICategory(bmi: Double): String {
    return when {
        bmi == 0.0 -> "-"
        bmi < 18.5 -> "Kurus"
        bmi < 24.9 -> "Normal"
        bmi < 29.9 -> "Gemuk"
        else -> "Obesitas"
    }
}

private fun getCategoryImage(category: String): Int? {
    return when (category) {
        "Kurus" -> R.drawable.kurus
        "Normal" -> R.drawable.normal
        "Gemuk" -> R.drawable.overweight
        "Obesitas" -> R.drawable.obesitas
        else -> null
    }
}

@Preview(showBackground = true)
@Composable
fun PreviewApp() {
    TipTimeTheme {
        BMIApp()
    }
}
