package com.epfl.esl.sportstracker

import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Matrix
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.epfl.esl.sportstracker.ui.theme.SportsTrackerTheme
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.History
import androidx.compose.material.icons.filled.LiveTv
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material3.Button
import androidx.compose.material3.DrawerValue
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ModalDrawerSheet
import androidx.compose.material3.ModalNavigationDrawer
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.NavigationDrawerItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.TextField
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.rememberDrawerState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import coil.compose.AsyncImage
import androidx.navigation.compose.rememberNavController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import com.google.android.gms.tasks.Task
import com.google.android.gms.tasks.Tasks
import com.google.android.gms.wearable.DataClient
import com.google.android.gms.wearable.DataEvent
import com.google.android.gms.wearable.DataEventBuffer
import com.google.android.gms.wearable.DataItem
import com.google.android.gms.wearable.DataMapItem
import com.google.android.gms.wearable.MessageClient
import com.google.android.gms.wearable.PutDataMapRequest
import com.google.android.gms.wearable.PutDataRequest
import com.google.android.gms.wearable.Wearable
import kotlinx.coroutines.launch
import java.io.ByteArrayOutputStream
import java.net.URLEncoder
import java.nio.charset.StandardCharsets


// It's common to create class member named TAG of type String
// Class fields usually at the top of the class in a companion object


class MainActivity : ComponentActivity() {

    private lateinit var dataClient: DataClient
    private var username by mutableStateOf("")
    private var imageUri by mutableStateOf<Uri?>(null)
    private var uriString by mutableStateOf("")
    private var userKey by mutableStateOf("")

    @OptIn(ExperimentalMaterial3Api::class)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        dataClient = Wearable.getDataClient(this)

        setContent {
            SportsTrackerTheme {
                val navController = rememberNavController()
                var shouldShowBottomMenu by remember { mutableStateOf(false) }

                val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed)
                val scope = rememberCoroutineScope()

                Surface {
                    ModalNavigationDrawer(
                        drawerState = drawerState,
                        drawerContent = {
                            ModalDrawerSheet {
                                NavigationDrawerItem(
                                    label = {
                                        Text(text = getString(R.string.about_navigation_drawer_item_text))
                                    },
                                    icon = {
                                        Image(
                                            painter = painterResource(id = R.drawable.esl_icon),
                                            contentDescription = getString(
                                                R.string.esl_icon_content_description
                                            ),
                                            modifier = Modifier.padding(top = 8.dp, bottom = 8.dp)
                                        )
                                    },
                                    selected = false,
                                    onClick = {
                                        scope.launch {
                                            navController.navigate("about")
                                            drawerState.close()
                                        }
                                    },
                                    modifier = Modifier.padding(top = 16.dp)
                                )
                            }

                        }
                    ) {
                        Scaffold(
                            topBar = {
                                TopAppBar(
                                    title = {
                                        Text(text = stringResource(id = R.string.app_name))
                                    },
                                    navigationIcon = {
                                        IconButton(onClick = {
                                            scope.launch {
                                                drawerState.open()
                                            }
                                        }) {
                                            Icon(
                                                imageVector = Icons.Filled.Menu,
                                                contentDescription = getString(
                                                    R.string.menu_icon_content_description
                                                )
                                            )
                                        }
                                    }
                                )
                            },

                            bottomBar = {
                                if (shouldShowBottomMenu) {
                                    NavigationBar {
                                        val navBackStackEntry by navController.currentBackStackEntryAsState()
                                        val currentRoute = navBackStackEntry?.destination?.route

                                        NavigationBarItem(
                                            selected = currentRoute == "myHistory",
                                            onClick = {
                                                navController.navigate("myHistory")
                                            },
                                            icon = {
                                                Icon(
                                                    imageVector = Icons.Filled.History,
                                                    contentDescription = getString(
                                                        R.string.my_history_content_description
                                                    )
                                                )
                                            },
                                            label = { Text(getString(R.string.my_history_navigation_label)) }
                                        )
                                        NavigationBarItem(
                                            selected = currentRoute?.startsWith("newRecording") ?: false,
                                            onClick = {
                                                navController.navigate("newRecording/$username/$uriString")
                                            },
                                            icon = {
                                                Icon(
                                                    imageVector = Icons.Filled.Add,
                                                    contentDescription = getString(
                                                        R.string.new_recording_content_description
                                                    )
                                                )
                                            },
                                            label = {
                                                Text(getString(R.string.new_recording_navigation_label))
                                            }
                                        )
                                        NavigationBarItem(
                                            selected = currentRoute == "exerciseLive",
                                            onClick = {
                                                navController.navigate("exerciseLive")
                                            },
                                            icon = {
                                                Icon(
                                                    imageVector = Icons.Filled.LiveTv,
                                                    contentDescription = getString(
                                                        R.string.exercise_live_content_description
                                                    )
                                                )
                                            },
                                            label = {
                                                Text(getString(R.string.exercise_live_navigation_label))
                                            }
                                        )
                                    }
                                }
                            }
                        )

                        { innerPadding ->
                            NavHost(
                                navController = navController,
                                startDestination = "login",
                                modifier = Modifier.padding(innerPadding)
                            ) {
                                composable("login") {
                                    val context = LocalContext.current
                                    LoginProfileScreen(
                                        onNavigateToNewRecording = { loginInfo ->
                                             username = loginInfo.username
                                             imageUri = loginInfo.imageUri
                                             userKey = loginInfo.userKey

                                            if (imageUri == null || username == "") {
                                                Toast.makeText(
                                                    context, "Pick an image and a username!",
                                                    Toast.LENGTH_SHORT
                                                ).show()
                                            } else {


                                                uriString = URLEncoder.encode(
                                                    imageUri.toString(),
                                                    StandardCharsets.UTF_8.toString()
                                                )

                                                shouldShowBottomMenu = true
                                                navController.navigate("newRecording/$username/${uriString}") {
                                                    popUpTo(navController.graph.id) {
                                                        inclusive = true
                                                    }
                                                }
                                            }
                                        },
                                        dataClient
                                    )
                                }
                                composable("newRecording/{username}/{imageUriString}") { backStackEntry ->
                                    val username = backStackEntry.arguments?.getString("username") ?: ""

                                    val imageUriString =
                                        backStackEntry.arguments?.getString("imageUriString")
                                    val uri = if (!imageUriString.isNullOrEmpty()) {
                                        Uri.parse(imageUriString)
                                    } else {
                                        null
                                    }

                                    NewRecordingScreen(
                                        username,
                                        uri,
                                        userKey,
                                        onLogoutClicked = {
                                            shouldShowBottomMenu = false
                                            navController.navigate("login") {
                                                popUpTo(navController.graph.id) {
                                                    inclusive = true
                                                }
                                            }
                                        }
                                    )
                                }
                                composable("myHistory") {
                                    MyHistoryScreen(username)
                                }
                                composable("exerciseLive") {
                                    ExerciseLiveScreen(
                                        dataClient
                                    )
                                }
                                composable("about") {
                                    AboutScreen()
                                }

                            }
                        }
                    }
                }
            }
        }
    }




}
