package com.example.mathseduc.ui
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.ArrowBack
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
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.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.mathseduc.CreateLobbyActivity
import com.example.mathseduc.MainActivity
import com.example.mathseduc.ServerDetailsActivity
import com.example.mathseduc.controllers.ControllerChapter
import com.example.mathseduc.controllers.ControllerLobby
import com.example.mathseduc.controllers.ControllerUtiliser
import com.example.mathseduc.models.Lobby
import com.example.mathseduc.ui.theme.Colors
import okhttp3.MultipartBody


@Composable
fun MultiPage() {
    val context = LocalContext.current
    var selectedItem by rememberSaveable { mutableStateOf<Lobby?>(null) }

    var lobbyList by rememberSaveable { mutableStateOf(ControllerLobby.getLobbies() ?: emptyList()) }
    var refreshState by rememberSaveable { mutableStateOf(true) }

    DisposableEffect(refreshState) {
        val handler = Handler(Looper.getMainLooper())
        val refreshRunnable = object : Runnable {
            override fun run() {
                lobbyList = ControllerLobby.getLobbies()!!
                selectedItem = null
                handler.postDelayed(this, 3000)
            }
        }

        handler.post(refreshRunnable)

        onDispose {
            handler.removeCallbacks(refreshRunnable)
        }
    }

    Box(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp)
    ) {
        IconButton(
            onClick = {
                val intent = Intent(context, MainActivity::class.java)
                context.startActivity(intent)
            },
            modifier = Modifier
                .align(Alignment.TopStart)
        ) {
            Icon(
                Icons.Rounded.ArrowBack,
                "arrow_back",
                tint = Colors.White
            )
        }

        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(top = 48.dp)
        ) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(vertical = 10.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "Liste des lobbies",
                    color = Colors.White,
                    modifier = Modifier
                        .weight(1f)
                        .padding(start = 20.dp)
                )

                Button(
                    onClick = {
                        val intent = Intent(context, CreateLobbyActivity::class.java)
                        context.startActivity(intent)
                    },
                    shape = RoundedCornerShape(15),
                    modifier = Modifier
                        .weight(1f)
                        .padding(end = 20.dp),
                    colors = ButtonDefaults.buttonColors(Colors.Blue)
                ) {
                    Text(text = "Ajouter un lobby")
                }
            }

            LazyColumn(
                modifier = Modifier
                    .fillMaxSize()
                    .weight(0.85f)
            ) {
                items(lobbyList ?: emptyList()) { lobby ->
                    LobbyItem(lobby, selectedItem == lobby) {
                        selectedItem = it

                        if (ControllerLobby.getNbPlayerInLobby(selectedItem!!.id) < selectedItem!!.nbplayers){
                            val formDataBuilder = MultipartBody.Builder().setType(MultipartBody.FORM)
                            formDataBuilder.addFormDataPart("idplayer", MainActivity.idPlayerConnected.toString())
                            formDataBuilder.addFormDataPart("idlobby", selectedItem!!.id.toString())
                            formDataBuilder.addFormDataPart("playertime", "0")

                            ControllerUtiliser.createUtiliserByIdLobby(formDataBuilder)

                            val intent = Intent(context, ServerDetailsActivity::class.java)
                            intent.putExtra("serverName", selectedItem!!.name)
                            intent.putExtra("lobbyId", selectedItem!!.id)
                            context.startActivity(intent)
                        } else {
                            Toast.makeText(context, "Oh nan, le serveur est déjà plein ! Réessayer plus tard.", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            }
        }
    }
}

@Composable
fun LobbyItem(lobby: Lobby, isSelected: Boolean, onItemClick: (Lobby) -> Unit) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(8.dp)
            .clickable {
                onItemClick(lobby)
            }
            .background(if (isSelected) Colors.Orange else Colors.Grey)
            .padding(16.dp)
            .clip(RoundedCornerShape(8.dp))
    ) {
        Text(
            text = lobby.name,
            fontSize = 18.sp,
            color = Colors.White,
            modifier = Modifier.weight(1f)

        )
        Text(
            text = "${ControllerLobby.getNbPlayerInLobby(lobby.id)}/${lobby.nbplayers}",
            fontSize = 18.sp,
            color = Colors.White,
            modifier = Modifier.weight(1f)
        )
        Text(
            text = ControllerChapter.getChapterNameById(lobby.idchapter).toString(),
            fontSize = 18.sp,
            color = Colors.White,
            modifier = Modifier.weight(1f)
        )
        Text(
            text = lobby.difficulty.toString(),
            fontSize = 18.sp,
            color = Colors.White,
            modifier = Modifier.weight(1f)
        )
    }
}

