package com.example.godeye.ui

import android.os.Bundle
import android.view.View
import androidx.activity.ComponentActivity
import androidx.lifecycle.lifecycleScope
import com.example.godeye.R
import com.example.godeye.managers.ConnectionManager
import com.example.godeye.utils.Logger
import com.example.godeye.utils.PreferenceManager
import kotlinx.coroutines.launch
import android.widget.*
import androidx.core.content.ContextCompat

/**
 * Активность для мониторинга видеопотока без предварительного просмотра
 * Показывает только статус трансляции и счетчик времени записи
 */
class StreamingMonitorActivity : ComponentActivity() {

    private lateinit var connectionManager: ConnectionManager
    private lateinit var preferenceManager: PreferenceManager

    // UI элементы
    private lateinit var statusText: TextView
    private lateinit var recordingTimeText: TextView
    private lateinit var streamingStatusIndicator: View
    private lateinit var startButton: Button
    private lateinit var stopButton: Button
    private lateinit var switchCameraButton: Button
    private lateinit var disconnectButton: Button
    private lateinit var recordingIndicator: ImageView
    private lateinit var connectionStatusText: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_streaming_monitor)

        initializeUI()
        initializeManagers()
        setupEventListeners()
        setupObservers()
    }

    /**
     * Инициализация UI элементов
     */
    private fun initializeUI() {
        statusText = findViewById(R.id.statusText)
        recordingTimeText = findViewById(R.id.recordingTimeText)
        streamingStatusIndicator = findViewById(R.id.streamingStatusIndicator)
        startButton = findViewById(R.id.startButton)
        stopButton = findViewById(R.id.stopButton)
        switchCameraButton = findViewById(R.id.switchCameraButton)
        disconnectButton = findViewById(R.id.disconnectButton)
        recordingIndicator = findViewById(R.id.recordingIndicator)
        connectionStatusText = findViewById(R.id.connectionStatusText)

        // Начальное состояние
        updateUIForStatus(ConnectionManager.StreamingStatus.IDLE)
        recordingTimeText.text = "00:00:00"
        connectionStatusText.text = "Не подключено"
    }

    /**
     * Инициализация менеджеров
     */
    private fun initializeManagers() {
        preferenceManager = PreferenceManager(this)
        connectionManager = ConnectionManager(this, preferenceManager)
    }

    /**
     * Настройка слушателей событий
     */
    private fun setupEventListeners() {
        startButton.setOnClickListener {
            startStreaming()
        }

        stopButton.setOnClickListener {
            stopStreaming()
        }

        switchCameraButton.setOnClickListener {
            switchCamera()
        }

        disconnectButton.setOnClickListener {
            disconnect()
        }
    }

    /**
     * Настройка наблюдателей за состоянием
     */
    private fun setupObservers() {
        // Наблюдение за событиями соединения
        lifecycleScope.launch {
            connectionManager.events.collect { event ->
                when (event) {
                    is ConnectionManager.ConnectionEvent.Connected -> {
                        runOnUiThread {
                            connectionStatusText.text = "Подключено к серверу"
                            connectionStatusText.setTextColor(ContextCompat.getColor(this@StreamingMonitorActivity, R.color.success_green))
                            Toast.makeText(this@StreamingMonitorActivity, "Подключено к серверу", Toast.LENGTH_SHORT).show()
                        }
                    }
                    is ConnectionManager.ConnectionEvent.Disconnected -> {
                        runOnUiThread {
                            connectionStatusText.text = "Отключено от сервера"
                            connectionStatusText.setTextColor(ContextCompat.getColor(this@StreamingMonitorActivity, R.color.error_red))
                        }
                    }
                    is ConnectionManager.ConnectionEvent.Error -> {
                        runOnUiThread {
                            Toast.makeText(this@StreamingMonitorActivity, "Ошибка: ${event.message}", Toast.LENGTH_LONG).show()
                            Logger.error("STREAMING_MONITOR_ERROR", event.message, null)
                        }
                    }
                    is ConnectionManager.ConnectionEvent.StatusUpdated -> {
                        runOnUiThread {
                            statusText.text = event.status
                        }
                    }
                    is ConnectionManager.ConnectionEvent.RecordingTimeUpdated -> {
                        runOnUiThread {
                            recordingTimeText.text = event.duration
                        }
                    }
                    is ConnectionManager.ConnectionEvent.StreamingStarted -> {
                        runOnUiThread {
                            Toast.makeText(this@StreamingMonitorActivity, "Трансляция началась", Toast.LENGTH_SHORT).show()
                        }
                    }
                    is ConnectionManager.ConnectionEvent.StreamingStopped -> {
                        runOnUiThread {
                            Toast.makeText(this@StreamingMonitorActivity, "Трансляция остановлена", Toast.LENGTH_SHORT).show()
                        }
                    }
                    null -> {}
                }
            }
        }

        // Наблюдение за статусом трансляции
        lifecycleScope.launch {
            connectionManager.streamingStatus.collect { status ->
                runOnUiThread {
                    updateUIForStatus(status)
                }
            }
        }

        // Наблюдение за длительностью записи
        lifecycleScope.launch {
            connectionManager.recordingDuration.collect { duration ->
                runOnUiThread {
                    recordingTimeText.text = duration
                }
            }
        }

        // Наблюдение за состоянием записи
        lifecycleScope.launch {
            connectionManager.isRecording.collect { isRecording ->
                runOnUiThread {
                    updateRecordingIndicator(isRecording)
                }
            }
        }
    }

    /**
     * Обновление UI в зависимости от статуса трансляции
     */
    private fun updateUIForStatus(status: ConnectionManager.StreamingStatus) {
        when (status) {
            ConnectionManager.StreamingStatus.IDLE -> {
                streamingStatusIndicator.setBackgroundColor(ContextCompat.getColor(this, R.color.status_idle))
                startButton.isEnabled = true
                stopButton.isEnabled = false
                switchCameraButton.isEnabled = false
                statusText.text = "Готов к трансляции"
            }
            ConnectionManager.StreamingStatus.CONNECTING -> {
                streamingStatusIndicator.setBackgroundColor(ContextCompat.getColor(this, R.color.status_connecting))
                startButton.isEnabled = false
                stopButton.isEnabled = false
                switchCameraButton.isEnabled = false
                statusText.text = "Подключение..."
            }
            ConnectionManager.StreamingStatus.STREAMING -> {
                streamingStatusIndicator.setBackgroundColor(ContextCompat.getColor(this, R.color.status_streaming))
                startButton.isEnabled = false
                stopButton.isEnabled = true
                switchCameraButton.isEnabled = true
                statusText.text = "Трансляция активна"
            }
            ConnectionManager.StreamingStatus.ERROR -> {
                streamingStatusIndicator.setBackgroundColor(ContextCompat.getColor(this, R.color.status_error))
                startButton.isEnabled = true
                stopButton.isEnabled = false
                switchCameraButton.isEnabled = false
                statusText.text = "Ошибка трансляции"
            }
            ConnectionManager.StreamingStatus.STOPPING -> {
                streamingStatusIndicator.setBackgroundColor(ContextCompat.getColor(this, R.color.status_stopping))
                startButton.isEnabled = false
                stopButton.isEnabled = false
                switchCameraButton.isEnabled = false
                statusText.text = "Остановка трансляции..."
            }
        }
    }

    /**
     * Обновление индикатора записи
     */
    private fun updateRecordingIndicator(isRecording: Boolean) {
        if (isRecording) {
            recordingIndicator.setImageResource(R.drawable.ic_recording_active)
            recordingIndicator.visibility = View.VISIBLE
            // Добавляем анимацию мигания
            recordingIndicator.animate()
                .alpha(0f)
                .setDuration(500)
                .withEndAction {
                    recordingIndicator.animate()
                        .alpha(1f)
                        .setDuration(500)
                        .withEndAction {
                            if (connectionManager.isCurrentlyRecording()) {
                                updateRecordingIndicator(true) // Повторяем анимацию
                            }
                        }
                }
        } else {
            recordingIndicator.visibility = View.GONE
            recordingIndicator.clearAnimation()
        }
    }

    /**
     * Начало трансляции
     */
    private fun startStreaming() {
        try {
            Logger.step("MONITOR_START_STREAMING", "Starting streaming from monitor")

            // Здесь можно получить sessionId и operatorId из Intent или диалога
            val sessionId = intent.getStringExtra("sessionId") ?: generateSessionId()
            val operatorId = intent.getStringExtra("operatorId") ?: "operator_1"
            val cameraType = intent.getStringExtra("cameraType") ?: "back"

            connectionManager.startVideoStream(sessionId, operatorId, cameraType)

        } catch (e: Exception) {
            Logger.error("MONITOR_START_ERROR", "Failed to start streaming", e)
            Toast.makeText(this, "Ошибка запуска трансляции: ${e.message}", Toast.LENGTH_LONG).show()
        }
    }

    /**
     * Остановка трансляции
     */
    private fun stopStreaming() {
        try {
            Logger.step("MONITOR_STOP_STREAMING", "Stopping streaming from monitor")
            connectionManager.stopAllStreaming()

        } catch (e: Exception) {
            Logger.error("MONITOR_STOP_ERROR", "Failed to stop streaming", e)
            Toast.makeText(this, "Ошибка остановки трансляции: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * Переключение камеры
     */
    private fun switchCamera() {
        try {
            Logger.step("MONITOR_SWITCH_CAMERA", "Switching camera from monitor")
            connectionManager.switchCamera()

        } catch (e: Exception) {
            Logger.error("MONITOR_SWITCH_ERROR", "Failed to switch camera", e)
            Toast.makeText(this, "Ошибка переключения камеры: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * Отключение от сервера
     */
    private fun disconnect() {
        try {
            Logger.step("MONITOR_DISCONNECT", "Disconnecting from monitor")
            connectionManager.disconnect()

        } catch (e: Exception) {
            Logger.error("MONITOR_DISCONNECT_ERROR", "Failed to disconnect", e)
        }
    }

    /**
     * Генерация ID сессии
     */
    private fun generateSessionId(): String {
        return "session_${System.currentTimeMillis()}"
    }

    override fun onDestroy() {
        super.onDestroy()
        try {
            connectionManager.dispose()
        } catch (e: Exception) {
            Logger.error("MONITOR_DISPOSE_ERROR", "Failed to dispose connection manager", e)
        }
    }

    override fun onPause() {
        super.onPause()
        // Не останавливаем трансляцию при уходе активности в фон
        Logger.step("MONITOR_PAUSE", "Monitor activity paused, streaming continues")
    }

    override fun onResume() {
        super.onResume()
        Logger.step("MONITOR_RESUME", "Monitor activity resumed")

        // Обновляем UI с текущим состоянием
        runOnUiThread {
            updateUIForStatus(connectionManager.getCurrentStreamingStatus())
            recordingTimeText.text = connectionManager.getCurrentRecordingDuration()
            updateRecordingIndicator(connectionManager.isCurrentlyRecording())
        }
    }
}
