package com.epfl.esl.sportstracker

import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.content.Intent
import android.net.Uri
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.DrawableRes
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
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.layout.size
import androidx.compose.material3.Button
import androidx.compose.material3.Divider
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
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.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import coil.compose.AsyncImage
import com.epfl.esl.sportstracker.ui.theme.SportsTrackerTheme

enum class DEVICE(val value: String) {
    SMARTWATCH("Smartwatch"),
    BELT("Belt")
}

@Composable
fun NewRecordingScreen (
    username: String,
    imageUri: Uri?,
    userKey: String,
    device: DEVICE,
    onUpdateDevice: (DEVICE) -> Unit,
    onLogoutClicked: () -> Unit,
    modifier: Modifier = Modifier,
    newRecordingViewModel: NewRecordingViewModel = viewModel()
) {

    val selectedSport by newRecordingViewModel.selectedSport.observeAsState(initial = SPORT.NO_SPORT)
    var isChecked by remember { mutableStateOf(device == DEVICE.SMARTWATCH) }

    val context = LocalContext.current
    if(newRecordingViewModel.bluetoothAdapter==null){
        Toast.makeText(context,"Bluetooth not supported",
            Toast.LENGTH_SHORT).show()
    }

    val resultLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.StartActivityForResult(),
        onResult = { result ->
            if (result.resultCode != Activity.RESULT_OK) {
                Toast.makeText(
                    context, "Bluetooth is not enabled!",
                    Toast.LENGTH_SHORT
                ).show()
                isChecked = false
                onUpdateDevice(DEVICE.SMARTWATCH)
            }
        }
    )

    if (isChecked == true) {
        if (newRecordingViewModel.bluetoothAdapter?.isEnabled == false) {
            val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
            resultLauncher.launch(enableBtIntent)
        }
    }

    Surface(
        modifier = modifier.fillMaxSize(),
        color = MaterialTheme.colorScheme.background
    ) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            modifier = modifier.padding(16.dp)
        ) {

            Row(
                verticalAlignment = Alignment.CenterVertically,
            ) {

                if (imageUri == null) {
                    Image(
                        painter = painterResource(id = R.drawable.user_image),
                        contentDescription = stringResource(
                            R.string.user_image_content_description
                        ),
                        modifier = modifier
                            .weight(1f)
                            .padding(end = 8.dp)
                    )
                } else {
                    AsyncImage(
                        model = imageUri,
                        contentDescription = stringResource(
                            R.string.user_image_content_description
                        ),
                        modifier = modifier
                            .weight(1f)
                            .padding(end = 8.dp)
                    )
                }

                Text(
                    text = "Welcome $username", modifier = modifier
                        .weight(2f)
                        .padding(end = 8.dp)
                )

                Button(onClick = onLogoutClicked) {
                    Text(text = stringResource(id = R.string.log_out_button_text))
                }

            }

            HorizontalDivider(
                color = Color.Black,
                thickness = 2.dp,
                modifier = modifier.padding(top = 16.dp, bottom = 64.dp)
            )


            Image(
                painter = painterResource(id = selectedSport.imageResource),
                contentDescription = stringResource(
                    R.string.selected_activity_content_description
                ),
                modifier.size(128.dp)
            )
            Text(text = selectedSport.activity)

            Row(
                horizontalArrangement = Arrangement.spacedBy(8.dp),
                modifier = modifier.padding(start = 16.dp, top = 32.dp, end = 16.dp)
            ) {
                Image(
                    painter = painterResource(id = R.drawable.running),
                    contentDescription = stringResource(R.string.running_activity_content_description),
                    modifier = modifier.weight(1f).clickable {
                        newRecordingViewModel.updateSelectedSport(SPORT.RUNNING, userKey, device)
                    }
                )
                Image(
                    painter = painterResource(id = R.drawable.cycling),
                    contentDescription = stringResource(R.string.cycling_activity_content_description),
                    modifier = modifier.weight(1f).clickable {
                        newRecordingViewModel.updateSelectedSport(SPORT.CYCLING, userKey, device)
                    }
                )
                Image(
                    painter = painterResource(id = R.drawable.skiing),
                    contentDescription = stringResource(R.string.skiing_activity_content_description),
                    modifier = modifier.weight(1f).clickable {
                        newRecordingViewModel.updateSelectedSport(SPORT.SKIING, userKey, device)
                    }
                )
                Image(
                    painter = painterResource(id = R.drawable.climbing),
                    contentDescription = stringResource(R.string.climbing_activity_content_description),
                    modifier = modifier.weight(1f).clickable {
                        newRecordingViewModel.updateSelectedSport(SPORT.CLIMBING, userKey, device)
                    }
                )
            }

            Row(
                modifier = modifier.padding(top = 32.dp),
                horizontalArrangement = Arrangement.Center,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(text = stringResource(R.string.heart_rate_belt_text))
                Spacer(modifier.padding(end = 8.dp))
                Switch(checked = isChecked, onCheckedChange = { checked ->
                    isChecked = checked
                    if (checked) {
                        onUpdateDevice(DEVICE.BELT)
                    } else {
                        onUpdateDevice(DEVICE.SMARTWATCH)
                    }
                })
            }
        }
    }
}


    @Preview
    @Composable
    fun NewRecordingScreenPreview() {
        SportsTrackerTheme {
            NewRecordingScreen("Test", null, "", DEVICE.SMARTWATCH, {}, {})
        }
    }

