package moe.lava.neon.ui.screens

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.safeContentPadding
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
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.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.ViewModel
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.viewModelScope
import co.touchlab.kermit.Logger
import kotlinx.coroutines.launch
import moe.lava.neon.core.repository.AuthRepository
import moe.lava.neon.core.repository.GatewayRepository
import moe.lava.neon.resources.Res
import moe.lava.neon.resources.compose_multiplatform
import org.jetbrains.compose.resources.painterResource
import org.koin.compose.viewmodel.koinViewModel

@Composable
fun Sample(
    navTest: (Boolean) -> Unit,
    onRequestLogout: () -> Unit,
) {
    val viewModel: SampleViewModel = koinViewModel()

    val li = LocalLifecycleOwner.current
    DisposableEffect(li) {
        val observer = LifecycleEventObserver { _, event ->
            when (event) {
                Lifecycle.Event.ON_PAUSE -> {
                    viewModel.disconnect()
                }

                Lifecycle.Event.ON_RESUME -> {
                    viewModel.connect()
                }

                Lifecycle.Event.ON_DESTROY -> {
                    viewModel.disconnect()
                }

                else -> {}
            }
        }
        li.lifecycle.addObserver(observer)
        onDispose {
            li.lifecycle.removeObserver(observer)
        }
    }

    var showContent by remember { mutableStateOf(false) }
    Column(
        modifier = Modifier
            .background(MaterialTheme.colorScheme.primaryContainer)
            .safeContentPadding()
            .fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally,
    ) {
        Button(onClick = { showContent = !showContent }) {
            Text("Click me!")
        }
        Button(onClick = { navTest(true) }) {
            Text("Click me (left)!")
        }
        Button(onClick = { navTest(false) }) {
            Text("Click me (bottom!")
        }
        AnimatedVisibility(showContent) {
            Column(
                modifier = Modifier.fillMaxWidth(),
                horizontalAlignment = Alignment.CenterHorizontally,
            ) {
                Image(painterResource(Res.drawable.compose_multiplatform), null)
                Text("Logged in: ${viewModel.loggedIn}")
            }
        }
        Button(onClick = {
            viewModel.connect()
        }) {
            Text("Connect!")
        }
        Button(onClick = {
            viewModel.disconnect()
        }) {
            Text("Disconnect!")
        }
        Button(onClick = {
            viewModel.logout()
            onRequestLogout()
        }) {
            Text("Logout!")
        }
    }
}

class SampleViewModel(
    private val auth: AuthRepository,
    private val gateway: GatewayRepository,
) : ViewModel() {
    private val logger = Logger.withTag("neon.ui.screens/Sample")
    val loggedIn by auth::loggedIn

    fun connect() {
        viewModelScope.launch {
            val exception = gateway.start().exceptionOrNull()
            if (exception != null) {
                logger.e(exception) { "Failed to connect to gateway: ${exception.stackTraceToString()}" }
            }
        }
    }
    fun disconnect() {
        viewModelScope.launch {
            val exception = gateway.pause().exceptionOrNull()
            if (exception != null) {
                logger.e(exception) { "Failed to disconnect from gateway: ${exception.stackTraceToString()}" }
            }
        }
    }
    fun logout() {
        auth.logout()
    }
}
