/* 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.app.Activity
import android.content.Context
import android.content.ContextWrapper
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.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
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.compose.ui.tooling.preview.WearPreviewDevices
import androidx.wear.compose.ui.tooling.preview.WearPreviewFontScales
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.ScalingLazyColumn
import com.google.android.horologist.compose.layout.ScalingLazyColumnDefaults
import com.google.android.horologist.compose.layout.ScreenScaffold
import com.google.android.horologist.compose.layout.rememberResponsiveColumnState
import com.google.android.horologist.compose.material.Chip
import com.google.android.horologist.compose.material.ListHeaderDefaults.firstItemPadding
import com.google.android.horologist.compose.material.ResponsiveListHeader
import com.google.android.horologist.compose.rotaryinput.rotaryWithScroll
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() {


    override fun onCreate(savedInstanceState: Bundle?) {
        installSplashScreen()

        super.onCreate(savedInstanceState)
        setTheme(android.R.style.Theme_DeviceDefault)
        setContent {
            WearApp()
        }
    }
}

@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 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, startDestination = "speaker") {

            composable("speaker") {
                StartRecordingScreen(
                    context = context,
                    navController = navController,
                    appState = mainState.appState,
                    isPermissionDenied = mainState.isPermissionDenied,
                    onMicClicked = {
                        scope.launch {
                            mainState.onMicClicked()
                        }
                    },
                )
            }

            composable("species_list") {
                SpeciesListView(context = context)
            }

        }

        //        var sdnv = SwipeDismissableNavHost(navController = navController, startDestination = "list") {
        //            composable("speaker") {
        //                StartRecordingScreen(
        //                    context = context,
        //                    appState = mainState.appState,
        //                    isPermissionDenied = mainState.isPermissionDenied,
        //                    onMicClicked = {
        //                        scope.launch {
        //                            mainState.onMicClicked()
        //                        }
        //                    },
        //                )
        //            }


    }
}


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")
}


@OptIn(ExperimentalHorologistApi::class)
@Composable
fun MessageDetail(id: String) {
    val scrollState = rememberScrollState()

    ScreenScaffold(scrollState = scrollState) {
        val padding =
            ScalingLazyColumnDefaults.padding(first = ScalingLazyColumnDefaults.ItemType.Text, last = ScalingLazyColumnDefaults.ItemType.Text)()
        Column(modifier = Modifier
            .fillMaxSize()
            .verticalScroll(scrollState)
            .rotaryWithScroll(scrollState)
            .padding(padding),
            verticalArrangement = Arrangement.Center) {
            Text(text = id, textAlign = TextAlign.Center, modifier = Modifier.fillMaxSize())
        }
    }
}

@OptIn(ExperimentalHorologistApi::class)
@Composable
fun MessageList(onMessageClick: (String) -> Unit) {
    val columnState =
        rememberResponsiveColumnState(contentPadding = ScalingLazyColumnDefaults.padding(first = ScalingLazyColumnDefaults.ItemType.Text,
            last = ScalingLazyColumnDefaults.ItemType.Chip))

    ScreenScaffold(scrollState = columnState) {
        ScalingLazyColumn(columnState = columnState, modifier = Modifier.fillMaxSize()) {
            item {
                ResponsiveListHeader(contentPadding = firstItemPadding()) {
                    Text(text = "Hey hey hey")
                }
            }
            item {
                Chip(label = "Message 1", onClick = { onMessageClick("message1") })
            }
            item {
                Chip(label = "Message 2", onClick = { onMessageClick("message2") })
            }
        }
    }
}


@OptIn(ExperimentalHorologistApi::class)
@Composable
fun MessageList2(onMessageClick: (String) -> Unit) {
    val columnState =
        rememberResponsiveColumnState(contentPadding = ScalingLazyColumnDefaults.padding(first = ScalingLazyColumnDefaults.ItemType.Text,
            last = ScalingLazyColumnDefaults.ItemType.Chip))

    ScreenScaffold(scrollState = columnState) {
        ScalingLazyColumn(columnState = columnState, modifier = Modifier.fillMaxSize()) {
            item {
                ResponsiveListHeader(contentPadding = firstItemPadding()) {
                    Text(text = "Hey hey hey")
                }
            }
            item {
                Chip(label = "Message 3", onClick = { onMessageClick("message3") })
            }
            item {
                Chip(label = "Message 4", onClick = { onMessageClick("message4") })
            }
        }
    }
}

@WearPreviewDevices
@WearPreviewFontScales
@Composable
fun MessageDetailPreview() {
    MessageDetail("test")
}

@WearPreviewDevices
@WearPreviewFontScales
@Composable
fun MessageListPreview() {
    MessageList(onMessageClick = {})
}