package com.aiosman.riderpro.ui.account

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.util.Log
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.Row
import androidx.compose.foundation.layout.Spacer
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.layout.widthIn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicText
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Check
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
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.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.aiosman.riderpro.AppColors
import com.aiosman.riderpro.LocalNavController
import com.aiosman.riderpro.R
import com.aiosman.riderpro.data.AccountService
import com.aiosman.riderpro.data.AccountServiceImpl
import com.aiosman.riderpro.data.UploadImage
import com.aiosman.riderpro.entity.AccountProfileEntity
import com.aiosman.riderpro.ui.comment.NoticeScreenHeader
import com.aiosman.riderpro.ui.composables.CustomAsyncImage
import com.aiosman.riderpro.ui.composables.StatusBarSpacer
import com.aiosman.riderpro.ui.modifiers.noRippleClickable
import com.aiosman.riderpro.ui.post.NewPostViewModel.uriToFile
import kotlinx.coroutines.launch

/**
 * 编辑用户资料界面
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AccountEditScreen2() {
    val accountService: AccountService = AccountServiceImpl()
    var name by remember { mutableStateOf("") }
    var bio by remember { mutableStateOf("") }
    var imageUrl by remember { mutableStateOf<Uri?>(null) }
    var bannerImageUrl by remember { mutableStateOf<Uri?>(null) }
    var profile by remember {
        mutableStateOf<AccountProfileEntity?>(
            null
        )
    }
    val navController = LocalNavController.current
    val scope = rememberCoroutineScope()
    val context = LocalContext.current

    /**
     * 加载用户资料
     */
    suspend fun reloadProfile() {
        accountService.getMyAccountProfile().let {
            profile = it
            name = it.nickName
            bio = it.bio
        }
    }

    fun updateUserProfile() {
        scope.launch {
            val newAvatar = imageUrl?.let {
                val cursor = context.contentResolver.query(it, null, null, null, null)
                var newAvatar: UploadImage? = null
                cursor?.use { cur ->
                    if (cur.moveToFirst()) {
                        val displayName = cur.getString(cur.getColumnIndex("_display_name"))
                        val extension = displayName.substringAfterLast(".")
                        Log.d("NewPost", "File name: $displayName, extension: $extension")
                        // read as file
                        val file = uriToFile(context, it)
                        Log.d("NewPost", "File size: ${file.length()}")
                        newAvatar = UploadImage(file, displayName, it.toString(), extension)
                    }
                }
                newAvatar
            }
            var newBanner = bannerImageUrl?.let {
                val cursor = context.contentResolver.query(it, null, null, null, null)
                var newBanner: UploadImage? = null
                cursor?.use { cur ->
                    if (cur.moveToFirst()) {
                        val displayName = cur.getString(cur.getColumnIndex("_display_name"))
                        val extension = displayName.substringAfterLast(".")
                        Log.d("NewPost", "File name: $displayName, extension: $extension")
                        // read as file
                        val file = uriToFile(context, it)
                        Log.d("NewPost", "File size: ${file.length()}")
                        newBanner = UploadImage(file, displayName, it.toString(), extension)
                    }
                }
                newBanner
            }
            val newName = if (name == profile?.nickName) null else name
            accountService.updateProfile(
                avatar = newAvatar,
                banner = newBanner,
                nickName = newName,
                bio = bio
            )
            reloadProfile()
            navController.popBackStack()
        }
    }

    val pickImageLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.StartActivityForResult()
    ) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            val uri = result.data?.data
            uri?.let {
                imageUrl = it
            }
        }
    }

    LaunchedEffect(Unit) {
        reloadProfile()
    }
    Column(
        modifier = Modifier
            .fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        StatusBarSpacer()
        Box(
            modifier = Modifier.padding(horizontal = 24.dp, vertical = 16.dp)
        ) {
            NoticeScreenHeader(
                title = stringResource(R.string.edit_profile),
                moreIcon = false
            ) {

                Icon(
                    modifier = Modifier
                        .size(24.dp)
                        .noRippleClickable {
                            updateUserProfile()
                        },
                    imageVector = Icons.Default.Check,
                    contentDescription = "保存"
                )
            }
        }
        Spacer(modifier = Modifier.height(32.dp))
        profile?.let {
            Box(
                modifier = Modifier.size(width = 112.dp, height = 112.dp),
                contentAlignment = Alignment.Center
            ) {
                Image(
                    modifier = Modifier.fillMaxSize(),
                    painter = painterResource(id = R.drawable.avatar_bold), contentDescription = ""
                )
                CustomAsyncImage(
                    context,
                    imageUrl?.toString() ?: it.avatar,
                    modifier = Modifier
                        .size(width = 88.dp, height = 88.dp)
                        .clip(
                            RoundedCornerShape(88.dp)
                        ),
                    contentDescription = "",
                    contentScale = ContentScale.Crop
                )
                Box(
                    modifier = Modifier
                        .size(32.dp)
                        .clip(CircleShape)
                        .background(AppColors.mainColor)
                        .align(Alignment.BottomEnd).noRippleClickable {
                            Intent(Intent.ACTION_PICK).apply {
                                type = "image/*"
                                pickImageLauncher.launch(this)
                            }
                        }
                    ,
                    contentAlignment = Alignment.Center
                ) {
                    Icon(
                        Icons.Default.Add,
                        contentDescription = "Add",
                        tint = Color.White,
                    )
                }

            }
            Spacer(modifier = Modifier.height(46.dp))
            Column(
                modifier = Modifier.padding(horizontal = 24.dp).border(
                    width = 1.dp,
                    color = Color(0xFFEBEBEB),
                )
            ) {
                Row(
                    modifier = Modifier.padding(16.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = stringResource(R.string.nickname),
                        modifier = Modifier
                            .widthIn(100.dp),
                        style = TextStyle(
                            fontSize = 16.sp,
                            fontWeight = FontWeight.Bold,
                            color = Color(0xFF333333)
                        )
                    )
                    BasicTextField(
                        maxLines = 1,
                        value = name,
                        onValueChange = {
                            name = it
                        },
                        textStyle = TextStyle(
                            fontSize = 16.sp,
                            fontWeight = FontWeight.Normal
                        ),
                        modifier = Modifier
                            .weight(1f)
                            .padding(start = 16.dp)
                    )
                }
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(1.dp)
                        .padding(horizontal = 16.dp)
                        .background(Color(0xFFEBEBEB))
                )
                Row(
                    modifier = Modifier.padding(16.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = stringResource(R.string.bio),
                        modifier = Modifier
                            .widthIn(100.dp),
                        style = TextStyle(
                            fontSize = 16.sp,
                            fontWeight = FontWeight.Bold,
                            color = Color(0xFF333333)
                        )
                    )
                    BasicTextField(
                        value = bio,
                        onValueChange = {
                            bio = it
                        },
                        textStyle = TextStyle(
                            fontSize = 16.sp,
                            fontWeight = FontWeight.Normal
                        ),
                        modifier = Modifier
                            .weight(1f)
                            .padding(start = 16.dp)
                    )
                }
            }
        }

    }


}