package pl.novelpay.samplesdkcommunicator

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.TextUnitType
import androidx.compose.ui.unit.dp
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch
import pl.novelpay.samplesdkcommunicator.Application.Companion.getSDK
import pl.novelpay.samplesdkcommunicator.Application.Companion.interceptionChannel
import pl.novelpay.samplesdkcommunicator.ui.theme.SampleSDKCommunicatorTheme

class MainActivity : ComponentActivity() {
    private val viewModel = defaultViewModelProviderFactory.create(MainViewModel::class.java)


    @OptIn(ExperimentalMaterial3Api::class)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (!Settings.canDrawOverlays(this))
            startActivity(
                Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:$packageName"))
            )
        viewModel.clientSDK = applicationContext.getSDK();
        lifecycleScope.launch {
            applicationContext.interceptionChannel().collect { message ->
                viewModel.interceptor.intercept(message)
            }
        }

        setContent {
            SampleSDKCommunicatorTheme { // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    Column(horizontalAlignment = Alignment.CenterHorizontally) {
                        val currency by viewModel.currency.collectAsState()
                        val amount by viewModel.amount.collectAsState()
                        val paidAmount by viewModel.paidAmount.collectAsState()
                        val tipAmount by viewModel.tipAmount.collectAsState()
                        val cashBackAmount by viewModel.cashbackAmount.collectAsState()
                        val poiTransactionId by viewModel.poiTransactionId.collectAsState()
                        val service by viewModel.service.collectAsState()
                        var isExpanded by remember { mutableStateOf(false) }
                        var isDropdownExpanded by remember { mutableStateOf(false) }
                        Card(
                            modifier = Modifier
                                .padding(15.dp)
                                .fillMaxWidth()
                        ) {
                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .clickable {
                                        isExpanded = !isExpanded
                                    },
                                verticalAlignment = Alignment.CenterVertically,
                                horizontalArrangement = Arrangement.SpaceBetween
                            ) {
                                Text(
                                    modifier = Modifier.padding(start = 15.dp),
                                    color = Color.Gray,
                                    text = "Transaction Parameters"
                                )
                                Icon(
                                    if (isExpanded) Icons.Default.Close else Icons.Default.ArrowDropDown,
                                    "Show amount options",
                                    modifier = Modifier
                                        .padding(4.dp)
                                )
                            }
                            Column(
                                modifier = Modifier.fillMaxWidth(),
                                horizontalAlignment = Alignment.CenterHorizontally
                            ) {
                                Column(
                                    modifier = Modifier.verticalScroll(rememberScrollState()),
                                    horizontalAlignment = Alignment.CenterHorizontally
                                ) {
                                    if (isExpanded) {
                                        TextField(
                                            value = service,
                                            label = { Text(text = "Service") },
                                            onValueChange = {},
                                            enabled = false,
                                            modifier = Modifier.clickable {
                                                isDropdownExpanded = !isDropdownExpanded
                                            },
                                            colors = TextFieldDefaults.textFieldColors(
                                                disabledTextColor = LocalContentColor.current,
                                                disabledLabelColor = MaterialTheme.colorScheme.onSurface
                                            )
                                        )
                                        Box {
                                            DropdownMenu(
                                                expanded = isDropdownExpanded,
                                                onDismissRequest = {
                                                    isDropdownExpanded = !isDropdownExpanded
                                                }) {
                                                SupportedPaymentServices.toTypedArray()
                                                    .forEach { service ->
                                                        DropdownMenuItem(
                                                            text = { Text(text = service) },
                                                            onClick = {
                                                                isDropdownExpanded =
                                                                    !isDropdownExpanded
                                                                viewModel.switchService(service)
                                                            })
                                                    }
                                            }
                                        }
                                        TextField(
                                            value = poiTransactionId,
                                            label = { Text(text = "PoiTransactionId") },
                                            onValueChange = viewModel::switchPoiTransactionId
                                        )
                                        TextField(
                                            value = currency,
                                            label = { Text(text = "Currency(ex:EUR)") },
                                            onValueChange = viewModel::switchCurrency,
                                            singleLine = true
                                        )
                                        TextField(
                                            value = amount,
                                            label = { Text(text = "Amount(ex:15.30)") },
                                            onValueChange = viewModel::switchAmount,
                                            singleLine = true,
                                            keyboardOptions = KeyboardOptions.Default.copy(
                                                keyboardType = KeyboardType.Number
                                            )
                                        )
                                        TextField(
                                            value = paidAmount.orEmpty(),
                                            label = { Text(text = "Paid Amount") },
                                            onValueChange = viewModel::switchPaidAmount,
                                            singleLine = true,
                                            keyboardOptions = KeyboardOptions.Default.copy(
                                                keyboardType = KeyboardType.Number
                                            )
                                        )
                                        TextField(
                                            value = cashBackAmount.orEmpty(),
                                            label = { Text(text = "Cashback Amount") },
                                            onValueChange = viewModel::switchCashbackAmount,
                                            singleLine = true,
                                            keyboardOptions = KeyboardOptions.Default.copy(
                                                keyboardType = KeyboardType.Number
                                            )
                                        )
                                        TextField(
                                            value = tipAmount.orEmpty(),
                                            label = { Text(text = "Tip Amount") },
                                            onValueChange = viewModel::switchTipAmount,
                                            singleLine = true,
                                            keyboardOptions = KeyboardOptions.Default.copy(
                                                keyboardType = KeyboardType.Number
                                            )
                                        )
                                        Row(
                                            horizontalArrangement = Arrangement.SpaceEvenly,
                                            modifier = Modifier
                                                .fillMaxWidth()
                                                .padding(top = 4.dp)
                                        ) {
                                            Button(onClick = { viewModel.sendTestConnectionRequest() }) {
                                                Text(text = "Test")
                                            }
                                            Button(onClick = { viewModel.sendReversalRequest() }) {
                                                Text(text = "Reversal")
                                            }
                                        }
                                        Row(
                                            horizontalArrangement = Arrangement.SpaceEvenly,
                                            modifier = Modifier
                                                .fillMaxWidth()
                                                .padding(top = 4.dp)
                                        ) {
                                            Button(onClick = { viewModel.sendPayment() }) {
                                                Text(text = "Payment")
                                            }
                                            Button(onClick = { viewModel.sendStatusRequest() }) {
                                                Text(text = "Status")
                                            }
                                        }
                                        Row(
                                            horizontalArrangement = Arrangement.SpaceEvenly,
                                            modifier = Modifier
                                                .fillMaxWidth()
                                                .padding(top = 4.dp)
                                        ) {
                                            Button(onClick = { viewModel.sendActivationRequest() }) {
                                                Text(text = "Activation")
                                            }
                                            Button(onClick = { viewModel.sendUpdateRequest() }) {
                                                Text(text = "Update")
                                            }
                                        }
                                    }
                                }
                                Row(
                                    horizontalArrangement = Arrangement.SpaceEvenly,
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(top = 4.dp)
                                ) {
                                    Button(onClick = { viewModel.sendLogin() }) {
                                        Text(text = "Login")
                                    }
                                    Button(onClick = { viewModel.sendLogout() }) {
                                        Text(text = "LogOut")
                                    }
                                }
                            }
                        }
                        val response by viewModel.response.collectAsState()
                        Text(
                            text = response,
                            textAlign = TextAlign.Start,
                            modifier = Modifier
                                .verticalScroll(rememberScrollState())
                                .padding(15.dp),
                            fontSize = TextUnit(10F, TextUnitType.Sp)
                        )
                    }
                }
            }
        }
    }
}

@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
  Text(
    text = "Hello $name!", modifier = modifier
  )
}

@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
  SampleSDKCommunicatorTheme {
    Greeting("Android")
  }
}