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.layout.Column
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.material.icons.Icons
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.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.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import com.aiosman.riderpro.LocalNavController
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.composables.CustomAsyncImage
import com.aiosman.riderpro.ui.modifiers.noRippleClickable
import com.aiosman.riderpro.ui.post.NewPostViewModel.uriToFile
import kotlinx.coroutines.launch

/**
 * 编辑用户资料界面
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AccountEditScreen() {
    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
            }
        }
    }
    val pickBannerImageLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.StartActivityForResult()
    ) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            val uri = result.data?.data
            uri?.let {
                bannerImageUrl = uri
            }
        }
    }

    LaunchedEffect(Unit) {
        reloadProfile()
    }
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("Edit") },
            )
        },
        floatingActionButton = {
            FloatingActionButton(
                onClick = {
                    updateUserProfile()
                }
            ) {
                Icon(
                    imageVector = Icons.Default.Check,
                    contentDescription = "Save"
                )
            }
        }
    ) { padding ->
        profile?.let {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(padding)
                    .padding(horizontal = 24.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                CustomAsyncImage(
                    context,
                    if (imageUrl != null) {
                        imageUrl.toString()
                    } else {
                        it.avatar
                    },
                    contentDescription = null,
                    modifier = Modifier
                        .size(100.dp)
                        .noRippleClickable {
                            Intent(Intent.ACTION_PICK).apply {
                                type = "image/*"
                                pickImageLauncher.launch(this)
                            }
                        },
                    contentScale = ContentScale.Crop
                )
                Spacer(modifier = Modifier.size(16.dp))
                CustomAsyncImage(
                    context,
                    if (bannerImageUrl != null) {
                        bannerImageUrl.toString()
                    } else {
                        it.banner!!
                    },
                    contentDescription = null,
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(200.dp)
                        .noRippleClickable {
                            Intent(Intent.ACTION_PICK).apply {
                                type = "image/*"
                                pickBannerImageLauncher.launch(this)
                            }
                        },
                    contentScale = ContentScale.Crop
                )
                Spacer(modifier = Modifier.size(16.dp))
                TextField(
                    value = name,
                    onValueChange = {
                        name = it
                    },
                    label = {
                        Text("Name")
                    },
                    modifier = Modifier.fillMaxWidth()
                )
                Spacer(modifier = Modifier.size(16.dp))
                TextField(
                    value = bio,
                    onValueChange = {
                        bio = it
                    },
                    label = {
                        Text("Bio")
                    },
                    modifier = Modifier.fillMaxWidth()
                )
            }
        }
    }


}