package com.tt.honeyDue.platform

import android.content.Context
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalInspectionMode
import androidx.core.content.FileProvider
import java.io.File

@Composable
actual fun rememberImagePicker(
    onImagesPicked: (List<ImageData>) -> Unit
): () -> Unit {
    val context = LocalContext.current

    val launcher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.PickMultipleVisualMedia(5)
    ) { uris: List<Uri> ->
        if (uris.isNotEmpty()) {
            val images = uris.mapNotNull { uri ->
                try {
                    val inputStream = context.contentResolver.openInputStream(uri)
                    val bytes = inputStream?.readBytes()
                    inputStream?.close()

                    val fileName = getFileNameFromUri(context, uri)

                    if (bytes != null) {
                        ImageData(bytes, fileName)
                    } else {
                        null
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    null
                }
            }
            if (images.isNotEmpty()) {
                onImagesPicked(images)
            }
        }
    }

    return {
        launcher.launch(
            PickVisualMediaRequest(
                ActivityResultContracts.PickVisualMedia.ImageOnly
            )
        )
    }
}

@Composable
actual fun rememberCameraPicker(
    onImageCaptured: (ImageData) -> Unit
): () -> Unit {
    // Compose previews and Roborazzi snapshot tests run without a
    // `FileProvider` resolvable cache path — `getUriForFile` throws
    // `Failed to find configured root...` because the test cache dir
    // isn't registered in the manifest's `file_paths.xml`. The launch
    // callback is never invoked in a preview/snapshot anyway, so
    // returning a no-op keeps the composition clean.
    if (LocalInspectionMode.current) {
        return {}
    }
    val context = LocalContext.current

    // Create a temp file URI for the camera to save to
    val photoUri = remember {
        val photoFile = File(context.cacheDir, "camera_photo_${System.currentTimeMillis()}.jpg")
        FileProvider.getUriForFile(
            context,
            "${context.packageName}.fileprovider",
            photoFile
        )
    }

    val launcher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.TakePicture()
    ) { success: Boolean ->
        if (success) {
            try {
                val inputStream = context.contentResolver.openInputStream(photoUri)
                val bytes = inputStream?.readBytes()
                inputStream?.close()

                if (bytes != null) {
                    val fileName = "camera_${System.currentTimeMillis()}.jpg"
                    onImageCaptured(ImageData(bytes, fileName))
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    return {
        launcher.launch(photoUri)
    }
}

private fun getFileNameFromUri(context: android.content.Context, uri: Uri): String {
    var fileName = "image_${System.currentTimeMillis()}.jpg"

    try {
        context.contentResolver.query(uri, null, null, null, null)?.use { cursor ->
            if (cursor.moveToFirst()) {
                val nameIndex = cursor.getColumnIndex(android.provider.OpenableColumns.DISPLAY_NAME)
                if (nameIndex >= 0) {
                    val name = cursor.getString(nameIndex)
                    if (name != null) {
                        fileName = name
                    }
                }
            }
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }

    return fileName
}
