// Dirson Ali Wardana
// 202310715XXX
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.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
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.graphics.Brush
import androidx.compose.ui.graphics.Color
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.unit.dp
import androidx.compose.ui.unit.sp

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        enableEdgeToEdge()
        super.onCreate(savedInstanceState)
        setContent {
            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) {
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(
                Brush.verticalGradient(
                    listOf(Color(0xFFDDEEC7), Color(0xFFB6D7A8))
                )
            ),
        contentAlignment = Alignment.Center
    ) {
        Column(horizontalAlignment = Alignment.CenterHorizontally) {

            // 🏞️ Logo / ilustrasi Ghibli style
            Image(
                painter = painterResource(id = R.drawable.bmilogo),
                contentDescription = "App Logo",
                modifier = Modifier
                    .size(160.dp)
                    .padding(bottom = 24.dp)
            )

            Text(
                text = "BMI CALCULATOR",
                fontSize = 22.sp,
                color = Color(0xFF375E3B),
                textAlign = TextAlign.Center
            )

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

            Button(
                onClick = onStart,
                colors = ButtonDefaults.buttonColors(containerColor = Color(0xFF9C7B4B)),
                shape = RoundedCornerShape(16.dp),
                modifier = Modifier
                    .fillMaxWidth(0.6f)
                    .height(50.dp)
            ) {
                Text("Mulai Sekarang", color = Color.White, fontSize = 18.sp)
            }
        }
    }
}

@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)

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(
                Brush.verticalGradient(
                    listOf(Color(0xFFEAF4D3), Color(0xFFD2E3B8))
                )
            )
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(24.dp)
                .verticalScroll(rememberScrollState()),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Text(
                text = "Kalkulator BMI",
                style = MaterialTheme.typography.headlineLarge,
                color = Color(0xFF375E3B),
                modifier = Modifier.padding(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(),
                colors = OutlinedTextFieldDefaults.colors(
                    focusedBorderColor = Color(0xFF375E3B),
                    focusedLabelColor = Color(0xFF375E3B)
                )
            )

            Spacer(modifier = Modifier.height(12.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(),
                colors = OutlinedTextFieldDefaults.colors(
                    focusedBorderColor = Color(0xFF375E3B),
                    focusedLabelColor = Color(0xFF375E3B)
                )
            )

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

            Button(
                onClick = { useMetric = !useMetric },
                colors = ButtonDefaults.buttonColors(containerColor = Color(0xFF9C7B4B)),
                shape = RoundedCornerShape(12.dp)
            ) {
                Text(if (useMetric) "Gunakan US (USC)" else "Gunakan Metric (SI)", color = Color.White)
            }

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

            Card(
                colors = CardDefaults.cardColors(containerColor = Color(0xFFFDF6E3)),
                shape = RoundedCornerShape(20.dp),
                modifier = Modifier.fillMaxWidth()
            ) {
                Column(
                    modifier = Modifier.padding(24.dp),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Text(
                        text = "BMI Anda: $bmiText",
                        style = MaterialTheme.typography.headlineMedium,
                        color = Color(0xFF375E3B)
                    )
                    Text(
                        text = "Kategori: $category",
                        style = MaterialTheme.typography.titleMedium,
                        color = Color(0xFF8B4513)
                    )

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

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

            Text(
                text = "Dibuat oleh Dirson Ali Wardana\nUniversitas Bhayangkara Jakarta Raya\n© 2025",
                style = MaterialTheme.typography.bodyMedium,
                textAlign = TextAlign.Center,
                color = Color(0xFF375E3B)
            )
        }
    }
}

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.kurusg
        "Normal" -> R.drawable.normalg
        "Gemuk" -> R.drawable.overweightg
        "Obesitas" -> R.drawable.obesitasg
        else -> null
    }
}
