package com.img.rabbit.pages.screen.make

import android.net.Uri
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import coil3.compose.AsyncImage
import com.img.rabbit.R
import com.img.rabbit.components.DrawingBoardFormatPicker
import com.img.rabbit.config.CommonData.formats
import com.img.rabbit.pages.toolbar.TitleBar
import com.img.rabbit.utils.ExportFormat
import com.img.rabbit.utils.ImageUtils.convertToGallery
import com.img.rabbit.utils.ImageUtils.getBitmapFromUri
import kotlinx.coroutines.launch

@Composable
fun FormatScreen(navController: NavController) {
    val context = LocalContext.current
    val coroutineScope = rememberCoroutineScope()

    // 当前选中的格式
    val selectedFormat = remember { mutableStateOf(formats.getOrNull(0)) }

    // 人物图片选择相关状态
    val selectedImageUri = remember { mutableStateOf<Uri?>(null) }

    // 图片选择启动器
    val imagePickerLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.GetContent()
    ) { uri ->
        uri?.let {
            selectedImageUri.value = it
        }
    }

    Scaffold{
        LaunchedEffect(Unit) {
            imagePickerLauncher.launch("image/*")
        }
        Column(
            modifier = Modifier.fillMaxSize().background(Color(0xFFF4F4F4))
        ) {
            TitleBar(navController = navController, paddingValues = it, title = "", showSave = true) {
                val bitmap = selectedImageUri.value?.let {uri->
                     getBitmapFromUri(context, uri)
                }
                if(bitmap != null){
                    // 保存图片
                    coroutineScope.launch {
                        // 转换图片格式
                        val format = when(selectedFormat.value?.title){
                            ExportFormat.PNG.name -> ExportFormat.PNG
                            ExportFormat.GIF.name -> ExportFormat.GIF
                            ExportFormat.SVG.name -> ExportFormat.SVG
                            else -> ExportFormat.JPG
                        }
                        convertToGallery(
                            context = context,
                            sourceBitmap = bitmap,
                            format = format,
                            onSubmitResult = { fileName, isSuccess ->
                                if (isSuccess) {
                                    Toast.makeText(context, "已保存至 $fileName", Toast.LENGTH_SHORT).show()
                                } else {
                                    Toast.makeText(context, "保存失败", Toast.LENGTH_SHORT).show()
                                }
                            }
                        )
                    }
                }

            }

            Box(
                modifier = Modifier
                    .fillMaxSize()
            ){
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(start = 38.dp, end = 38.dp, top = 14.dp)
                        .aspectRatio(300f / 420f)
                        .background(Color(0xFFFFFFFF))
                        .border(1.dp, Color(0xFFD8D8D8))
                ){
                    if (selectedImageUri.value != null) {
                        // 显示选中的原始图片
                        AsyncImage(
                            model = selectedImageUri.value,
                            contentDescription = "选中的图片",
                            modifier = Modifier.fillMaxSize(),
                            contentScale = androidx.compose.ui.layout.ContentScale.Fit
                        )
                    } else {
                        // 空状态
                        Column(
                            modifier = Modifier.align(Alignment.Center)
                        ) {
                            Image(
                                painter = painterResource(id = R.mipmap.ic_image_empty_pld),
                                contentDescription = "空图",
                            )
                            Text(
                                text = "去相册选一张美照吧~",
                                color = Color(0xFFD8D8D8),
                                fontSize = 12.sp,
                                modifier = Modifier.align(Alignment.CenterHorizontally)
                            )
                        }
                    }
                }

                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .align(Alignment.BottomCenter)
                ) {
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(horizontal = 14.dp, vertical = 9.dp)
                            .background(Color(0xFFAAAAAA), shape = RoundedCornerShape(7.dp))
                            .align(Alignment.CenterHorizontally)
                    ){

                        Text(
                            text = "请选择图片导出格式，用于适配各种平台",
                            color = Color(0xFFFFFFFF),
                            fontSize = 14.sp,
                            fontWeight = FontWeight.Normal,
                            modifier = Modifier.align(Alignment.Center)
                        )
                    }

                    Box(Modifier.height(14.dp))

                    //底部画板
                    DrawingBoardFormatPicker(
                        //格式列表数据
                        formats = formats,
                        //选中
                        selectedFormat = selectedFormat,
                    )
                }
            }
        }
    }
}