package com.jordanbot.installer

import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import com.jordanbot.installer.databinding.ActivityMainBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.URL

class MainActivity : AppCompatActivity() {

    companion object {
        private const val JORDAN_BOT_PACKAGE = "com.jordanbot.autoride"
        private const val APK_URL = "https://lawer.tripz-egypt.com/jordan_bot/jordan_bot.apk"
    }

    private lateinit var binding: ActivityMainBinding
    private var pendingInstallAfterUninstall = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        updateButtonState()

        binding.btnInstall.setOnClickListener {
            if (isAppInstalled()) {
                showUninstallDialog()
            } else {
                startDownloadAndInstall()
            }
        }
    }

    override fun onResume() {
        super.onResume()
        updateButtonState()
        if (pendingInstallAfterUninstall && !isAppInstalled()) {
            pendingInstallAfterUninstall = false
            startDownloadAndInstall()
        }
    }

    private fun updateButtonState() {
        if (isAppInstalled()) {
            binding.btnInstall.text = "تحديث Jordan Bot"
            binding.tvStatus.text = "⚠️ يجب حذف النسخة القديمة أولاً قبل التحديث"
        } else {
            binding.btnInstall.text = "تثبيت Jordan Bot"
            binding.tvStatus.text = "جاهز للتثبيت ✅"
        }
        binding.btnInstall.isEnabled = true
        binding.progressBar.visibility = View.GONE
    }

    private fun isAppInstalled(): Boolean {
        return isPackageInstalled(JORDAN_BOT_PACKAGE) || 
               isPackageInstalled("$JORDAN_BOT_PACKAGE.debug")
    }

    private fun isPackageInstalled(packageName: String): Boolean {
        return try {
            packageManager.getPackageInfo(packageName, 0)
            true
        } catch (e: PackageManager.NameNotFoundException) {
            false
        }
    }

    private fun showUninstallDialog() {
        AlertDialog.Builder(this)
            .setTitle("تحديث Jordan Bot")
            .setMessage("لتثبيت التحديث الجديد، يجب حذف النسخة القديمة أولاً.\n\nلا تقلق، إعداداتك محفوظة في السيرفر وسيتم استعادتها تلقائياً.\n\nهل تريد حذف النسخة القديمة الآن؟")
            .setPositiveButton("نعم، احذف وحدّث") { _, _ ->
                pendingInstallAfterUninstall = true
                val pkg = if (isPackageInstalled(JORDAN_BOT_PACKAGE)) JORDAN_BOT_PACKAGE 
                          else "$JORDAN_BOT_PACKAGE.debug"
                val intent = Intent(Intent.ACTION_DELETE, Uri.parse("package:$pkg"))
                startActivity(intent)
            }
            .setNegativeButton("إلغاء", null)
            .show()
    }

    private fun startDownloadAndInstall() {
        binding.btnInstall.isEnabled = false
        binding.progressBar.visibility = View.VISIBLE
        binding.tvStatus.text = "جاري التحميل... ⏳"

        CoroutineScope(Dispatchers.IO).launch {
            try {
                val downloadedFile = downloadApk(APK_URL)
                
                // Verify the downloaded file is a valid APK (check for PK header)
                val header = downloadedFile.inputStream().use { 
                    val h = ByteArray(4)
                    it.read(h)
                    h
                }
                if (header[0] != 0x50.toByte() || header[1] != 0x4B.toByte()) {
                    throw Exception("الملف المحمّل ليس APK صالح. تأكد من رابط السيرفر.")
                }

                withContext(Dispatchers.Main) {
                    binding.tvStatus.text = "جاري التثبيت... ⏳"
                    launchInstallIntent(downloadedFile)
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    binding.tvStatus.text = "خطأ: ${e.message}"
                    binding.progressBar.visibility = View.GONE
                    binding.btnInstall.isEnabled = true
                }
            }
        }
    }

    private fun launchInstallIntent(apkFile: File) {
        val apkUri: Uri = FileProvider.getUriForFile(
            this,
            "${packageName}.fileprovider",
            apkFile
        )
        
        val installIntent = Intent(Intent.ACTION_VIEW).apply {
            setDataAndType(apkUri, "application/vnd.android.package-archive")
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_GRANT_READ_URI_PERMISSION
        }
        
        startActivity(installIntent)
    }

    private fun downloadApk(urlString: String): File {
        val url = URL(urlString)
        val connection = url.openConnection() as HttpURLConnection
        connection.requestMethod = "GET"
        connection.connectTimeout = 15000
        connection.readTimeout = 60000
        connection.instanceFollowRedirects = true
        connection.connect()

        if (connection.responseCode != HttpURLConnection.HTTP_OK) {
            throw Exception("السيرفر رجع خطأ HTTP ${connection.responseCode}")
        }

        val contentLength = connection.contentLength
        val file = File(cacheDir, "jordan_bot.apk")
        if (file.exists()) file.delete()

        val input: InputStream = connection.inputStream
        val output = FileOutputStream(file)
        
        val buffer = ByteArray(8192)
        var bytesRead: Int
        var totalRead = 0L
        while (input.read(buffer).also { bytesRead = it } != -1) {
            output.write(buffer, 0, bytesRead)
            totalRead += bytesRead
        }
        
        output.flush()
        output.close()
        input.close()
        connection.disconnect()

        // Verify download completeness
        if (contentLength > 0 && totalRead != contentLength.toLong()) {
            file.delete()
            throw Exception("التحميل غير مكتمل: $totalRead / $contentLength bytes")
        }

        if (totalRead < 100_000) {
            file.delete()
            throw Exception("حجم الملف صغير جداً ($totalRead bytes). الرابط غير صحيح.")
        }

        return file
    }
}
