package com.jiooption.trading.ui.deposit

import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.android.billingclient.api.ProductDetails
import com.jiooption.trading.R
import com.jiooption.trading.billing.BillingManager
import com.jiooption.trading.billing.BillingRepository
import com.jiooption.trading.utils.*
import com.google.android.material.button.MaterialButton
import com.google.android.material.card.MaterialCardView
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

/**
 * Deposit activity with Google Play Billing purchase flow
 * Shows deposit amount grid and processes purchases
 */
class DepositActivity : AppCompatActivity() {

    companion object {
        private const val TAG = "DepositActivity"
    }

    private lateinit var billingManager: BillingManager
    private val billingRepository = BillingRepository()

    private var selectedProductId: String? = null
    private var amountButtons = mutableListOf<MaterialCardView>()

    // Deposit amounts
    private val depositOptions = listOf(
        "deposit_100" to "₹100",
        "deposit_500" to "₹500",
        "deposit_1000" to "₹1,000",
        "deposit_2000" to "₹2,000",
        "deposit_5000" to "₹5,000",
    )

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

        setupViews()
        setupBilling()
    }

    private fun setupViews() {
        // Back button
        findViewById<ImageView>(R.id.btnBack).setOnClickListener { finish() }

        // Build the amount selection grid
        val gridLayout = findViewById<GridLayout>(R.id.amountGrid)
        gridLayout.removeAllViews()

        depositOptions.forEach { (productId, label) ->
            val card = createAmountCard(productId, label)
            gridLayout.addView(card)
            amountButtons.add(card)
        }

        // Pay button
        val btnPay = findViewById<MaterialButton>(R.id.btnPay)
        btnPay.setOnClickListener {
            if (selectedProductId != null) {
                initiatePayment()
            } else {
                toast("Please select a deposit amount")
            }
        }
    }

    private fun createAmountCard(productId: String, label: String): MaterialCardView {
        val card = MaterialCardView(this).apply {
            layoutParams = GridLayout.LayoutParams().apply {
                width = 0
                height = GridLayout.LayoutParams.WRAP_CONTENT
                columnSpec = GridLayout.spec(GridLayout.UNDEFINED, 1f)
                setMargins(8, 8, 8, 8)
            }
            cardElevation = 0f
            strokeColor = getColor(R.color.border_color)
            strokeWidth = 2
            radius = resources.getDimension(R.dimen.corner_radius_md)
            setCardBackgroundColor(getColor(R.color.bg_tertiary))
            isClickable = true
            isFocusable = true
        }

        val textView = TextView(this).apply {
            text = label
            textSize = 16f
            setTextColor(getColor(R.color.text_primary))
            textAlignment = View.TEXT_ALIGNMENT_CENTER
            setPadding(16, 32, 16, 32)
        }

        card.addView(textView)

        card.setOnClickListener {
            selectAmount(productId, card)
        }

        return card
    }

    private fun selectAmount(productId: String, selectedCard: MaterialCardView) {
        selectedProductId = productId

        // Update visual state
        amountButtons.forEach { card ->
            if (card == selectedCard) {
                card.strokeColor = getColor(R.color.accent_green)
                card.setCardBackgroundColor(getColor(R.color.accent_green_light))
            } else {
                card.strokeColor = getColor(R.color.border_color)
                card.setCardBackgroundColor(getColor(R.color.bg_tertiary))
            }
        }

        // Update pay button text
        val amount = Constants.getAmountForProduct(productId)
        val btnPay = findViewById<MaterialButton>(R.id.btnPay)
        btnPay.text = "Pay ${amount.formatINR()}"
        btnPay.isEnabled = true
    }

    private fun setupBilling() {
        billingManager = BillingManager(this)

        // Handle successful purchases
        billingManager.onPurchaseCompleted = { purchase ->
            Log.d(TAG, "Purchase completed, verifying on server...")
            showLoading(true)

            lifecycleScope.launch {
                val (success, message) = billingRepository.verifyPurchase(purchase)
                showLoading(false)

                if (success) {
                    showSuccess(message)
                } else {
                    showError(message)
                }
            }
        }

        // Handle purchase errors
        billingManager.onPurchaseError = { errorMessage ->
            showLoading(false)
            if (errorMessage != "Purchase cancelled") {
                showError(errorMessage)
            }
        }

        // Observe product details
        lifecycleScope.launch {
            billingManager.productDetailsList.collectLatest { products ->
                if (products.isNotEmpty()) {
                    Log.d(TAG, "Products loaded: ${products.size}")
                    // Could update prices from Google Play here
                }
            }
        }

        // Initialize billing
        billingManager.initialize()
    }

    private fun initiatePayment() {
        val productId = selectedProductId ?: return

        if (!NetworkUtils.isNetworkAvailable(this)) {
            toast(getString(R.string.no_internet))
            return
        }

        showLoading(true)
        billingManager.purchaseProduct(productId)
    }

    private fun showLoading(show: Boolean) {
        runOnUiThread {
            findViewById<ProgressBar>(R.id.progressBar).visibility =
                if (show) View.VISIBLE else View.GONE
            findViewById<MaterialButton>(R.id.btnPay).isEnabled = !show
        }
    }

    private fun showSuccess(message: String) {
        runOnUiThread {
            val rootView = findViewById<View>(android.R.id.content)
            rootView.showSuccessSnackbar("✅ $message")
            // Reset selection
            selectedProductId = null
            amountButtons.forEach { card ->
                card.strokeColor = getColor(R.color.border_color)
                card.setCardBackgroundColor(getColor(R.color.bg_tertiary))
            }
            val btnPay = findViewById<MaterialButton>(R.id.btnPay)
            btnPay.text = getString(R.string.deposit_funds)
            btnPay.isEnabled = false
        }
    }

    private fun showError(message: String) {
        runOnUiThread {
            val rootView = findViewById<View>(android.R.id.content)
            rootView.showErrorSnackbar("❌ $message")
        }
    }

    override fun onDestroy() {
        billingManager.destroy()
        super.onDestroy()
    }
}
