package com.atridad.ascently.ui.components

import android.graphics.BitmapFactory
import android.graphics.Matrix
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.exifinterface.media.ExifInterface
import com.atridad.ascently.utils.ImageUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File

@Composable
fun OrientationAwareImage(
    imagePath: String,
    modifier: Modifier = Modifier,
    contentDescription: String? = null,
    contentScale: ContentScale = ContentScale.Fit,
) {
    val context = LocalContext.current
    var imageBitmap by
        remember(imagePath) { mutableStateOf<androidx.compose.ui.graphics.ImageBitmap?>(null) }
    var isLoading by remember(imagePath) { mutableStateOf(true) }

    LaunchedEffect(imagePath) {
        isLoading = true
        val bitmap =
            withContext(Dispatchers.IO) {
                try {
                    val imageFile = ImageUtils.getImageFile(context, imagePath)
                    if (!imageFile.exists()) return@withContext null

                    val originalBitmap =
                        BitmapFactory.decodeFile(imageFile.absolutePath)
                            ?: return@withContext null
                    val correctedBitmap = correctImageOrientation(imageFile, originalBitmap)
                    correctedBitmap.asImageBitmap()
                } catch (_: Exception) {
                    null
                }
            }
        imageBitmap = bitmap
        isLoading = false
    }

    Box(modifier = modifier) {
        if (isLoading) {
            CircularProgressIndicator(modifier = Modifier.size(32.dp).align(Alignment.Center))
        } else {
            imageBitmap?.let { bitmap ->
                Image(
                    bitmap = bitmap,
                    contentDescription = contentDescription,
                    modifier = Modifier.fillMaxSize(),
                    contentScale = contentScale,
                )
            }
        }
    }
}

private fun correctImageOrientation(
    imageFile: File,
    bitmap: android.graphics.Bitmap,
): android.graphics.Bitmap {
    return try {
        val exif = ExifInterface(imageFile.absolutePath)
        val orientation =
            exif.getAttributeInt(
                ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_NORMAL,
            )

        val matrix = Matrix()
        var needsTransform = false

        when (orientation) {
            ExifInterface.ORIENTATION_ROTATE_90 -> {
                matrix.postRotate(90f)
                needsTransform = true
            }
            ExifInterface.ORIENTATION_ROTATE_180 -> {
                matrix.postRotate(180f)
                needsTransform = true
            }
            ExifInterface.ORIENTATION_ROTATE_270 -> {
                matrix.postRotate(270f)
                needsTransform = true
            }
            ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> {
                matrix.postScale(-1f, 1f)
                needsTransform = true
            }
            ExifInterface.ORIENTATION_FLIP_VERTICAL -> {
                matrix.postScale(1f, -1f)
                needsTransform = true
            }
            ExifInterface.ORIENTATION_TRANSPOSE -> {
                matrix.postRotate(90f)
                matrix.postScale(-1f, 1f)
                needsTransform = true
            }
            ExifInterface.ORIENTATION_TRANSVERSE -> {
                matrix.postRotate(-90f)
                matrix.postScale(-1f, 1f)
                needsTransform = true
            }
            else -> {
                // Default case - no transformation needed
            }
        }

        if (!needsTransform) {
            bitmap
        } else {
            val rotatedBitmap =
                android.graphics.Bitmap.createBitmap(
                    bitmap,
                    0,
                    0,
                    bitmap.width,
                    bitmap.height,
                    matrix,
                    true,
                )
            if (rotatedBitmap != bitmap) {
                bitmap.recycle()
            }
            rotatedBitmap
        }
    } catch (_: Exception) {
        bitmap
    }
}
