package com.example.godeye

import android.Manifest
import android.content.pm.PackageManager
import android.hardware.Camera
import android.os.Bundle
import android.view.SurfaceHolder
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.example.godeye.databinding.ActivityLegacyCameraBinding
import com.example.godeye.utils.Logger
import java.io.IOException

/**
 * LegacyCameraActivity - камера для Android 9
 * Использует устаревший Camera API для максимальной совместимости
 */
@Suppress("DEPRECATION")
class LegacyCameraActivity : AppCompatActivity(), SurfaceHolder.Callback {

    private lateinit var binding: ActivityLegacyCameraBinding
    private var camera: Camera? = null
    private var surfaceHolder: SurfaceHolder? = null
    private var isPreviewRunning = false

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

        try {
            Logger.step("LEGACY_CAMERA_CREATE", "Creating LegacyCameraActivity for Android 9")

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

            setupUI()
            setupCamera()

            Logger.step("LEGACY_CAMERA_CREATE_SUCCESS", "LegacyCameraActivity created successfully")

        } catch (e: Exception) {
            Logger.error("LEGACY_CAMERA_CREATE_ERROR", "Error creating LegacyCameraActivity", e)
            Toast.makeText(this, "Ошибка инициализации камеры", Toast.LENGTH_LONG).show()
            finish()
        }
    }

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

            btnCapture.setOnClickListener {
                capturePhoto()
            }

            btnSwitchCamera.setOnClickListener {
                switchCamera()
            }

            // Настройка информации
            tvCameraInfo.text = "📹 Legacy Camera для Android 9"
        }
    }

    private fun setupCamera() {
        try {
            if (!checkCameraPermission()) {
                Toast.makeText(this, "Нет разрешения на использование камеры", Toast.LENGTH_LONG).show()
                finish()
                return
            }

            // Настройка SurfaceView для предварительного просмотра
            surfaceHolder = binding.surfaceViewCamera.holder
            surfaceHolder?.addCallback(this)
            surfaceHolder?.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS)

            Logger.step("LEGACY_CAMERA_SETUP", "Camera surface setup completed")

        } catch (e: Exception) {
            Logger.error("LEGACY_CAMERA_SETUP_ERROR", "Error setting up camera", e)
            Toast.makeText(this, "Ошибка настройки камеры", Toast.LENGTH_SHORT).show()
        }
    }

    private fun checkCameraPermission(): Boolean {
        return ContextCompat.checkSelfPermission(
            this,
            Manifest.permission.CAMERA
        ) == PackageManager.PERMISSION_GRANTED
    }

    override fun surfaceCreated(holder: SurfaceHolder) {
        try {
            Logger.step("LEGACY_SURFACE_CREATED", "Camera surface created")
            startCamera()
        } catch (e: Exception) {
            Logger.error("LEGACY_SURFACE_CREATE_ERROR", "Error on surface created", e)
        }
    }

    override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
        try {
            Logger.step("LEGACY_SURFACE_CHANGED", "Camera surface changed: ${width}x${height}")

            if (isPreviewRunning) {
                camera?.stopPreview()
            }

            startCameraPreview()

        } catch (e: Exception) {
            Logger.error("LEGACY_SURFACE_CHANGE_ERROR", "Error on surface changed", e)
        }
    }

    override fun surfaceDestroyed(holder: SurfaceHolder) {
        try {
            Logger.step("LEGACY_SURFACE_DESTROYED", "Camera surface destroyed")
            stopCamera()
        } catch (e: Exception) {
            Logger.error("LEGACY_SURFACE_DESTROY_ERROR", "Error on surface destroyed", e)
        }
    }

    private fun startCamera() {
        try {
            if (camera == null) {
                camera = Camera.open()
                Logger.step("LEGACY_CAMERA_OPENED", "Legacy camera opened successfully")
            }
        } catch (e: Exception) {
            Logger.error("LEGACY_CAMERA_OPEN_ERROR", "Error opening camera", e)
            Toast.makeText(this, "Не удалось открыть камеру", Toast.LENGTH_SHORT).show()
        }
    }

    private fun startCameraPreview() {
        try {
            camera?.let { cam ->
                cam.setPreviewDisplay(surfaceHolder)

                // Настройка параметров камеры для Android 9
                val parameters = cam.parameters
                val supportedSizes = parameters.supportedPreviewSizes

                // Выбираем подходящий размер превью
                supportedSizes?.let { sizes ->
                    val optimalSize = getOptimalPreviewSize(sizes, binding.surfaceViewCamera.width, binding.surfaceViewCamera.height)
                    optimalSize?.let {
                        parameters.setPreviewSize(it.width, it.height)
                        cam.parameters = parameters
                    }
                }

                cam.startPreview()
                isPreviewRunning = true

                // Обновляем UI
                binding.tvStatus.text = "✅ Камера активна"

                Logger.step("LEGACY_CAMERA_PREVIEW_STARTED", "Camera preview started successfully")
            }
        } catch (e: IOException) {
            Logger.error("LEGACY_CAMERA_PREVIEW_ERROR", "Error starting camera preview", e)
            Toast.makeText(this, "Ошибка запуска предварительного просмотра", Toast.LENGTH_SHORT).show()
        }
    }

    private fun getOptimalPreviewSize(sizes: List<Camera.Size>, width: Int, height: Int): Camera.Size? {
        val targetRatio = width.toDouble() / height
        var optimalSize: Camera.Size? = null
        var minDiff = Double.MAX_VALUE

        for (size in sizes) {
            val ratio = size.width.toDouble() / size.height
            if (Math.abs(ratio - targetRatio) > 0.1) continue

            if (Math.abs(size.height - height) < minDiff) {
                optimalSize = size
                minDiff = Math.abs(size.height - height).toDouble()
            }
        }

        if (optimalSize == null) {
            minDiff = Double.MAX_VALUE
            for (size in sizes) {
                if (Math.abs(size.height - height) < minDiff) {
                    optimalSize = size
                    minDiff = Math.abs(size.height - height).toDouble()
                }
            }
        }

        return optimalSize
    }

    private fun stopCamera() {
        try {
            camera?.let { cam ->
                if (isPreviewRunning) {
                    cam.stopPreview()
                    isPreviewRunning = false
                }
                cam.release()
                camera = null

                binding.tvStatus.text = "⚪ Камера остановлена"

                Logger.step("LEGACY_CAMERA_STOPPED", "Camera stopped and released")
            }
        } catch (e: Exception) {
            Logger.error("LEGACY_CAMERA_STOP_ERROR", "Error stopping camera", e)
        }
    }

    private fun capturePhoto() {
        try {
            if (!isPreviewRunning) {
                Toast.makeText(this, "Камера не активна", Toast.LENGTH_SHORT).show()
                return
            }

            Logger.step("LEGACY_CAMERA_CAPTURE", "Capturing photo with legacy camera")

            // Простая реализация захвата фото
            camera?.takePicture(null, null) { data, _ ->
                try {
                    Logger.step("LEGACY_PHOTO_CAPTURED", "Photo captured, size: ${data.size} bytes")
                    Toast.makeText(this@LegacyCameraActivity, "Фото сделано!", Toast.LENGTH_SHORT).show()

                    // Здесь можно добавить сохранение фото или отправку на сервер

                } catch (e: Exception) {
                    Logger.error("LEGACY_PHOTO_SAVE_ERROR", "Error processing captured photo", e)
                }
            }

        } catch (e: Exception) {
            Logger.error("LEGACY_CAMERA_CAPTURE_ERROR", "Error capturing photo", e)
            Toast.makeText(this, "Ошибка съемки фото", Toast.LENGTH_SHORT).show()
        }
    }

    private fun switchCamera() {
        try {
            Logger.step("LEGACY_CAMERA_SWITCH", "Attempting to switch camera")

            // Для Android 9 просто показываем сообщение
            Toast.makeText(this, "Переключение камеры (в разработке)", Toast.LENGTH_SHORT).show()

        } catch (e: Exception) {
            Logger.error("LEGACY_CAMERA_SWITCH_ERROR", "Error switching camera", e)
        }
    }

    override fun onPause() {
        super.onPause()
        try {
            if (isPreviewRunning) {
                camera?.stopPreview()
                isPreviewRunning = false
            }
        } catch (e: Exception) {
            Logger.error("LEGACY_CAMERA_PAUSE_ERROR", "Error pausing camera", e)
        }
    }

    override fun onResume() {
        super.onResume()
        try {
            if (camera != null && !isPreviewRunning) {
                startCameraPreview()
            }
        } catch (e: Exception) {
            Logger.error("LEGACY_CAMERA_RESUME_ERROR", "Error resuming camera", e)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        try {
            stopCamera()
            Logger.step("LEGACY_CAMERA_DESTROY", "LegacyCameraActivity destroyed safely")
        } catch (e: Exception) {
            Logger.error("LEGACY_CAMERA_DESTROY_ERROR", "Error destroying camera activity", e)
        }
    }
}
