package com.iscs.bozzys.ui.pages.profile.face

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
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.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
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.lifecycle.viewmodel.compose.viewModel
import coil.compose.AsyncImage
import com.iscs.bozzys.R
import com.iscs.bozzys.api.UserCharacteristic
import com.iscs.bozzys.ui.common.Empty
import com.iscs.bozzys.ui.common.PageBase
import com.iscs.bozzys.ui.common.Title
import com.iscs.bozzys.ui.dialog.TipsDialog
import com.iscs.bozzys.ui.pages.compose.CardBox
import com.iscs.bozzys.ui.pages.vm.VMFace
import com.iscs.bozzys.utils.DateUtil.getShowDateOrTime
import com.iscs.bozzys.utils.SystemUtil.uriToFile
import java.io.File

/**
 * 打开人脸录入界面
 */
fun Context.openPageFace(userId: Int, username: String) {
    startActivity(Intent(this, PageFace::class.java).apply {
        putExtra("userId", userId)
        putExtra("username", username)
    })
}

/**
 * 人脸数据页面
 */
class PageFace : PageBase() {


    // 跳转到选择照片页面
    private val imageLauncher = registerForActivityResult(ActivityResultContracts.GetContent()) { uri ->
        uriToFile(uri)?.let { onImagePickerFinish(it) }
    }

    // 照片选择成功回调
    private var onImagePickerFinish: (file: File) -> Unit = {}

    /**
     * 执行照片选择
     */
    private fun pickerImage(done: (file: File) -> Unit) {
        this.onImagePickerFinish = done
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
            if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1001)
                return
            }
        }
        imageLauncher.launch("image/*")
    }

    /**
     * 获取用户id
     */
    private fun getUserId(): Int {
        return intent.getIntExtra("userId", 0)
    }

    /**
     * 从页面携带数据中获取用户名称
     */
    private fun getUsername(): String {
        return intent.getStringExtra("username") ?: ""
    }

    @Composable
    override fun GetViews(pv: PaddingValues) {
        val vm: VMFace = viewModel()
        val state by vm.state.collectAsState()
        LaunchedEffect(Unit) {
            vm.loading.initLoading()
            vm.toast.initToast()
            vm.init(getUserId(), getUsername())
        }
        Column {
            Title(pv, "人脸", rightShow = true, rightIcon = R.drawable.add, rightClick = {
                pickerImage { vm.uploadUserFace(it) }
            })
            Box(contentAlignment = Alignment.Center) {
                Column(
                    modifier = Modifier
                        .padding(horizontal = 16.dp, vertical = 8.dp)
                        .fillMaxSize()
                        .verticalScroll(rememberScrollState())
                ) {
                    state.faceList.forEach { FaceListItem(vm, it) }
                }
                if (state.faceList.isEmpty() && !state.isFirstLoad) Empty(tips = "暂无人脸数据")
            }
            TipsDialog(show = state.showDeleteTips, title = "提示", content = "确定要删除当前人脸数据吗？", onCancel = {
                vm.hideDeleteTips()
            }, onConfirm = {
                vm.hideDeleteTips()
                vm.deleteFaceData()
            })
        }

    }

    /**
     * 人脸特征数据
     */
    @Composable
    fun FaceListItem(vm: VMFace, face: UserCharacteristic) {
        CardBox(modifier = Modifier.padding(vertical = 8.dp)) {
            Row(
                modifier = Modifier
                    .height(80.dp)
                    .fillMaxWidth()
                    .padding(horizontal = 12.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                AsyncImage(
                    model = face.imageUrl,
                    contentDescription = null,
                    placeholder = painterResource(R.mipmap.logo),
                    modifier = Modifier
                        .size(60.dp)
                        .clip(RoundedCornerShape(50)),
                    contentScale = ContentScale.Crop
                )
                Column(
                    modifier = Modifier
                        .padding(horizontal = 6.dp)
                        .weight(1f)
                ) {
                    Text("录入时间", fontSize = 16.sp, fontWeight = FontWeight.Bold)
                    Text(face.createTime.getShowDateOrTime(), fontSize = 14.sp, color = MaterialTheme.colorScheme.surfaceTint.copy(alpha = 0.5f))
                }
                Icon(
                    painter = painterResource(R.drawable.delete_all), contentDescription = null, modifier = Modifier
                        .size(36.dp)
                        .clip(RoundedCornerShape(50))
                        .clickable { vm.showDeleteTips(face) }
                        .padding(5.dp),
                    tint = Color(0xFFFA666C)
                )
            }
        }
    }
}