package com.img.rabbit.utils

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.MediaStore
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

/**
 * 图片选择工具类
 */
object ImagePickerUtils {

    /**
     * 创建相机拍照的Intent
     */
    fun createCameraIntent(context: Context): Pair<Intent, File> {
        val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
        val storageDir = context.externalCacheDir ?: context.cacheDir
        val imageFile = File.createTempFile(
            "JPEG_${timeStamp}_",
            ".jpg",
            storageDir
        )

        val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE).apply {
            putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imageFile))
            addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
        }

        return Pair(intent, imageFile)
    }

    /**
     * 创建相册选择的Intent
     */
    fun createGalleryIntent(): Intent {
        return Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI).apply {
            type = "image/*"
        }
    }

    /**
     * 获取图片的Uri路径
     */
    fun getImageUri(context: Context, file: File): Uri {
        return androidx.core.content.FileProvider.getUriForFile(
            context,
            "${context.packageName}.fileprovider",
            file
        )
    }
}

/**
 * 图片选择结果数据类
 */
data class ImagePickerResult(
    val uri: Uri? = null,
    val filePath: String? = null,
    val error: String? = null
)

/**
 * 可组合函数：创建相机启动器
 */
@Composable
fun rememberCameraLauncher(
    context: Context = LocalContext.current,
    onResult: (ImagePickerResult) -> Unit
) = rememberLauncherForActivityResult(
    ActivityResultContracts.TakePicture()
) { success ->
    if (success) {
        // 这里需要与createCameraIntent配合使用，实际使用时需要保存临时文件路径
        onResult(ImagePickerResult(error = "需要配合createCameraIntent使用"))
    } else {
        onResult(ImagePickerResult(error = "拍照取消或失败"))
    }
}

/**
 * 可组合函数：创建相册启动器（单个图片选择）
 */
@Composable
fun rememberGalleryLauncher(
    onResult: (ImagePickerResult) -> Unit
) = rememberLauncherForActivityResult(
    ActivityResultContracts.PickVisualMedia()
) { uri ->
    if (uri != null) {
        onResult(ImagePickerResult(uri = uri))
    } else {
        onResult(ImagePickerResult(error = "未选择图片"))
    }
}

/**
 * 可组合函数：创建相册启动器（多个图片选择）
 */
@Composable
fun rememberMultipleGalleryLauncher(
    onResult: (List<ImagePickerResult>) -> Unit
) = rememberLauncherForActivityResult(
    ActivityResultContracts.PickMultipleVisualMedia()
) { uris ->
    val results = uris.map { uri ->
        ImagePickerResult(uri = uri)
    }
    onResult(results)
}

/**
 * 可组合函数：创建通用图片选择启动器（支持相机和相册）
 */
@Composable
fun rememberImagePickerLauncher(
    onResult: (ImagePickerResult) -> Unit
) = rememberLauncherForActivityResult(
    ActivityResultContracts.GetContent()
) { uri ->
    if (uri != null) {
        onResult(ImagePickerResult(uri = uri))
    } else {
        onResult(ImagePickerResult(error = "未选择图片"))
    }
}