package com.example.godeye

import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Surface
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.core.content.ContextCompat
import com.example.godeye.managers.PermissionManager
import com.example.godeye.ui.screens.MainScreen
import com.example.godeye.ui.theme.GodEyeTheme
import com.example.godeye.ui.viewmodels.MainViewModel
import com.example.godeye.utils.Logger
import kotlinx.coroutines.launch

class MainActivity : ComponentActivity() {

    private val viewModel: MainViewModel by viewModels()
    private lateinit var permissionManager: PermissionManager

    // Launcher для запроса разрешений
    private val permissionsLauncher = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { permissions ->
        val allGranted = permissions.values.all { it }
        if (allGranted) {
            Logger.d("All permissions granted")
            viewModel.startServices() // Запуск сервисов после получения разрешений
        } else {
            Logger.w("Some permissions were denied")
            val deniedPermissions = permissions.filterValues { !it }.keys
            Logger.w("Denied permissions: ${deniedPermissions.joinToString(", ")}")
        }

        // Логируем статус разрешений
        permissionManager.logPermissionsStatus()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        Logger.d("MainActivity created")
        permissionManager = PermissionManager(this)

        // Проверяем разрешения при запуске
        checkAndRequestPermissions()
        if (permissionManager.hasAllRequiredPermissions()) {
            viewModel.startServices() // Запуск сервисов если разрешения уже есть
        }

        setContent {
            GodEyeTheme {
                val snackbarHostState = remember { SnackbarHostState() }
                val coroutineScope = rememberCoroutineScope()

                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    Scaffold(
                        snackbarHost = { SnackbarHost(snackbarHostState) }
                    ) { paddingValues ->
                        MainScreen(
                            viewModel = viewModel,
                            onRequestPermissions = {
                                requestMissingPermissions()
                            },
                            onShowError = { message ->
                                coroutineScope.launch {
                                    snackbarHostState.showSnackbar(message)
                                }
                            }
                        )
                    }
                }
            }
        }
    }

    /**
     * Проверить и запросить недостающие разрешения
     */
    private fun checkAndRequestPermissions() {
        if (!permissionManager.hasAllRequiredPermissions()) {
            Logger.d("Some permissions are missing, requesting...")
            requestMissingPermissions()
        } else {
            Logger.d("All required permissions are granted")
        }
    }

    /**
     * Запросить недостающие разрешения
     */
    private fun requestMissingPermissions() {
        val missingPermissions = permissionManager.getMissingPermissions()
        if (missingPermissions.isNotEmpty()) {
            Logger.d("Requesting permissions: ${missingPermissions.joinToString(", ")}")
            permissionsLauncher.launch(missingPermissions.toTypedArray())
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        Logger.d("MainActivity destroyed")
    }
}