package com.rosetta.messenger.ui.utils

import android.content.Context
import android.graphics.Color
import android.view.View
import android.view.Window
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat

data class SystemBarsState(
    val statusBarColor: Int,
    val navigationBarColor: Int,
    val isLightStatusBars: Boolean,
    val isLightNavigationBars: Boolean
)

object SystemBarsStyleUtils {

    fun capture(window: Window?, view: View?): SystemBarsState? {
        if (window == null || view == null) return null
        val insetsController = WindowCompat.getInsetsController(window, view)
        return SystemBarsState(
            statusBarColor = window.statusBarColor,
            navigationBarColor = window.navigationBarColor,
            isLightStatusBars = insetsController.isAppearanceLightStatusBars,
            isLightNavigationBars = insetsController.isAppearanceLightNavigationBars
        )
    }

    fun applyFullscreenDark(window: Window?, view: View?) {
        if (window == null || view == null) return
        val insetsController = WindowCompat.getInsetsController(window, view)
        window.statusBarColor = Color.BLACK
        window.navigationBarColor = Color.BLACK
        insetsController.isAppearanceLightStatusBars = false
        insetsController.isAppearanceLightNavigationBars = false
    }

    fun applyChatStatusBar(window: Window?, view: View?, isDarkTheme: Boolean) {
        if (window == null || view == null) return
        val insetsController = WindowCompat.getInsetsController(window, view)
        window.statusBarColor = Color.TRANSPARENT
        insetsController.isAppearanceLightStatusBars = false
    }

    fun restoreNavigationBar(window: Window?, view: View?, context: Context, state: SystemBarsState?) {
        if (window == null || view == null) return
        val insetsController = WindowCompat.getInsetsController(window, view)

        insetsController.show(WindowInsetsCompat.Type.navigationBars())
        if (state != null) {
            window.navigationBarColor = state.navigationBarColor
            insetsController.isAppearanceLightNavigationBars = state.isLightNavigationBars
        }
    }

    fun restoreChatAfterFullscreen(
        window: Window?,
        view: View?,
        context: Context,
        isDarkTheme: Boolean,
        state: SystemBarsState?
    ) {
        applyChatStatusBar(window, view, isDarkTheme)
        restoreNavigationBar(window, view, context, state)
    }
}
