package com.jordanbot.autoride

import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.jordanbot.autoride.api.ApiClient
import com.jordanbot.autoride.api.CheckPaymentRequest
import com.jordanbot.autoride.api.InitPaymentRequest
import com.jordanbot.autoride.subscription.SubscriptionManager
import com.jordanbot.autoride.utils.DeviceUtils
import kotlinx.coroutines.*

class SubscriptionActivity : AppCompatActivity() {

    private lateinit var tvStatus: TextView
    private lateinit var btnPro: Button
    private lateinit var btnBasic: Button
    
    // Payment Overlay UI
    private lateinit var layoutOverlay: LinearLayout
    private lateinit var tvRefCode: TextView
    private lateinit var tvTimer: TextView
    private lateinit var btnCancel: Button

    private var pollingJob: Job? = null
    private var timerJob: Job? = null

    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)
        
        layoutOverlay = findViewById(R.id.layout_payment_overlay)
        tvRefCode = findViewById(R.id.tv_ref_code)
        tvTimer = findViewById(R.id.tv_timer)
        btnCancel = findViewById(R.id.btn_cancel_payment)

        updateStatusUI()

        btnBasic.setOnClickListener { startPaymentFlow("basic", 10.0) }
        btnPro.setOnClickListener { startPaymentFlow("pro", 17.0) }
        
        btnCancel.setOnClickListener {
            stopPaymentFlow()
        }
    }

    private fun updateStatusUI() {
        val plan = SubscriptionManager.currentPlan
        val limit = SubscriptionManager.ridesLimit
        val today = SubscriptionManager.ridesToday
        val missed = SubscriptionManager.missedRidesToday
        
        val planText = when(plan) {
            "basic" -> "أساسي (3 تطبيقات)"
            "pro" -> "احترافي (5 تطبيقات)"
            else -> "مجاني (تطبيق واحد)"
        }
        
        var statusText = "الخطة الحالية: $planText\nاستهلاك اليوم: $today / $limit"
        
        // FOMO counter: show missed rides to free users
        if (missed > 0 && (plan == "free" || plan == "")) {
            val estimatedLoss = missed * 2.5 // Average ride ~2.5 JOD
            statusText += "\n\n⚠️ طلبات فاتتك اليوم بسبب الحد المجاني: $missed طلب"
            statusText += "\n💸 خسارة تقديرية: ~${String.format("%.1f", estimatedLoss)} دينار"
        }
        
        tvStatus.text = statusText
    }

    private fun startPaymentFlow(plan: String, amount: Double) {
        val fingerprint = DeviceUtils.getDeviceFingerprint(this)
        
        lifecycleScope.launch {
            try {
                val response = withContext(Dispatchers.IO) {
                    ApiClient.service.initPayment(InitPaymentRequest(fingerprint, plan, amount))
                }
                
                if (response.success && response.reference_code != null) {
                    showPaymentOverlay(response.reference_code, amount)
                    startPolling(response.reference_code)
                } else {
                    Toast.makeText(this@SubscriptionActivity, "فشل إنشاء طلب الدفع", Toast.LENGTH_SHORT).show()
                }
            } catch (e: Exception) {
                Toast.makeText(this@SubscriptionActivity, "حدث خطأ في الاتصال بالسيرفر", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun showPaymentOverlay(refCode: String, amount: Double) {
        tvRefCode.text = refCode
        layoutOverlay.visibility = View.VISIBLE
        
        // Start 10 minute timer
        var secondsLeft = 600
        timerJob?.cancel()
        timerJob = lifecycleScope.launch {
            while (secondsLeft > 0) {
                val mins = secondsLeft / 60
                val secs = secondsLeft % 60
                tvTimer.text = "ننتظر وصول الدفعة... (${String.format("%02d:%02d", mins, secs)})"
                delay(1000)
                secondsLeft--
            }
            stopPaymentFlow()
            Toast.makeText(this@SubscriptionActivity, "انتهى وقت طلب الدفع", Toast.LENGTH_LONG).show()
        }
    }

    private fun startPolling(refCode: String) {
        val fingerprint = DeviceUtils.getDeviceFingerprint(this)
        pollingJob?.cancel()
        pollingJob = lifecycleScope.launch {
            while (isActive) {
                delay(5000) // Poll every 5 seconds
                try {
                    val response = withContext(Dispatchers.IO) {
                        ApiClient.service.checkPayment(CheckPaymentRequest(refCode, fingerprint))
                    }
                    
                    if (response.status == "paid") {
                        onPaymentSuccess()
                        break
                    } else if (response.status == "expired") {
                        stopPaymentFlow()
                        Toast.makeText(this@SubscriptionActivity, "انتهت صلاحية الطلب", Toast.LENGTH_SHORT).show()
                        break
                    }
                } catch (e: Exception) {
                    // Ignore connection errors during polling
                }
            }
        }
    }

    private fun onPaymentSuccess() {
        stopPaymentFlow()
        Toast.makeText(this, "✅ تم تفعيل الاشتراك بنجاح!", Toast.LENGTH_LONG).show()
        lifecycleScope.launch {
            SubscriptionManager.checkSubscription(this@SubscriptionActivity)
            updateStatusUI()
        }
    }

    private fun stopPaymentFlow() {
        pollingJob?.cancel()
        timerJob?.cancel()
        layoutOverlay.visibility = View.GONE
    }

    override fun onDestroy() {
        super.onDestroy()
        pollingJob?.cancel()
        timerJob?.cancel()
    }
}
