package com.crm.chat.ui.chat

import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
import com.crm.chat.databinding.ActivityImageViewerBinding
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

class ImageViewerActivity : AppCompatActivity() {

    private lateinit var binding: ActivityImageViewerBinding
    private var imageUrl: String = ""
    private var fileName: String = ""
    private var serverUrl: String? = null
    private var token: String? = null
    private var apiKey: String? = null
    private var cachedImageFile: java.io.File? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        // Get SharedPreferences
        val prefs = getSharedPreferences("crm_chat_prefs", MODE_PRIVATE)

        // Apply saved theme preference
        val savedThemeMode = prefs.getInt("theme_mode", androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
        androidx.appcompat.app.AppCompatDelegate.setDefaultNightMode(savedThemeMode)

        super.onCreate(savedInstanceState)
        binding = ActivityImageViewerBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // Get data from intent
        imageUrl = intent.getStringExtra(EXTRA_IMAGE_URL) ?: ""
        fileName = intent.getStringExtra(EXTRA_FILE_NAME) ?: "image"

        // Get credentials from SharedPreferences
        serverUrl = prefs.getString("server_url", null)
        token = prefs.getString("auth_token", null)
        apiKey = prefs.getString("api_key", null)

        // Set up custom toolbar
        binding.toolbarTitle.text = fileName

        // Load image
        loadImage()

        // Set up back button
        binding.backButton.setOnClickListener {
            finish()
        }

        // Set up download button in toolbar
        binding.downloadButton.setOnClickListener {
            downloadImage()
        }
    }

    private fun loadImage() {
        if (imageUrl.isNotEmpty()) {
            // Check if we already have the image cached
            if (cachedImageFile != null && cachedImageFile!!.exists()) {
                displayImageFromCache(cachedImageFile!!)
                return
            }

            // Download image to cache first
            downloadImageToCache()
        }
    }

    private fun downloadImageToCache() {
        if (serverUrl.isNullOrEmpty() || apiKey.isNullOrEmpty()) {
            // Fallback: try to load without auth (might work for some servers)
            Glide.with(this)
                .load(imageUrl)
                .into(binding.imageView)
            return
        }

        val repository = com.crm.chat.data.api.ApiClient(serverUrl!!, apiKey!!, token ?: "")
            .let { com.crm.chat.data.repository.ChatRepository(it) }

        GlobalScope.launch {
            try {
                val result = repository.downloadFile(imageUrl, fileName, this@ImageViewerActivity)
                runOnUiThread {
                    result.fold(
                        onSuccess = { cacheFile ->
                            cachedImageFile = cacheFile
                            displayImageFromCache(cacheFile)
                        },
                        onFailure = { exception ->
                            // Fallback: try to load directly (might work for some images)
                            android.util.Log.w("ImageViewer", "Failed to download image to cache: ${exception.message}")
                            Glide.with(this@ImageViewerActivity)
                                .load(imageUrl)
                                .into(binding.imageView)
                        }
                    )
                }
            } catch (e: Exception) {
                runOnUiThread {
                    android.util.Log.e("ImageViewer", "Error downloading image to cache", e)
                    // Fallback: try to load directly
                    Glide.with(this@ImageViewerActivity)
                        .load(imageUrl)
                        .into(binding.imageView)
                }
            }
        }
    }

    private fun displayImageFromCache(cacheFile: java.io.File) {
        Glide.with(this)
            .load(cacheFile)
            .into(binding.imageView)
    }

