package com.example.godeye

import android.Manifest
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.example.godeye.databinding.ActivityLegacyMainBinding
import com.example.godeye.services.SocketService
import com.example.godeye.utils.Logger

/**
 * LegacyMainActivity - упрощенная версия для Android 9
 * Использует классические Android Views вместо Compose
 * Максимальная совместимость с Android 9
 */
class LegacyMainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityLegacyMainBinding
    private var socketService: SocketService? = null
    private var isServiceBound = false

    // Подключение к SocketService
    private val serviceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            Logger.step("LEGACY_SERVICE_CONNECTED", "SocketService connected to LegacyMainActivity")
            val binder = service as? SocketService.LocalBinder
            socketService = binder?.getService()
            isServiceBound = true
            updateUI()
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            Logger.step("LEGACY_SERVICE_DISCONNECTED", "SocketService disconnected")
            socketService = null
            isServiceBound = false
            updateUI()
        }
    }

    // Обработка разрешений
    private val permissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { permissions ->
        val allGranted = permissions.values.all { it }
        if (allGranted) {
            Logger.step("LEGACY_PERMISSIONS_GRANTED", "All permissions granted")
            updateUI()
        } else {
            Logger.step("LEGACY_PERMISSIONS_DENIED", "Some permissions denied")
            Toast.makeText(this, "Требуются разрешения для работы приложения", Toast.LENGTH_LONG).show()
        }
    }

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

        try {
            Logger.step("LEGACY_ACTIVITY_CREATE", "LegacyMainActivity onCreate for Android 9")

            binding = ActivityLegacyMainBinding.inflate(layoutInflater)
            setContentView(binding.root)

            setupUI()
            checkPermissions()
            startAndBindService()

            Logger.step("LEGACY_ACTIVITY_CREATE_SUCCESS", "LegacyMainActivity created successfully")

        } catch (e: Exception) {
            Logger.error("LEGACY_ACTIVITY_CREATE_ERROR", "Error creating LegacyMainActivity", e)
            Toast.makeText(this, "Ошибка запуска приложения", Toast.LENGTH_LONG).show()
        }
    }

    private fun setupUI() {
        binding.apply {
            // Настройка кнопок
            btnConnect.setOnClickListener {
                connectToServer()
            }

            btnDisconnect.setOnClickListener {
                disconnectFromServer()
            }

            btnCamera.setOnClickListener {
                openCamera()
            }

            btnSettings.setOnClickListener {
                openSettings()
            }

            // Установка начального состояния
            updateUI()
        }
    }

    private fun checkPermissions() {
        val requiredPermissions = arrayOf(
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.INTERNET,
            Manifest.permission.ACCESS_NETWORK_STATE
        )

        val missingPermissions = requiredPermissions.filter { permission ->
            ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED
        }

        if (missingPermissions.isNotEmpty()) {
            Logger.step("LEGACY_REQUEST_PERMISSIONS", "Requesting permissions: ${missingPermissions.joinToString()}")
            permissionLauncher.launch(missingPermissions.toTypedArray())
        } else {
            Logger.step("LEGACY_PERMISSIONS_OK", "All permissions already granted")
        }
    }

    private fun startAndBindService() {
        try {
            val intent = Intent(this, SocketService::class.java)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(intent)
            } else {
                startService(intent)
            }
            bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)
            Logger.step("LEGACY_SERVICE_BIND", "Binding to SocketService")
        } catch (e: Exception) {
            Logger.error("LEGACY_SERVICE_BIND_ERROR", "Error binding to service", e)
        }
    }

    private fun updateUI() {
        binding.apply {
            // Обновление статуса подключения
            if (isServiceBound && socketService != null) {
                tvStatus.text = "✅ Сервис подключен"
                btnConnect.isEnabled = true
                btnCamera.isEnabled = hasAllPermissions()
            } else {
                tvStatus.text = "❌ Сервис не подключен"
                btnConnect.isEnabled = false
                btnCamera.isEnabled = false
            }

            // Обновление информации об устройстве
            val deviceInfo = "📱 ${android.os.Build.MANUFACTURER} ${android.os.Build.MODEL}\n" +
                    "🤖 Android ${android.os.Build.VERSION.RELEASE}"
            tvDeviceInfo.text = deviceInfo

            // Обновление статуса разрешений
            val permissionsStatus = if (hasAllPermissions()) {
                "✅ Разрешения предоставлены"
            } else {
                "⚠️ Требуются разрешения"
            }
            tvPermissions.text = permissionsStatus
        }
    }

    private fun hasAllPermissions(): Boolean {
        val requiredPermissions = arrayOf(
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.INTERNET,
            Manifest.permission.ACCESS_NETWORK_STATE
        )

        return requiredPermissions.all { permission ->
            ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED
        }
    }

    private fun connectToServer() {
        try {
            Logger.step("LEGACY_CONNECT_SERVER", "Attempting to connect to server")
            // Простая заглушка для подключения
            binding.tvConnectionStatus.text = "🔄 Подключение к серверу..."
            Toast.makeText(this, "Подключение к серверу...", Toast.LENGTH_SHORT).show()
        } catch (e: Exception) {
            Logger.error("LEGACY_CONNECT_ERROR", "Error connecting to server", e)
            binding.tvConnectionStatus.text = "❌ Ошибка подключения"
        }
    }

    private fun disconnectFromServer() {
        try {
            Logger.step("LEGACY_DISCONNECT_SERVER", "Disconnecting from server")
            binding.tvConnectionStatus.text = "⚪ Отключено"
            Toast.makeText(this, "Отключено от сервера", Toast.LENGTH_SHORT).show()
        } catch (e: Exception) {
            Logger.error("LEGACY_DISCONNECT_ERROR", "Error disconnecting", e)
        }
    }

    private fun openCamera() {
        if (!hasAllPermissions()) {
            Toast.makeText(this, "Требуются разрешения камеры", Toast.LENGTH_SHORT).show()
            checkPermissions()
            return
        }

        try {
            Logger.step("LEGACY_OPEN_CAMERA", "Opening legacy camera")
            val intent = Intent(this, LegacyCameraActivity::class.java)
            startActivity(intent)
        } catch (e: Exception) {
            Logger.error("LEGACY_CAMERA_ERROR", "Error opening camera", e)
            Toast.makeText(this, "Ошибка открытия камеры", Toast.LENGTH_SHORT).show()
        }
    }

    private fun openSettings() {
        try {
            Logger.step("LEGACY_OPEN_SETTINGS", "Opening settings")
            Toast.makeText(this, "Настройки (в разработке)", Toast.LENGTH_SHORT).show()
        } catch (e: Exception) {
            Logger.error("LEGACY_SETTINGS_ERROR", "Error opening settings", e)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        try {
            if (isServiceBound) {
                unbindService(serviceConnection)
                isServiceBound = false
            }
            Logger.step("LEGACY_ACTIVITY_DESTROY", "LegacyMainActivity destroyed safely")
        } catch (e: Exception) {
            Logger.error("LEGACY_DESTROY_ERROR", "Error destroying activity", e)
        }
    }
}
