package com.example.uitugasakhir

import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.runtime.Composable
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.*
import androidx.compose.ui.res.painterResource
import com.example.app.ui.theme.Inria_Bold
import com.example.app.ui.theme.Inria_Regular
import com.example.app.ui.theme.Inter
import androidx.navigation.NavController
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.ui.platform.LocalContext
import android.content.Context
import android.widget.Toast
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.android.volley.Request
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.graphics.ColorFilter
import okhttp3.ResponseBody
import retrofit2.Call
import org.json.JSONObject
import retrofit2.Callback
import retrofit2.Response
import com.example.uitugasakhir.api.RetrofitClient


@Composable
fun LoginScreen(navController: NavController) {

    var email by remember { mutableStateOf("") }
    var password by remember { mutableStateOf("") }

    var passwordVisible by remember { mutableStateOf(false) }

    val context = LocalContext.current

    fun loginUser(
        email: String,
        password: String,
        context: Context,
        navController: NavController
    ) {
        val url = "http://kopikaosmartsystem.my.id/login.php"

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

            { response ->

                try {
                    val jsonObject = JSONObject(response)

                    if (jsonObject.getString("status") == "success") {

                        val nama = jsonObject.getString("nama")
                        val emailUser = jsonObject.getString("email")

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

                        val editor = sharedPreferences.edit()
                        editor.putString("nama", nama)
                        editor.putString("email", emailUser)
                        editor.apply()

                        Toast.makeText(context, "Login Berhasil", Toast.LENGTH_SHORT).show()

                        navController.navigate("dashboard")

                    } else {
                        Toast.makeText(
                            context,
                            jsonObject.getString("message"),
                            Toast.LENGTH_SHORT
                        ).show()
                    }

                } catch (e: Exception) {
                    Toast.makeText(
                        context,
                        "Response error: ${e.message}",
                        Toast.LENGTH_LONG
                    ).show()
                }
            },

            { error ->
                Toast.makeText(
                    context,
                    "Error: ${error.message}",
                    Toast.LENGTH_LONG
                ).show()
            }

        ) {
            override fun getParams(): MutableMap<String, String> {
                return hashMapOf(
                    "email" to email,
                    "password" to password
                )
            }
        }

        val queue = Volley.newRequestQueue(context)
        queue.add(request)
    }

    Box(
        modifier = Modifier
            .fillMaxSize()
    ) {

        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(160.dp),
            contentAlignment = Alignment.TopCenter
        ) {

            // Card hijau di atas
            Card(
                modifier = Modifier
                    .fillMaxWidth(),
                shape = RoundedCornerShape(0.dp),
                colors = CardDefaults.cardColors(
                    containerColor = Color(0xFF2F6F4E)
                )
            ) {

                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(top = 22.dp),
                    contentAlignment = Alignment.TopCenter
                ) {

                    Text(
                        text = "Halaman Login",
                        fontSize = 16.sp,
                        fontFamily = Inter,
                        fontWeight = FontWeight.Bold,
                        color = Color.White
                    )
                }
            }
        }

        Card(
            modifier = Modifier
                .padding(top = 58.dp)
                .fillMaxSize(),
            shape = RoundedCornerShape(topStart = 24.dp, topEnd = 0.dp),
            colors = CardDefaults.cardColors(
                containerColor = Color(0xFFFFFFFF)
            )
        ) {

            Column(
                modifier = Modifier
                    .fillMaxSize(),
                verticalArrangement = Arrangement.Top,
                horizontalAlignment = Alignment.CenterHorizontally
            ) {

                Image(
                    painter = painterResource(id = R.drawable.kopikakao),
                    contentDescription = "Logo Kopi",
                    Modifier.size(200.dp)
                )

                Text(
                    text = "Selamat Datang!",
                    fontSize = 20.sp,
                    fontFamily = Inria_Bold,
                    fontWeight = FontWeight.Bold,
                    color = Color.Black
                )

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

                Text(
                    text = "Silahkan masukkan email dan password anda",
                    fontSize = 15.sp,
                    fontFamily = Inria_Regular,
                    fontWeight = FontWeight.Medium,
                    color = Color.Black.copy(alpha = 0.7f)
                )

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

                Box(
                    modifier = Modifier
                        .wrapContentHeight()
                        .padding(bottom = 50.dp)
                        .padding(horizontal = 40.dp),
                    contentAlignment = Alignment.TopCenter
                ) {
                    Card(
                        modifier = Modifier
                            .size(width = 276.dp, height = 259.dp),
                        shape = RoundedCornerShape(24.dp),
                        colors = CardDefaults.cardColors(
                            containerColor = Color(0xFF2F6F4E)
                        )
                    ) {
                        Column(
                            modifier = Modifier
                                .fillMaxSize()
                                .padding(20.dp),
                            verticalArrangement = Arrangement.Top,
                            horizontalAlignment = Alignment.CenterHorizontally
                        ) {
                            Card(
                                modifier = Modifier
                                    .size(width = 235.dp, height = 46.dp),
                                shape = RoundedCornerShape(25.dp),
                                colors = CardDefaults.cardColors(
                                    containerColor = Color.White
                                )
                            ) {

                                Row(
                                    verticalAlignment = Alignment.CenterVertically,
                                    modifier = Modifier.fillMaxSize()
                                ) {

                                    Spacer(modifier = Modifier.width(10.dp))

                                    Image(
                                        painter = painterResource(id = R.drawable.mail),
                                        contentDescription = "Email",
                                        modifier = Modifier
                                            .size(20.dp)
                                            .padding(start = 5.dp),
                                        colorFilter = ColorFilter.tint(Color.Gray)
                                    )

                                    Spacer(modifier = Modifier.width(10.dp))

                                    BasicTextField(
                                        value = email,
                                        onValueChange = { email = it },
                                        modifier = Modifier.fillMaxWidth(),
                                        singleLine = true,
                                        decorationBox = { innerTextField ->
                                            if (email.isEmpty()) {
                                                Text(
                                                    "Email",
                                                    color = Color.Gray
                                                )
                                            }
                                            innerTextField()
                                        }
                                    )
                                }
                            }

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

                            Card(
                                modifier = Modifier
                                    .size(width = 235.dp, height = 46.dp),
                                shape = RoundedCornerShape(25.dp),
                                colors = CardDefaults.cardColors(
                                    containerColor = Color.White
                                )
                            ) {

                                Row(
                                    verticalAlignment = Alignment.CenterVertically,
                                    modifier = Modifier.fillMaxSize()
                                ) {

                                    Spacer(modifier = Modifier.width(10.dp))

                                    Image(
                                        painter = painterResource(id = R.drawable.password),
                                        contentDescription = "Password",
                                        modifier = Modifier
                                            .size(20.dp)
                                            .padding(start = 5.dp),
                                        colorFilter = ColorFilter.tint(Color.Gray)

                                    )

                                    Spacer(modifier = Modifier.width(10.dp))

                                    BasicTextField(
                                        value = password,
                                        onValueChange = { password = it },
                                        modifier = Modifier.weight(1f),
                                        singleLine = true,

                                        // 🔒 Enkripsi tampilan password
                                        visualTransformation = if (passwordVisible)
                                            VisualTransformation.None
                                        else
                                            PasswordVisualTransformation(),

                                        decorationBox = { innerTextField ->
                                            if (password.isEmpty()) {
                                                Text(
                                                    "Password",
                                                    color = Color.Gray
                                                )
                                            }
                                            innerTextField()
                                        }
                                    )

                                    // 👁️ Icon show/hide password
                                    IconButton(onClick = {
                                        passwordVisible = !passwordVisible
                                    }) {
                                        Icon(
                                            painter = painterResource(
                                                id = if (passwordVisible)
                                                    R.drawable.ic_eye_open   // mata terbuka
                                                else
                                                    R.drawable.ic_eye_closed // mata tertutup
                                            ),
                                            contentDescription = "Toggle Password",
                                            modifier = Modifier.size(18.dp),
                                            tint = Color.Gray
                                        )
                                    }
                                }
                            }

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

                            Text(
                                text = "Lupa password?",
                                fontSize = 14.sp,
                                fontFamily = Inter,
                                color = Color.White,
                                modifier = Modifier
                                    .offset(x = 70.dp)
                                    .clickable {
                                        navController.navigate("forgot_password")
                                    }
                            )

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

                            Card(
                                onClick = { loginUser(email, password, context, navController) },
                                modifier = Modifier
                                    .size(width = 235.dp, height = 46.dp),
                                shape = RoundedCornerShape(25.dp),
                                colors = CardDefaults.cardColors(
                                    containerColor = Color(0xFF22C55E)
                                )
                            ) {
                                Text(
                                    text = "Masuk",
                                    fontSize = 16.sp,
                                    fontFamily = Inter,
                                    fontWeight = FontWeight.Normal,
                                    color = Color.White,
                                    modifier = Modifier
                                        .padding(top = 13.dp)
                                        .align(Alignment.CenterHorizontally)
                                )
                            }

                        }
                    }
                }

                Row {

                    Text(
                        text = "Belum mempunyai akun?",
                        fontSize = 16.sp,
                        fontFamily = Inter,
                        fontWeight = FontWeight.Normal,
                        color = Color.Black.copy(alpha = 0.7f)
                    )

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

                    Text(
                        text = "Buat akun",
                        fontSize = 16.sp,
                        fontFamily = Inter,
                        fontWeight = FontWeight.Normal,
                        color = Color(0xFF22C55E),
                        modifier = Modifier.clickable {
                            navController.navigate("register")
                        }
                    )
                }
            }
        }
    }
}

