package de.tsschulz.timeclock

import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.core.view.WindowCompat
import androidx.lifecycle.viewmodel.compose.viewModel
import de.tsschulz.timeclock.ui.TimeClockApp
import de.tsschulz.timeclock.ui.admin.AdminViewModel
import de.tsschulz.timeclock.ui.auth.AuthViewModel
import de.tsschulz.timeclock.ui.booking.BookingViewModel
import de.tsschulz.timeclock.ui.settings.SettingsViewModel
import de.tsschulz.timeclock.ui.theme.TimeClockTheme
import de.tsschulz.timeclock.ui.time.TimeViewModel

class MainActivity : ComponentActivity() {
    @Suppress("DEPRECATION")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.i(TAG, "MainActivity.onCreate")
        window.statusBarColor = Color.rgb(240, 255, 236)
        window.navigationBarColor = Color.WHITE
        try {
            setContent {
                val authViewModel: AuthViewModel = viewModel(factory = AuthViewModel.Factory(application))
                val timeViewModel: TimeViewModel = viewModel(factory = TimeViewModel.Factory(application))
                val bookingViewModel: BookingViewModel = viewModel(factory = BookingViewModel.Factory(application))
                val settingsViewModel: SettingsViewModel = viewModel(factory = SettingsViewModel.Factory(application))
                val adminViewModel: AdminViewModel = viewModel(factory = AdminViewModel.Factory(application))
                TimeClockTheme {
                    TimeClockApp(
                        authViewModel = authViewModel,
                        timeViewModel = timeViewModel,
                        bookingViewModel = bookingViewModel,
                        settingsViewModel = settingsViewModel,
                        adminViewModel = adminViewModel,
                    )
                }
            }
        } catch (e: Throwable) {
            Log.e(TAG, "Failed to create Compose content", e)
            setContentView(
                TextView(this).apply {
                    text = "Die App konnte nicht gestartet werden.\n${e.message.orEmpty()}"
                    setTextColor(Color.BLACK)
                    setBackgroundColor(Color.WHITE)
                    setPadding(32, 32, 32, 32)
                },
            )
        }
        window.decorView.post {
            val controller = WindowCompat.getInsetsController(window, window.decorView)
            controller.isAppearanceLightStatusBars = true
            controller.isAppearanceLightNavigationBars = true
        }
    }

    private companion object {
        const val TAG = "TimeClockStartup"
    }
}
