package com.jordanbot.autoride

import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.jordanbot.autoride.api.ActivateSubscriptionRequest
import com.jordanbot.autoride.api.ApiClient
import com.jordanbot.autoride.subscription.SubscriptionManager
import com.jordanbot.autoride.utils.DeviceUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class SubscriptionActivity : AppCompatActivity() {

    private lateinit var tvStatus: TextView
    private lateinit var btnBasic: Button
    private lateinit var btnPro: Button

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

        tvStatus = findViewById(R.id.tv_current_status)
        btnBasic = findViewById(R.id.btn_subscribe_basic)
        btnPro = findViewById(R.id.btn_subscribe_pro)

        updateStatusUI()

        btnBasic.setOnClickListener { activatePlan("basic") }
        btnPro.setOnClickListener { activatePlan("pro") }
    }

    private fun updateStatusUI() {
        val plan = SubscriptionManager.currentPlan
        val limit = SubscriptionManager.ridesLimit
        val today = SubscriptionManager.ridesToday
        
        val planText = when(plan) {
            "basic" -> "أساسي ($limit طلب / يوم)"
            "pro" -> "احترافي (لا محدود)"
            "annual" -> "سنوي (لا محدود)"
            else -> "مجاني (1 طلب / يوم)"
        }
        
        tvStatus.text = "الخطة الحالية: $planText\nاستهلاك اليوم: $today"
    }

    private fun activatePlan(plan: String) {
        // In a real app, integrate payment gateway here.
        // For demonstration, we just call the API directly.
        val fingerprint = DeviceUtils.getDeviceFingerprint(this)
        
        lifecycleScope.launch {
            try {
                val response = withContext(Dispatchers.IO) {
                    ApiClient.service.activateSubscription(
                        ActivateSubscriptionRequest(fingerprint, plan, "DEMO_REF_123")
                    )
                }
                
                if (response.success) {
                    Toast.makeText(this@SubscriptionActivity, "تم تفعيل الاشتراك بنجاح!", Toast.LENGTH_SHORT).show()
                    // Re-check subscription to update local cache
                    SubscriptionManager.checkSubscription(this@SubscriptionActivity)
                    updateStatusUI()
                } else {
                    Toast.makeText(this@SubscriptionActivity, "فشل تفعيل الاشتراك: ${response.message}", Toast.LENGTH_SHORT).show()
                }
            } catch (e: Exception) {
                Toast.makeText(this@SubscriptionActivity, "حدث خطأ في الاتصال", Toast.LENGTH_SHORT).show()
            }
        }
    }
}
