package com.example.livingai.pages.camera

import android.net.Uri
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.exifinterface.media.ExifInterface
import coil.compose.rememberAsyncImagePainter
import com.example.livingai.ui.theme.LivingAITheme
import java.io.InputStream
import kotlin.math.max
import kotlin.math.min

@Composable
fun ViewImageScreen(
    imageUri: String,
    shouldAllowRetake: Boolean,
    showAccept: Boolean,
    showBack: Boolean,
    onRetake: () -> Unit,
    onAccept: () -> Unit,
    onBack: () -> Unit
) {
    val context = LocalContext.current
    var boundingBox by remember { mutableStateOf<String?>(null) }
    var imageWidth by remember { mutableStateOf(0f) }
    var imageHeight by remember { mutableStateOf(0f) }

    LaunchedEffect(imageUri) {
        val uri = Uri.parse(imageUri)
        try {
            context.contentResolver.openInputStream(uri)?.use { inputStream ->
                val exif = ExifInterface(inputStream)
                boundingBox = exif.getAttribute(ExifInterface.TAG_USER_COMMENT)
                
                // Get image dimensions from Exif if possible, or we will rely on loading
                val width = exif.getAttributeInt(ExifInterface.TAG_IMAGE_WIDTH, 0)
                val height = exif.getAttributeInt(ExifInterface.TAG_IMAGE_LENGTH, 0)
                if (width > 0 && height > 0) {
                     imageWidth = width.toFloat()
                     imageHeight = height.toFloat()
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    LivingAITheme {
        Scaffold {
            Box(modifier = Modifier
                .fillMaxSize()
                .padding(it)) {
                Image(
                    painter = rememberAsyncImagePainter(
                        model = Uri.parse(imageUri),
                        onSuccess = { state ->
                            if (imageWidth == 0f || imageHeight == 0f) {
                                imageWidth = state.result.drawable.intrinsicWidth.toFloat()
                                imageHeight = state.result.drawable.intrinsicHeight.toFloat()
                            }
                        }
                    ),
                    contentDescription = "Captured Image",
                    modifier = Modifier.fillMaxSize(),
                    contentScale = ContentScale.Fit,
                    alignment = Alignment.Center
                )
                
                // Draw Bounding Box if available
                if (boundingBox != null && imageWidth > 0 && imageHeight > 0) {
                     Canvas(modifier = Modifier.fillMaxSize()) {
                         val canvasWidth = size.width
                         val canvasHeight = size.height
                         
                         // Parse bounding box string "left,top,right,bottom"
                         val parts = boundingBox!!.split(",")
                         if (parts.size == 4) {
                             val left = parts[0].toFloatOrNull() ?: 0f
                             val top = parts[1].toFloatOrNull() ?: 0f
                             val right = parts[2].toFloatOrNull() ?: 0f
                             val bottom = parts[3].toFloatOrNull() ?: 0f
                             
                             // Calculate scale and offset (CenterInside/Fit logic)
                             // Image composable uses 'Fit' by default which scales to fit within bounds while maintaining aspect ratio
                             val widthRatio = canvasWidth / imageWidth
                             val heightRatio = canvasHeight / imageHeight
                             val scale = min(widthRatio, heightRatio)

                             val displayedWidth = imageWidth * scale
                             val displayedHeight = imageHeight * scale
                             
                             val offsetX = (canvasWidth - displayedWidth) / 2
                             val offsetY = (canvasHeight - displayedHeight) / 2
                             
                             // Transform coordinates
                             val rectLeft = left * scale + offsetX
                             val rectTop = top * scale + offsetY
                             val rectRight = right * scale + offsetX
                             val rectBottom = bottom * scale + offsetY
                             
                             drawRect(
                                 color = Color.Yellow,
                                 topLeft = Offset(rectLeft, rectTop),
                                 size = Size(rectRight - rectLeft, rectBottom - rectTop),
                                 style = Stroke(width = 3.dp.toPx())
                             )
                         }
                     }
                }

                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .align(Alignment.BottomCenter)
                        .padding(16.dp),
                    horizontalArrangement = Arrangement.SpaceEvenly
                ) {
                    if (shouldAllowRetake) {
                        OutlinedButton(onClick = onRetake) {
                            Text("Retake")
                        }
                    }
                    if (showAccept) {
                        Button(onClick = onAccept) {
                            Text("Accept")
                        }
                    } else {
                        Button(onClick = onBack) {
                            Text("Back")
                        }
                    }
                }
            }
        }
    }
}
