package com.jpay.apm

import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.jpay.apm.ui.theme.JpayapmTheme
import org.json.JSONObject

class MainActivity : ComponentActivity() {
    // Payment constants
    private val TEST_ORDER_ID = "TEST123456789"
    private val TEST_PAY_URL = "http://192.168.1.52/pay/callbackurl?code=NomuPayACI&order_no=318792242442&order_status=1&transaction_id=ca6e599119214317853ff3bfb2fa8a4c&result_info=0000:Success" // Replace with real payment URL
    
    // Payment module instance
    private lateinit var jPayAPM: JPayAPM
    
    // Shared state for payment result between Compose and native code
    private val paymentResultState = mutableStateOf<String>("")
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        
        // Initialize payment module
        jPayAPM = JPayAPM(this, applicationContext)
        
        // Handle Scheme callback
        handleSchemeIntent(intent)
        
        setContent {
            JpayapmTheme {
                Scaffold(modifier = Modifier.fillMaxSize()) {
                    PaymentScreen(
                        modifier = Modifier.padding(it),
                        paymentResult = paymentResultState.value,
                        onPayClick = { 
                            // Clear previous result
                            paymentResultState.value = ""
                            // Start payment
                            jPayAPM.exec(
                                payMethod = "googlepay",
                                payUrl = TEST_PAY_URL,
                                callback = ::handlePayCallback
                            )
                        }
                    )
                }
            }
        }
    }
    
    /**
     * Process payment callback
     */
    private fun handlePayCallback(result: JSONObject) {
        runOnUiThread {
            try {
                val status = result.getInt("status")
                val message = result.getString("message")
                val orderId = result.getString("orderId")
                
                // Format result text
                val resultText = """Order ID: $orderId
                Status: ${getStatusDesc(status)}
                Message: $message""".trimIndent()
                
                // Update shared state
                paymentResultState.value = resultText
                
                // Display toast
                Toast.makeText(this, getStatusDesc(status), Toast.LENGTH_SHORT).show()
                
                // Log result
                Log.d("MainActivity", "Payment result: $result")
            } catch (e: Exception) {
                Log.e("MainActivity", "Parse error", e)
                val errorText = "Parse error: ${e.message}"
                paymentResultState.value = errorText
                Toast.makeText(this, errorText, Toast.LENGTH_SHORT).show()
            }
        }
    }
    
    /**
     * Handle custom Scheme intent
     */
    private fun handleSchemeIntent(intent: android.content.Intent?) {
        intent ?: return
        val data: Uri? = intent.data
         
        if (data != null && data.scheme == "jpayapm" && data.host == "payment" && data.path == "/result") {
            val status = data.getQueryParameter("status")?.toInt() ?: JPayAPM.PAY_STATUS_FAILED
            val orderId = data.getQueryParameter("orderId") ?: TEST_ORDER_ID
            val msg = data.getQueryParameter("msg") ?: "Scheme callback"
             
            jPayAPM.triggerPayResult(status, msg, orderId)
        }
    }
    
    /**
     * Get status description
     */
    private fun getStatusDesc(status: Int): String {
        return when (status) {
            0 -> "Success"
            1 -> "Failed"
            else -> "Unknown"
        }
    }
}

@Composable
fun PaymentScreen(
    modifier: Modifier = Modifier,
    paymentResult: String,
    onPayClick: () -> Unit
) {
    Column(
        modifier = modifier
            .fillMaxSize()
            .padding(16.dp),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        // Payment Button
        Button(
            onClick = onPayClick,
            modifier = Modifier.padding(bottom = 16.dp)
        ) {
            Text(text = "Pay with Google Pay")
        }
        
        // Result Display
        Text(
            text = if (paymentResult.isEmpty()) "Click the button to start payment" else paymentResult,
            modifier = Modifier.padding(16.dp)
        )
    }
}

@Preview(showBackground = true)
@Composable
fun PaymentScreenPreview() {
    JpayapmTheme {
        PaymentScreen(
            paymentResult = "",
            onPayClick = {}
        )
    }
}