package com.tapjoy.easyapp

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.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentSize
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.Clear
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.SegmentedButton
import androidx.compose.material3.SegmentedButtonDefaults
import androidx.compose.material3.SingleChoiceSegmentedButtonRow
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
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.platform.LocalContext
import androidx.compose.ui.res.stringResource
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.dp
import androidx.compose.ui.unit.sp
import com.tapjoy.Tapjoy
import com.tapjoy.easyapp.theme.DisabledColor
import com.tapjoy.easyapp.theme.Yellow700

@Preview
@Composable
fun MainScreen(viewModel: MainViewModel = MainViewModel()) {
    val context = LocalContext.current
    val eventMessage by viewModel.statusMessage.collectAsState()
    val currencyId by viewModel.currencyId.collectAsState()
    val currencyAmount by viewModel.currencyAmount.collectAsState()
    val currencyBalance by viewModel.currencyBalance.collectAsState()
    val currencyRequiredAmount by viewModel.currencyRequiredAmount.collectAsState()
    val isConnected by viewModel.isConnected.collectAsState()
    val isConnecting by viewModel.isConnecting.collectAsState()
    val isSelfManaged by viewModel.isSelfManaged.collectAsState()
    val isRequestReady by viewModel.isRequestReady.collectAsState()
    val loggingLevel = viewModel.loggingLevel.collectAsState()
    val purchasePrice by viewModel.purchasePrice.collectAsState()
    val purchaseCode by viewModel.purchaseCode.collectAsState()

    // Dropdown
    var isEntryPointExpanded by remember { mutableStateOf(false) }
    var selectedOptionText by remember { mutableStateOf(viewModel.entryPoints[0]) }

    // SharedPreferences
    val preferences = context.getSharedPreferences(PREFERENCES, 0)
    val sdkKey by remember { mutableStateOf(preferences.getString(PREF_SDK_CURRENT_KEY, DEFAULT_SDK_KEY) ?: DEFAULT_SDK_KEY) }
    val isAutoConnect by remember { mutableStateOf(preferences.getBoolean(AUTO_CONNECT_KEY, true)) }
    var placement by remember { mutableStateOf(preferences.getString(PLACEMENT_NAME_KEY, "offerwall_unit") ?: "offerwall_unit") }
    val debugLevel by remember { mutableIntStateOf(preferences.getInt(DEBUG_KEY, 0)) }

    LaunchedEffect(Unit) {
        viewModel.setLoggingLevelSegment(debugLevel)
        Tapjoy.setLoggingLevel(viewModel.getStoredLoggingLevel(preferences))
        if (isAutoConnect && !isConnected) {
            viewModel.connect(context, sdkKey)
        } else if (!isAutoConnect && !isConnected) {
            viewModel.setManualConnectMessage()
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .wrapContentSize(Alignment.TopCenter)
            .verticalScroll(rememberScrollState()),
    ) {
        Spacer(modifier = Modifier.size(10.dp))
        Text(
            text = eventMessage,
            modifier = Modifier
                .align(Alignment.CenterHorizontally)
                .padding(10.dp),
            textAlign = TextAlign.Center,
        )
        if (!isAutoConnect && !isConnected) {
            Button(
                colors = ButtonDefaults.buttonColors(containerColor = if (!isConnecting) Yellow700 else DisabledColor),
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 20.dp)
                    .align(Alignment.CenterHorizontally),
                onClick = {
                    viewModel.connect(context, sdkKey)
                },
            ) {
                Text(text = stringResource(id = R.string.connect_sdk), fontSize = 16.sp)
            }
        }
        Button(
            colors = ButtonDefaults.buttonColors(containerColor = if (!isConnecting && isConnected) Yellow700 else DisabledColor),
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 20.dp)
                .align(Alignment.CenterHorizontally),
            onClick = {
                viewModel.showOfferwall()
            },
        ) {
            Text(text = stringResource(id = R.string.show_offerwall), fontSize = 16.sp)
        }
        Text(
            text = stringResource(id = R.string.managed_currency),
            modifier = Modifier
                .align(Alignment.Start)
                .padding(10.dp),
            textAlign = TextAlign.Start,
            fontSize = 16.sp,
        )
        TextField(
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
            singleLine = true,
            modifier = Modifier.fillMaxWidth().padding(start = 20.dp, end = 20.dp, bottom = 10.dp),
            value = if (currencyAmount < 0) "" else currencyAmount.toString(),
            onValueChange = {
                viewModel.setManagedCurrencyAmount(it)
            },
        )
        Row(
            modifier = Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.Top,
            horizontalArrangement = Arrangement.SpaceEvenly,
        ) {
            Button(
                colors = ButtonDefaults.buttonColors(containerColor = if (!isConnecting && isConnected) Yellow700 else DisabledColor),
                modifier = Modifier
                    .weight(1f)
                    .padding(start = 20.dp, end = 10.dp),
                onClick = {
                    viewModel.getCurrencyBalance()
                },
            ) {
                Text(text = stringResource(id = R.string.get), fontSize = 16.sp)
            }
            Button(
                colors = ButtonDefaults.buttonColors(containerColor = if (!isConnecting && isConnected) Yellow700 else DisabledColor),
                modifier = Modifier
                    .weight(1f)
                    .padding(start = 10.dp, end = 10.dp),
                onClick = {
                    viewModel.callSpendCurrency(currencyAmount)
                },
            ) {
                Text(text = stringResource(id = R.string.spend), fontSize = 16.sp)
            }
            Button(
                colors = ButtonDefaults.buttonColors(containerColor = if (!isConnecting && isConnected) Yellow700 else DisabledColor),
                modifier = Modifier
                    .weight(1f)
                    .padding(start = 10.dp, end = 20.dp),
                onClick = {
                    viewModel.callAwardCurrency(currencyAmount)
                },
            ) {
                Text(text = stringResource(id = R.string.award), fontSize = 16.sp)
            }
        }
        Text(
            text = stringResource(id = R.string.content_placements),
            color = Color.Black,
            modifier = Modifier
                .align(Alignment.Start)
                .padding(10.dp),
            textAlign = TextAlign.Start,
            fontSize = 16.sp,
        )
        TextField(
            value = placement,
            singleLine = true,
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 20.dp)
                .align(Alignment.CenterHorizontally),
            trailingIcon = {
                Icon(
                    Icons.Default.Clear,
                    contentDescription = stringResource(id = R.string.clear),
                    modifier = Modifier
                        .clickable {
                            placement = ""
                            preferences.edit().putString(PLACEMENT_NAME_KEY, placement).apply()
                        },
                )
            },
            onValueChange = { placementName ->
                placement = placementName
                preferences.edit().putString(PLACEMENT_NAME_KEY, placementName).apply()
            },
        )
        Row(
            modifier = Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.Top,
            horizontalArrangement = Arrangement.SpaceEvenly,
        ) {
            Button(
                colors = ButtonDefaults.buttonColors(containerColor = if (!isConnecting && isConnected) Yellow700 else DisabledColor),
                modifier = Modifier
                    .weight(1f)
                    .padding(start = 20.dp, top = 20.dp, end = 10.dp),
                onClick = {
                    viewModel.requestPlacement(placement)
                },
            ) {
                Text(text = stringResource(id = R.string.request), fontSize = 16.sp)
            }
            Button(
                colors = ButtonDefaults.buttonColors(containerColor = if (isRequestReady) Yellow700 else DisabledColor),
                modifier = Modifier
                    .weight(1f)
                    .padding(start = 10.dp, top = 20.dp, end = 20.dp),
                onClick = {
                    viewModel.showPlacement()
                },
            ) {
                Text(text = stringResource(id = R.string.show), fontSize = 16.sp)
            }
        }

        Row(
            modifier = Modifier
                .padding(horizontal = 10.dp),
        ) {
            Text(
                text = stringResource(id = R.string.currency_settings),
                color = Color.Black,
                textAlign = TextAlign.Start,
                fontSize = 16.sp,
                modifier = Modifier
                    .align(Alignment.CenterVertically)
                    .padding(end = 8.dp),
            )
            Switch(
                checked = isSelfManaged,
                onCheckedChange = {
                    viewModel.setIsSelfManaged(it)
                },
                modifier = Modifier.align(Alignment.CenterVertically),
            )
        }

        if (isSelfManaged) {
            Row(
                modifier = Modifier
                    .align(Alignment.CenterHorizontally)
                    .fillMaxWidth(0.9f),
            ) {
                Text(
                    text = stringResource(id = R.string.user_currency_id),
                    color = Color.Black,
                    modifier = Modifier
                        .padding(10.dp)
                        .fillMaxWidth(0.2f),
                    textAlign = TextAlign.Start,
                    fontSize = 16.sp,
                )
                TextField(
                    value = currencyId,
                    singleLine = true,
                    modifier = Modifier.fillMaxWidth(1f),
                    onValueChange = {
                        viewModel.setCurrencyId(it)
                    },
                )
            }

            Spacer(modifier = Modifier.size(10.dp))
            Row(
                modifier = Modifier
                    .align(Alignment.CenterHorizontally)
                    .fillMaxWidth(0.9f),
            ) {
                Text(
                    text = stringResource(id = R.string.user_currency_balance),
                    color = Color.Black,
                    modifier = Modifier
                        .padding(10.dp)
                        .fillMaxWidth(0.2f),
                    textAlign = TextAlign.Start,
                    fontSize = 16.sp,
                )
                TextField(
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
                    singleLine = true,
                    modifier = Modifier.fillMaxWidth(1f),
                    placeholder = { Text(stringResource(id = R.string.self_managed)) },
                    value = if (currencyBalance < 0) "" else currencyBalance.toString(),
                    onValueChange = {
                        viewModel.setCurrencyBalance(it)
                    },
                )
            }

            Spacer(modifier = Modifier.size(10.dp))
            Row(
                modifier = Modifier
                    .align(Alignment.CenterHorizontally)
                    .fillMaxWidth(0.9f),
            ) {
                Text(
                    text = stringResource(id = R.string.user_currency_required),
                    color = Color.Black,
                    modifier = Modifier
                        .padding(10.dp)
                        .fillMaxWidth(0.2f),
                    textAlign = TextAlign.Start,
                    fontSize = 16.sp,
                )
                TextField(
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
                    singleLine = true,
                    modifier = Modifier.fillMaxWidth(1f),
                    value = if (currencyRequiredAmount < 0) "" else currencyRequiredAmount.toString(),
                    onValueChange = {
                        viewModel.setCurrencyRequiredAmount(it)
                    },
                )
            }
            Spacer(modifier = Modifier.size(10.dp))
        }

        Text(
            text = stringResource(id = R.string.entry_point),
            color = Color.Black,
            modifier = Modifier
                .align(Alignment.Start)
                .padding(horizontal = 10.dp),
            textAlign = TextAlign.Start,
            fontSize = 16.sp,
        )
        Box(modifier = Modifier.padding(top = 10.dp, start = 10.dp)) {
            Row(
                Modifier
                    .padding(horizontal = 10.dp)
                    .clickable {
                        isEntryPointExpanded = !isEntryPointExpanded
                    },
            ) {
                Text(text = selectedOptionText)
                Icon(imageVector = Icons.Filled.ArrowDropDown, "")
            }
            DropdownMenu(
                expanded = isEntryPointExpanded,
                onDismissRequest = {
                    isEntryPointExpanded = false
                },
            ) {
                viewModel.entryPoints.forEach { option ->
                    DropdownMenuItem(onClick = {
                        viewModel.setSelectedEntryPoint(option)
                        isEntryPointExpanded = false
                        selectedOptionText = viewModel.getEntryPointString(option)
                    }, text = {
                        Text(
                            text = viewModel.getEntryPointString(option),
                            fontSize = 16.sp,
                        )
                    })
                }
            }
        }

        Text(
            text = stringResource(id = R.string.purchase),
            color = Color.Black,
            modifier = Modifier
                .align(Alignment.Start)
                .padding(10.dp),
            textAlign = TextAlign.Start,
            fontSize = 16.sp,
        )
        Row(
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.SpaceEvenly,
        ) {
            Text(
                text = stringResource(id = R.string.price),
                fontSize = 16.sp,
                modifier = Modifier.padding(start = 16.dp, end = 10.dp),
            )
            TextField(
                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
                singleLine = true,
                modifier = Modifier.padding(end = 20.dp).weight(1f),
                value = purchasePrice,
                onValueChange = {
                    viewModel.setPurchaseAmount(it)
                },
            )
            Text(
                text = stringResource(id = R.string.code),
                fontSize = 16.sp,
                modifier = Modifier.padding(end = 10.dp),
            )
            TextField(
                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
                singleLine = true,
                modifier = Modifier.padding(end = 16.dp).weight(1f),
                value = purchaseCode,
                onValueChange = {
                    viewModel.setPurchaseCode(it)
                },
            )
        }

        Button(
            colors = ButtonDefaults.buttonColors(containerColor = if (!isConnecting && isConnected) Yellow700 else DisabledColor),
            modifier = Modifier
                .padding(start = 20.dp, end = 20.dp, top = 20.dp)
                .fillMaxWidth()
                .align(Alignment.CenterHorizontally),
            onClick = {
                viewModel.purchase()
            },
        ) {
            Text(
                text = stringResource(id = R.string.purchase),
                fontSize = 16.sp,
            )
        }
        Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(start = 10.dp, top = 20.dp, end = 10.dp)) {
            Text("Logging Level")
            SingleChoiceSegmentedButtonRow(modifier = Modifier.padding(start = 5.dp)) {
                viewModel.loggingOptions.forEachIndexed { index, label ->
                    SegmentedButton(
                        shape = SegmentedButtonDefaults.itemShape(
                            index = index,
                            count = viewModel.loggingOptions.size,
                        ),
                        onClick = {
                            viewModel.setLoggingLevel(preferences, index)
                        },
                        selected = index == loggingLevel.value,
                        label = { Text(label, maxLines = 1) },
                    )
                }
            }
        }

        Spacer(modifier = Modifier.size(20.dp))
        Row(
            modifier = Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.Bottom,
            horizontalArrangement = Arrangement.SpaceBetween,
        ) {
            Text(
                text = viewModel.getSDKVersion(),
                color = Color.Black,
                modifier = Modifier
                    .padding(10.dp),
                textAlign = TextAlign.Center,
                fontSize = 16.sp,
            )
        }
    }
}