@Composable
fun ForgotPasswordScreen(navController: NavController) {

    var email by remember { mutableStateOf("") }
    var message by remember { mutableStateOf("") }
    var isLoading by remember { mutableStateOf(false) }

    fun sendForgotPassword(email: String, callback: (String) -> Unit) {
        RetrofitClient.api.forgotPassword(email.trim())
            .enqueue(object : Callback<ResponseBody> {

                override fun onResponse(
                    call: Call<ResponseBody>,
                    response: Response<ResponseBody>
                ) {
                    callback(response.body()?.string() ?: "No response")
                }

                override fun onFailure(
                    call: Call<ResponseBody>,
                    t: Throwable
                ) {
                    callback("Error: ${t.message}")
                }
            })
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(20.dp),
        verticalArrangement = Arrangement.Center
    ) {

        Text(
            text = "Reset Password",
            fontSize = 24.sp,
            fontWeight = FontWeight.Bold
        )

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

        TextField(
            value = email,
            onValueChange = { email = it },
            placeholder = { Text("Masukkan email") },
            modifier = Modifier.fillMaxWidth()
        )

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

        Button(
            onClick = {
                isLoading = true
                sendForgotPassword(email) {
                    message = it
                    isLoading = false
                }
            },
            modifier = Modifier.fillMaxWidth()
        ) {
            Text("Kirim Link Reset")
        }

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

        if (isLoading) {
            CircularProgressIndicator()
        }

        Text(message)
    }
}

