package com.example.uitugasakhir.pengaturan

import android.content.Context
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.*
import androidx.compose.runtime.*
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.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.app.ui.theme.Inria_Regular
import androidx.compose.ui.text.TextStyle

import com.android.volley.Request
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import android.widget.Toast
import androidx.compose.foundation.text.BasicTextField
import com.example.app.ui.theme.Inria_Bold
import androidx.compose.ui.res.stringResource
import com.example.uitugasakhir.R
import com.example.uitugasakhir.ViewModel.MainViewModel


@Composable
fun AkunCardSection(
    viewModel: MainViewModel
) {

    val context = LocalContext.current

    // SharedPreferences
    val sharedPreferences =
        context.getSharedPreferences("USER_DATA", Context.MODE_PRIVATE)

    var nama by remember {
        mutableStateOf(
            sharedPreferences.getString("nama", "Nama User") ?: ""
        )
    }

    var email by remember {
        mutableStateOf(
            sharedPreferences.getString("email", "email@gmail.com") ?: ""
        )
    }

    // Popup dialog
    var showDialog by remember { mutableStateOf(false) }

    // Input edit
    var editNama by remember { mutableStateOf(nama) }
    var editEmail by remember { mutableStateOf(email) }

    Text(
        text = stringResource(R.string.account),
        fontSize = 15.sp,
        fontFamily = Inria_Regular,
        fontWeight = FontWeight.Medium,
        color = Color.Gray,
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 28.dp)
    )

    Spacer(modifier = Modifier.height(15.dp))

    Card(
        modifier = Modifier
            .padding(horizontal = 25.dp)
            .size(width = 333.dp, height = 100.dp),
        shape = RoundedCornerShape(24.dp),
        colors = CardDefaults.cardColors(
            containerColor = Color(0xFFEDEDED)
        ),
        elevation = CardDefaults.cardElevation(4.dp)
    ) {

        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(16.dp)
        ) {

            // Nama + tombol ubah
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {

                Text(
                    text = nama,
                    fontWeight = FontWeight.Bold
                )

                Text(
                    text = stringResource(R.string.change),
                    color = Color(0xFF2F6F4E),
                    fontSize = 13.sp,
                    modifier = Modifier.clickable {
                        editNama = nama
                        editEmail = email
                        showDialog = true
                    }
                )
            }

            Spacer(modifier = Modifier.height(13.dp))

            HorizontalDivider(
                modifier = Modifier.fillMaxWidth()
            )

            Spacer(modifier = Modifier.height(13.dp))

            Text(
                text = email,
                fontSize = 12.sp,
                color = Color.Gray
            )
        }
    }

    // POPUP EDIT
    if (showDialog) {

        AlertDialog(
            onDismissRequest = {
                showDialog = false
            },

            title = {
                Text("Edit Akun",
                    fontSize = 18.sp,
                    fontFamily = Inria_Bold,
                    fontWeight = FontWeight.Medium,
                    color = Color.Black,
                )
            },

            text = {

                Column {

                    Text(
                        "Ubah Nama",
                        fontSize = 15.sp,
                        fontFamily = Inria_Regular,
                        fontWeight = FontWeight.Medium,
                        color = Color.Gray,
                    )

                    Spacer(modifier = Modifier.height(5.dp))

                    Card(
                        shape = RoundedCornerShape(16.dp),
                        colors = CardDefaults.cardColors(
                            containerColor = Color(0xFF2F6F4E)
                        ),
                        elevation = CardDefaults.cardElevation(4.dp)
                    ) {

                        BasicTextField(
                            value = editNama,
                            onValueChange = {
                                editNama = it
                            },

                            textStyle = TextStyle(
                                color = Color.White.copy(alpha = 0.5f),
                                fontSize = 16.sp
                            ),

                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(16.dp),

                            decorationBox = { innerTextField ->

                                if (editNama.isEmpty()) {

                                    Text(
                                        "Nama",
                                        color = Color.Gray
                                    )
                                }

                                innerTextField()
                            }
                        )
                    }

                    Spacer(modifier = Modifier.height(12.dp))

                    Text(
                        "Ubah Email",
                        fontSize = 15.sp,
                        fontFamily = Inria_Regular,
                        fontWeight = FontWeight.Medium,
                        color = Color.Gray,
                    )

                    Spacer(modifier = Modifier.height(5.dp))

                    Card(
                        shape = RoundedCornerShape(16.dp),
                        colors = CardDefaults.cardColors(
                            containerColor = Color(0xFF2F6F4E)
                        ),
                        elevation = CardDefaults.cardElevation(4.dp),
                    ) {

                        BasicTextField(
                            value = editEmail,
                            onValueChange = {
                                editEmail = it
                            },

                            textStyle = TextStyle(
                                color = Color.White.copy(alpha = 0.5f),
                                fontSize = 16.sp
                            ),

                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(16.dp),

                            decorationBox = { innerTextField ->

                                if (editEmail.isEmpty()) {

                                    Text(
                                        "Email",
                                        color = Color.Gray
                                    )
                                }

                                innerTextField()
                            }
                        )
                    }
                }
            },

            confirmButton = {

                TextButton(
                    onClick = {

                        val url = "http://kopikaosmartsystem.my.id/update_profile.php"

                        val request = object : StringRequest(
                            Request.Method.POST,
                            url,

                            { response ->

                                Toast.makeText(
                                    context,
                                    response,
                                    Toast.LENGTH_SHORT
                                ).show()

                                if (response.contains("berhasil")) {

                                    // Simpan SharedPreferences
                                    val editor = sharedPreferences.edit()

                                    editor.putString("nama", editNama)
                                    editor.putString("email", editEmail)

                                    editor.apply()

                                    // Update tampilan
                                    nama = editNama
                                    email = editEmail

                                    showDialog = false
                                }
                            },

                            { error ->

                                android.widget.Toast.makeText(
                                    context,
                                    "Error: ${error.message}",
                                    android.widget.Toast.LENGTH_SHORT
                                ).show()
                            }

                        ) {

                            override fun getParams(): MutableMap<String, String> {

                                return hashMapOf(

                                    // email lama untuk mencari akun
                                    "email_lama" to email,

                                    // data baru
                                    "nama_baru" to editNama,
                                    "email_baru" to editEmail
                                )
                            }
                        }

                        val queue = Volley.newRequestQueue(context)
                        queue.add(request)
                    }
                ) {
                    Text("Simpan")
                }
            },

            dismissButton = {

                TextButton(
                    onClick = {
                        showDialog = false
                    }
                ) {
                    Text("Batal")
                }
            }
        )
    }
}