package com.example.godeye

import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.lifecycle.lifecycleScope
import com.example.godeye.managers.ConnectionManager
import com.example.godeye.managers.AutoApprovalManager
import com.example.godeye.models.*
import com.example.godeye.services.ConnectionService
import com.example.godeye.ui.components.*
import com.example.godeye.ui.screens.MainScreen
import com.example.godeye.ui.screens.SettingsScreen
import com.example.godeye.ui.theme.GodEyeTheme
import com.example.godeye.utils.PermissionHelper
import com.example.godeye.utils.PreferenceManager
import kotlinx.coroutines.launch

class MainActivity : ComponentActivity() {

    // Убираем SignalingManager - используем только ConnectionManager + AutoApprovalManager
    // private lateinit var signalingManager: SignalingManager
    private lateinit var connectionManager: ConnectionManager
    private lateinit var autoApprovalManager: AutoApprovalManager
    private lateinit var permissionHelper: PermissionHelper
    private lateinit var preferenceManager: PreferenceManager

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

        // Инициализируем менеджеры (БЕЗ SignalingManager)
        preferenceManager = PreferenceManager(this)
        // signalingManager = SignalingManager(this)  // УБИРАЕМ
        connectionManager = ConnectionManager(this, preferenceManager)
        autoApprovalManager = AutoApprovalManager(this, preferenceManager, connectionManager)
        permissionHelper = PermissionHelper(this)

        setContent {
            GodEyeTheme {
                AppContent()
            }
        }

        // Проверяем разрешения при запуске
        checkPermissionsAndStart()

        // Запускаем фоновый сервис
        startConnectionService()
    }

    @Composable
    private fun AppContent() {
        var currentScreen by remember { mutableStateOf(Screen.Main) }

        when (currentScreen) {
            Screen.Main -> {
                MainScreen(
                    connectionManager = connectionManager,
                    autoApprovalManager = autoApprovalManager,
                    preferenceManager = preferenceManager,
                    permissionHelper = permissionHelper,
                    onOpenSettings = { currentScreen = Screen.Settings }
                )
            }
            Screen.Settings -> {
                SettingsScreen(
                    preferenceManager = preferenceManager,
                    permissionHelper = permissionHelper,
                    onNavigateBack = { currentScreen = Screen.Main }
                )
            }
        }
    }

    private enum class Screen {
        Main, Settings
    }

    private fun checkPermissionsAndStart() {
        if (permissionHelper.hasAllPermissions()) {
            // Все разрешения уже есть, можно работать
            Log.d("MainActivity", "All permissions granted")
            startApplication()
        } else {
            // Запрашиваем разрешения
            Log.d("MainActivity", "Requesting permissions")
            permissionHelper.requestPermissions { granted ->
                if (granted) {
                    Log.d("MainActivity", "Permissions granted, starting application")
                    startApplication()
                } else {
                    Log.w("MainActivity", "Some permissions denied")
                }
            }
        }
    }

    private fun startApplication() {
        // Инициализируем автоматическое подключение если включено
        if (preferenceManager.getAutoConnect()) {
            connectionManager.connect()
        }

        Log.d("MainActivity", "Application started with settings: ${preferenceManager.getAllSettings()}")
    }

    /**
     * Запуск фонового сервиса для поддержания подключения
     */
    private fun startConnectionService() {
        val serviceIntent = Intent(this, ConnectionService::class.java).apply {
            action = ConnectionService.ACTION_START
        }

        // Проверяем версию Android для совместимости
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            startForegroundService(serviceIntent)
        } else {
            startService(serviceIntent)
        }

        Log.d("MainActivity", "Connection service started")
    }

    /**
     * Остановка фонового сервиса
     */
    private fun stopConnectionService() {
        val serviceIntent = Intent(this, ConnectionService::class.java).apply {
            action = ConnectionService.ACTION_STOP
        }
        stopService(serviceIntent)
        Log.d("MainActivity", "Connection service stopped")
    }

    override fun onResume() {
        super.onResume()
        Log.d("MainActivity", "Activity resumed")

        // Проверяем настройки и автоподключение
        if (permissionHelper.hasAllPermissions() && preferenceManager.getAutoConnect()) {
            connectionManager.connect()
        }
    }

    override fun onPause() {
        super.onPause()
        Log.d("MainActivity", "Activity paused - service continues in background")
    }

    override fun onDestroy() {
        super.onDestroy()

        // Очищаем ресурсы Activity, но оставляем сервис работать
        connectionManager.cleanup()
        autoApprovalManager.cleanup()

        // Останавливаем сервис только если приложение действительно закрывается
        if (isFinishing) {
            stopConnectionService()
        }

        Log.d("MainActivity", "MainActivity destroyed, resources cleaned up")
    }
}
