/* While this template provides a good starting point for using Wear Compose, you can always
 * take a look at https://github.com/android/wear-os-samples/tree/main/ComposeStarter to find the
 * most up to date changes to the libraries and their usages.
 */

package com.birdsounds.identify.presentation

import android.Manifest

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Notification
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.ManagedActivityResultLauncher
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts.RequestPermission
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.scale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.core.app.NotificationCompat
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import androidx.wear.ambient.AmbientLifecycleObserver
import androidx.wear.compose.material.CompactChip
import androidx.wear.compose.material.MaterialTheme
import androidx.wear.compose.material.Text
import androidx.wear.compose.navigation.SwipeDismissableNavHost
import androidx.wear.compose.navigation.composable
import androidx.wear.compose.navigation.rememberSwipeDismissableNavController
import androidx.wear.ongoing.OngoingActivity
import com.birdsounds.identify.presentation.theme.IdentifyTheme
import com.google.android.horologist.annotations.ExperimentalHorologistApi
import com.google.android.horologist.audio.ui.VolumeViewModel
import com.google.android.horologist.compose.layout.ScreenScaffold
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch


val flow_stream = MutableStateFlow<String>("")

val Any.TAG: String
    get() {
        val tag = javaClass.simpleName
        return if (tag.length <= 23) tag else tag.substring(0, 23)
    }

class MainActivity : ComponentActivity() {


     lateinit var ambientObserver:AmbientLifecycleObserver

    override fun onCreate(savedInstanceState: Bundle?) {
        installSplashScreen()
        ambientObserver= AmbientLifecycleObserver(this.findActivity(), ambientCallback)
        super.onCreate(savedInstanceState)

        lifecycle.addObserver(ambientObserver)
        setTheme(android.R.style.Theme_DeviceDefault)
        setContent {
            WearApp()
        }

    }
}

@SuppressLint("ForegroundServiceType")
@OptIn(ExperimentalHorologistApi::class)
@Composable
@Preview
fun WearApp() {
    IdentifyTheme {
        lateinit var requestPermissionLauncher: ManagedActivityResultLauncher<String, Boolean>
        val context = LocalContext.current
        val activity = context.findActivity()
        val scope = rememberCoroutineScope()


        val touchIntent =
            PendingIntent.getActivity(
                context,
                0,
                Intent(context, MainActivity::class.java),
                PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
            )


        val notificationBuilder =
            NotificationCompat.Builder(context, "Identify Watch App")
                .setOngoing(true)
                .setSmallIcon(com.birdsounds.identify.R.mipmap.ic_launcher)


        val ongoingActivity =
            OngoingActivity.Builder(
                context, 4, notificationBuilder
            ).setTouchIntent(touchIntent)
                .setStaticIcon(
                    com.birdsounds.identify.R.mipmap.ic_launcher)
                .build()


        ongoingActivity.apply(context)
        val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.notify(
            4,
            notificationBuilder.build()
        )

        val notification: Notification = NotificationCompat.Builder(
            context, "Identify Watch App"
        )
            .setContentTitle("Always On App")
            .setContentText("Running in foreground")
            .setSmallIcon(com.birdsounds.identify.R.mipmap.ic_launcher)
            .setPriority(NotificationCompat.PRIORITY_LOW)
            .build()



        val volumeViewModel: VolumeViewModel = viewModel(factory = VolumeViewModel.Factory)

        val mainState = remember(activity) {
            MainState(activity = activity, requestPermission = {
                requestPermissionLauncher.launch(Manifest.permission.RECORD_AUDIO)
            })
        }

        requestPermissionLauncher = rememberLauncherForActivityResult(RequestPermission()) {
            scope.launch {
                mainState.permissionResultReturned()
            }
        }

        val navController: NavHostController = rememberSwipeDismissableNavController()
        mainState.setNavController(navController);
        SwipeDismissableNavHost(
            navController = navController,
            userSwipeEnabled = true,
            startDestination = "speaker"
        ) {
            composable("species_list") {
                ScreenScaffold {
                    SpeciesListView(context = context, appState = mainState.appState, birdHeardState = mainState.birdHeardState, mainState = mainState )
                }
            }

            composable("speaker") {
                ScreenScaffold {
                    Column(
                        verticalArrangement = Arrangement.Center,
                        horizontalAlignment = Alignment.CenterHorizontally,
                        modifier = Modifier
                            .fillMaxSize()
                            .align(Alignment.Center)
                    ) {
                        Row() {
                            val interactionSource = remember { MutableInteractionSource() }
                            val isPressed by interactionSource.collectIsPressedAsState()

                            // Define the animation for the scale
                            val scale by animateFloatAsState(
                                targetValue = if (isPressed) 2.0f else 1.0f
                            )

                            CompactChip(
                                onClick = {
                                    vibrate(
                                        context,
                                        250
                                    );navController.navigate("species_list")
                                },
                                enabled = true,
                                modifier = Modifier.scale(scale),
                                interactionSource = interactionSource,
                                contentPadding = PaddingValues(5.dp, 1.dp, 5.dp, 1.dp),
                                shape = MaterialTheme.shapes.small,
                                label = {
                                    Text(text = "Show List")
                                },

                                )


                        }
                        Row() {
                            val interactionSource = remember { MutableInteractionSource() }
                            val isPressed by interactionSource.collectIsPressedAsState()

                            // Define the animation for the scale
                            val scale by animateFloatAsState(
                                targetValue = if (isPressed) 2.0f else 1.0f
                            )
                            CompactChip(
                                onClick = {
                                    vibrate(context, 250);
                                    scope.launch {
                                        mainState.onMicClicked()
                                    }
                                },
                                modifier = Modifier.scale(scale),
                                interactionSource = interactionSource,
                                enabled = true,
                                contentPadding = PaddingValues(5.dp, 1.dp, 5.dp, 1.dp),
                                shape = MaterialTheme.shapes.small,
                                label = {
                                    Text(text = if (mainState.appState == AppState.Recording) "Stop Recording" else "Start Recording")
                                })
                        }
                        Row() {
                            val interactionSource = remember { MutableInteractionSource() }
                            val isPressed by interactionSource.collectIsPressedAsState()

                            // Define the animation for the scale
                            val scale by animateFloatAsState(
                                targetValue = if (isPressed) 2.0f else 1.0f
                            )
                            CompactChip(
                                onClick = {
                                    vibrate(context, 250);
                                    species_list_show.clear();
                                    internal_list.clear();
                                },
                                enabled = true,
                                modifier = Modifier.scale(scale),
                                interactionSource = interactionSource,
                                contentPadding = PaddingValues(5.dp, 1.dp, 5.dp, 1.dp),
                                shape = MaterialTheme.shapes.small,
                                label = {
                                    Text(text = "Clear List")
                                },

                                )


                        }
                    }
                }
            }


        }

    }
}


tailrec fun Context.findActivity(): Activity = when (this) {
    is Activity -> this
    is ContextWrapper -> baseContext.findActivity()
    else -> throw IllegalStateException("findActivity should be called in the context of an Activity")
}

