package com.jordanbot.autoride

import android.Manifest
import android.accessibilityservice.AccessibilityServiceInfo
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.view.View
import android.view.accessibility.AccessibilityManager
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import com.jordanbot.autoride.service.BotForegroundService
import com.jordanbot.autoride.service.OverlayService
import com.jordanbot.autoride.api.ApiClient
import com.jordanbot.autoride.utils.DeviceUtils

import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch
import com.jordanbot.autoride.subscription.SubscriptionManager

import androidx.appcompat.app.AppCompatDelegate
import com.jordanbot.autoride.filter.FilterEngine

class MainActivity : AppCompatActivity() {

    private lateinit var tvStatus: TextView
    private lateinit var btnStart: Button
    private lateinit var btnStop: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // Apply Theme
        val prefs = getSharedPreferences("ThemePrefs", MODE_PRIVATE)
        val isDark = prefs.getBoolean("dark_mode", true)
        if (isDark) {
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
        } else {
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
        }

        setContentView(R.layout.activity_main)

        // Load Settings
        FilterEngine.init(this)

        // Set App Signature for API Security
        ApiClient.appSignature = DeviceUtils.getAppSignatureSHA256(this)

        // Load cached subscription data
        SubscriptionManager.loadLocalCache(this)

        // Check subscription with server
        lifecycleScope.launch {
            SubscriptionManager.checkSubscription(this@MainActivity)
        }

        tvStatus = findViewById(R.id.tv_status)
        btnStart = findViewById(R.id.btn_start)
        btnStop = findViewById(R.id.btn_stop)

        findViewById<Button>(R.id.btn_subscriptions).setOnClickListener {
            startActivity(Intent(this, SubscriptionActivity::class.java))
        }

        findViewById<Button>(R.id.btn_settings).setOnClickListener {
            startActivity(Intent(this, SettingsActivity::class.java))
        }

        findViewById<Button>(R.id.btn_notification).setOnClickListener {
            startActivity(Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS))
        }

        findViewById<Button>(R.id.btn_accessibility).setOnClickListener {
            startActivity(Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS))
        }

        findViewById<Button>(R.id.btn_overlay).setOnClickListener {
            if (!Settings.canDrawOverlays(this)) {
                startActivity(Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION))
            } else {
                Toast.makeText(this, "هذه الصلاحية مفعلة بالفعل", Toast.LENGTH_SHORT).show()
            }
        }

        // Location and Notification Permission Request
        findViewById<Button>(R.id.btn_location).setOnClickListener {
            requestPermissions()
        }

        btnStart.setOnClickListener {
            if (checkAllPermissions()) {
                startBot()
            } else {
                Toast.makeText(this, "الرجاء تفعيل جميع الصلاحيات أولاً", Toast.LENGTH_LONG).show()
            }
        }

        btnStop.setOnClickListener {
            stopBot()
        }

        findViewById<Button>(R.id.btn_test_connection).setOnClickListener {
            lifecycleScope.launch {
                Toast.makeText(this@MainActivity, "جاري فحص الاتصال بالسيرفر...", Toast.LENGTH_SHORT).show()
                val success = SubscriptionManager.checkSubscription(this@MainActivity)
                if (success) {
                    android.app.AlertDialog.Builder(this@MainActivity)
                        .setTitle("✅ الاتصال سليم")
                        .setMessage("تم التحقق من بصمة التطبيق والـ API Key بنجاح.\n\nالخطة الحالية: ${SubscriptionManager.currentPlan}\nعدد الرحلات اليوم: ${SubscriptionManager.ridesToday}")
                        .setPositiveButton("ممتاز", null)
                        .show()
                } else {
                    android.app.AlertDialog.Builder(this@MainActivity)
                        .setTitle("❌ خطأ في الاتصال")
                        .setMessage("فشل الاتصال بالسيرفر. تأكد من:\n1. وجود إنترنت.\n2. صحة الـ API Key في السيرفر.\n3. صحة بصمة التطبيق (SHA-256) في السيرفر.")
                        .setPositiveButton("سأتحقق", null)
                        .show()
                }
            }
        }
    }

    private fun requestPermissions() {
        val permissions = mutableListOf(
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
        )
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            permissions.add(Manifest.permission.POST_NOTIFICATIONS)
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
            permissions.add(Manifest.permission.FOREGROUND_SERVICE_LOCATION)
        }

        ActivityCompat.requestPermissions(this, permissions.toTypedArray(), 1001)
    }

    override fun onResume() {
        super.onResume()
        updateStatusUI()
    }

    private fun checkAllPermissions(): Boolean {
        val notificationEnabled = NotificationManagerCompat.getEnabledListenerPackages(this).contains(packageName)
        val overlayEnabled = Settings.canDrawOverlays(this)
        
        // Location Permission Check
        val fineLocationGranted = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
        
        // Check Accessibility
        var accessibilityEnabled = false
        val am = getSystemService(Context.ACCESSIBILITY_SERVICE) as AccessibilityManager
        val enabledServices = am.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_ALL_MASK)
        for (service in enabledServices) {
            if (service.id.contains(packageName)) {
                accessibilityEnabled = true
                break
            }
        }

        return notificationEnabled && overlayEnabled && accessibilityEnabled && fineLocationGranted
    }

    private fun updateStatusUI() {
        if (checkAllPermissions()) {
            tvStatus.text = "✅ جاهز للتشغيل"
            tvStatus.setTextColor(Color.parseColor("#00D4AA"))
        } else {
            tvStatus.text = "⚠️ بانتظار الصلاحيات"
            tvStatus.setTextColor(Color.parseColor("#FFCA28"))
        }
    }

    private fun startBot() {
        startService(Intent(this, OverlayService::class.java))
        startService(Intent(this, BotForegroundService::class.java))
        
        tvStatus.text = "⚡ البوت يعمل حالياً"
        tvStatus.setTextColor(Color.parseColor("#00D4AA"))
        
        btnStart.visibility = View.GONE
        btnStop.visibility = View.VISIBLE
        
        Toast.makeText(this, "تم التشغيل بنجاح", Toast.LENGTH_SHORT).show()
    }

    private fun stopBot() {
        stopService(Intent(this, OverlayService::class.java))
        stopService(Intent(this, BotForegroundService::class.java))
        
        tvStatus.text = "⏸ البوت متوقف"
        tvStatus.setTextColor(Color.parseColor("#FF5252"))
        
        btnStart.visibility = View.VISIBLE
        btnStop.visibility = View.GONE
    }
}
