package com.example.mathseduc

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.OnBackPressedCallback
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
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.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
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.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.mathseduc.controllers.ControllerLobby
import com.example.mathseduc.controllers.ControllerPlayer
import com.example.mathseduc.controllers.ControllerUtiliser
import com.example.mathseduc.models.Player
import com.example.mathseduc.ui.theme.Colors
import okhttp3.MultipartBody

class ServerDetailsActivity : ComponentActivity() {

    private var playerList: List<Player> = emptyList()
    private val handler = Handler(Looper.getMainLooper())
    private val refreshInterval: Long = 2000

    private val onBackPressedCallback: OnBackPressedCallback = object : OnBackPressedCallback(true) {
        override fun handleOnBackPressed() {
            myBackPressed()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            ServerDetailPage()
        }

        /*
        onBackPressedDispatcher.addCallback(this, onBackPressedCallback)
        //setContentView(R.layout.activity_server_details)

        val serverName = intent.getStringExtra("serverName")

        val serverNameTextView = findViewById<TextView>(R.id.titleServerDetails)
        serverNameTextView.text = serverName

        val lobbyId = intent.getIntExtra("lobbyId", -1)

        if (savedInstanceState != null) {
            playerList = savedInstanceState?.getParcelableArrayList("playerList") ?: emptyList()
        } else {
            val playerId = ControllerPlayer.getPlayersIdFromLobbyId(lobbyId)
            if (playerId != null) {
                playerList = playerId.mapNotNull { playerId ->
                    ControllerPlayer.getPlayerInfoById(playerId.toString())
                }
            }
        }

        val listViewPlayers = findViewById<ListView>(R.id.listViewPlayers)
        playerAdapter = PlayerAdapter(this, playerList)
        listViewPlayers.adapter = playerAdapter

        handler.postDelayed(refreshRunnable, refreshInterval)

        val btnLaunchQuiz = findViewById<Button>(R.id.btnLaunchQuiz)

        if (ControllerLobby.playerCreatorIdPresentInLobby(MainActivity.idPlayerConnected, lobbyId)) {
            btnLaunchQuiz.visibility = View.VISIBLE
            btnLaunchQuiz.setOnClickListener {

                val formDataBuilder = MultipartBody.Builder().setType(MultipartBody.FORM)
                formDataBuilder.addFormDataPart("launched", "1")

                ControllerLobby.updateLobbyLauched(lobbyId,formDataBuilder)

                val intent = Intent(this, QuizMultiActivity::class.java)
                intent.putExtra("lobbyId", lobbyId)
                startActivity(intent)
            }
        } else {
            btnLaunchQuiz.visibility = View.GONE
        }
        */
    }

    private fun myBackPressed() {
        val lobbyId = intent.getIntExtra("lobbyId", -1)

        ControllerUtiliser.DeleteUtiliserForLobby(MainActivity.idPlayerConnected, lobbyId)

        if (ControllerLobby.playerCreatorIdPresentInLobby(MainActivity.idPlayerConnected, lobbyId)) {
            val idNextPlayerCreator = ControllerUtiliser.getIdNextPlayerInLobby(lobbyId)

            if (idNextPlayerCreator == -1) {
                ControllerLobby.deleteLobby(lobbyId)
            } else {
                val formDataBuilder = MultipartBody.Builder().setType(MultipartBody.FORM)
                formDataBuilder.addFormDataPart("idplayercreator", idNextPlayerCreator.toString())
                ControllerLobby.updateLobbyIdCreatorLobby(lobbyId, formDataBuilder)
            }
        }
        //handler.removeCallbacks(refreshRunnable)
        finish()
    }

    @Composable
    fun ServerDetailPage() {
        val context = LocalContext.current

        val lobbyName = intent.getStringExtra("serverName")
        val lobbyId = intent.getIntExtra("lobbyId",-1)
        var isCreator = false

        var playerListInfos: List<Player> by rememberSaveable { mutableStateOf(emptyList()) }
        var playerList by rememberSaveable { mutableStateOf(ControllerPlayer.getPlayersIdFromLobbyId(lobbyId.toString()) ?: emptyList()) }
        var refreshState by rememberSaveable { mutableStateOf(true) }

        DisposableEffect(refreshState) {
            val handler = Handler(Looper.getMainLooper())
            val refreshRunnable = object : Runnable {
                override fun run() {
                    playerList = ControllerPlayer.getPlayersIdFromLobbyId(lobbyId.toString())!!
                    handler.postDelayed(this, 2000)

                    if (playerList != null) {
                        playerListInfos = playerList.mapNotNull { playerId ->
                            ControllerPlayer.getPlayerInfoById(playerId.toString())
                        }
                    }

                    isCreator = ControllerLobby.playerCreatorIdPresentInLobby(MainActivity.idPlayerConnected, lobbyId!!.toInt())

                    if(ControllerLobby.lobbyIsLaunched(lobbyId!!.toInt())){
                        //val intent = Intent(this@ServerDetailsActivity, QuizMultiActivity::class.java)
                        //intent.putExtra("lobbyId", lobbyId)
                        //startActivity(intent)
                        Toast.makeText(context, "TOTOGOGO", Toast.LENGTH_SHORT).show()
                        return
                    }
                }
            }

            handler.postDelayed(refreshRunnable, 2000)

            onDispose {
                handler.removeCallbacks(refreshRunnable)
            }
        }

        val modifier = Modifier
            .fillMaxSize()
            .padding(16.dp)

        Column(
            modifier = modifier,
            verticalArrangement = Arrangement.Center,
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Text(
                text = lobbyName!!,
                color = Color.White,
                fontWeight = FontWeight.Bold
            )
            LazyColumn(
                modifier = Modifier
                    .fillMaxSize()
                    .weight(0.75f)
            ) {
                items(playerListInfos) { player ->
                    Text(
                        text = player.nickname,
                        fontSize = 18.sp,
                        color = Colors.White,
                        modifier = Modifier.weight(1f)
                    )
                }
            }
            Button(
                onClick = {
                    Toast.makeText(context, "TOTOGOGOCREATOR", Toast.LENGTH_SHORT).show()
                },
                shape = RoundedCornerShape(15),
                colors = ButtonDefaults.buttonColors(Colors.Green),
                modifier = Modifier
                    .fillMaxWidth()
                    .height(48.dp)
            ) {
                Text(
                    text = "LAUNCH",
                    color = Color.White,
                    fontWeight = FontWeight.Bold
                )
            }
        }
    }
}