    private fun downloadImage() {
        // Use cached image if available
        cachedImageFile?.let { cacheFile ->
            if (cacheFile.exists()) {
                showSaveDialog(cacheFile, fileName)
                return
            }
        }

        if (serverUrl.isNullOrEmpty() || token.isNullOrEmpty() || apiKey.isNullOrEmpty()) {
            Toast.makeText(this, "Невозможно скачать: отсутствуют учетные данные", Toast.LENGTH_SHORT).show()
            return
        }

        val repository = com.crm.chat.data.api.ApiClient(serverUrl!!, apiKey!!, token!!)
            .let { com.crm.chat.data.repository.ChatRepository(it) }

        // Show progress
        binding.downloadButton.isEnabled = false
        Toast.makeText(this, "Скачивание $fileName...", Toast.LENGTH_SHORT).show()

        GlobalScope.launch {
            try {
                val result = repository.downloadFile(imageUrl, fileName, this@ImageViewerActivity)
                runOnUiThread {
                    result.fold(
                        onSuccess = { cacheFile ->
                            cachedImageFile = cacheFile // Update cached file reference
                            showSaveDialog(cacheFile, fileName)
                        },
                        onFailure = { exception ->
                            Toast.makeText(
                                this@ImageViewerActivity,
                                "Скачивание не удалось: ${exception.message}",
                                Toast.LENGTH_SHORT
                            ).show()
                            resetDownloadButton()
                        }
                    )
                }
            } catch (e: Exception) {
                runOnUiThread {
                    Toast.makeText(
                        this@ImageViewerActivity,
                        "Ошибка скачивания: ${e.message}",
                        Toast.LENGTH_SHORT
                    ).show()
                    resetDownloadButton()
                }
            }
        }
    }

    private fun showSaveDialog(cacheFile: java.io.File, fileName: String) {
        try {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
                saveFileUsingMediaStore(cacheFile, fileName)
            } else {
                saveFileDirectly(cacheFile, fileName)
            }
        } catch (e: Exception) {
            android.util.Log.e("ImageSave", "Failed to save image", e)
            Toast.makeText(
                this,
                "Не удалось сохранить изображение: ${e.message}",
                Toast.LENGTH_SHORT
            ).show()
            resetDownloadButton()
        }
    }

    @Suppress("DEPRECATION")
    private fun saveFileDirectly(cacheFile: java.io.File, fileName: String) {
        try {
            val downloadsDir = android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DOWNLOADS)
            val destFile = java.io.File(downloadsDir, fileName)

            cacheFile.inputStream().use { input ->
                destFile.outputStream().use { output ->
                    input.copyTo(output)
                }
            }

            android.media.MediaScannerConnection.scanFile(
                this,
                arrayOf(destFile.absolutePath),
                null,
                null
            )

            Toast.makeText(
                this,
                "Изображение сохранено в Загрузки: $fileName",
                Toast.LENGTH_LONG
            ).show()

            resetDownloadButton()
        } catch (e: Exception) {
            throw e
        }
    }

    private fun saveFileUsingMediaStore(cacheFile: java.io.File, fileName: String) {
        try {
            val contentResolver = contentResolver
            val contentValues = android.content.ContentValues().apply {
                put(android.provider.MediaStore.MediaColumns.DISPLAY_NAME, fileName)
                put(android.provider.MediaStore.MediaColumns.MIME_TYPE, "image/*")
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
                    put(android.provider.MediaStore.MediaColumns.RELATIVE_PATH, android.os.Environment.DIRECTORY_DOWNLOADS)
                }
            }

            val collectionUri = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
                android.provider.MediaStore.Downloads.EXTERNAL_CONTENT_URI
            } else {
                android.provider.MediaStore.Files.getContentUri("external")
            }

            val uri = contentResolver.insert(collectionUri, contentValues)

            if (uri != null) {
                contentResolver.openOutputStream(uri)?.use { outputStream ->
                    cacheFile.inputStream().use { inputStream ->
                        inputStream.copyTo(outputStream)
                    }
                }

                Toast.makeText(
                    this,
                    "Изображение сохранено в Загрузки: $fileName",
                    Toast.LENGTH_LONG
                ).show()
            } else {
                throw Exception("Failed to create file in Downloads")
            }

            resetDownloadButton()
        } catch (e: Exception) {
            throw e
        }
    }

    private fun resetDownloadButton() {
        binding.downloadButton.isEnabled = true
    }

    companion object {
        const val EXTRA_IMAGE_URL = "image_url"
        const val EXTRA_FILE_NAME = "file_name"
        const val EXTRA_SERVER_URL = "server_url"
        const val EXTRA_TOKEN = "token"
        const val EXTRA_API_KEY = "api_key"
    }
}
