package io.nexilis.alpha.ui.components

import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.width
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import androidx.navigation.compose.currentBackStackEntryAsState
import io.nexilis.alpha.ui.screen.Screen
import io.nexilis.alpha.ui.screen.screenItems
import io.nexilis.service.data.viewmodels.BuddyViewModel

@Composable
fun Title(navController: NavHostController, navMainController: NavHostController) {
    val navBackStackEntry by navController.currentBackStackEntryAsState()
    val navMainBackStackEntry by navMainController.currentBackStackEntryAsState()
    val buddyViewModel: BuddyViewModel = hiltViewModel()
    var title = ""
    navBackStackEntry?.destination?.route?.let { route ->
        try {
            title = screenItems.first { it.route == route }.title
        } catch (ignored: Exception) {
        }
    }
    navMainBackStackEntry?.destination?.route?.let { route ->
        try {
            title = screenItems.first { it.route == route }.title
        } catch (ignored: Exception) {
        }
    }
    var isChat = false
    var pin = ""
    navMainBackStackEntry?.destination?.route?.let {
        isChat = it.startsWith("${Screen.Chat.route}/")
    }
    navMainBackStackEntry?.arguments?.getString("pin")
        ?.let {
            pin = it
        }
    if (isChat && pin.isNotEmpty()) {
        Row {
            val buddy by buddyViewModel.getBuddy(pin).observeAsState()
            buddy?.let {
                Person(buddy = it)
                Spacer(modifier = Modifier.width(8.dp))
                Text(
                    modifier = Modifier.align(Alignment.CenterVertically),
                    text = "${buddy?.first_name} ${it.last_name}".trim()
                )
            }
        }
    } else {
        Text(text = title)
    }
}