package com.tapjoy.easyapp

import android.content.res.Configuration
import androidx.compose.foundation.background
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.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
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.Clear
import androidx.compose.material3.Button
import androidx.compose.material3.Checkbox
import androidx.compose.material3.Icon
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.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalConfiguration
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 androidx.compose.ui.viewinterop.AndroidView
import com.tapjoy.TJError
import com.tapjoy.TJOfferwallDiscoverListener
import com.tapjoy.TJOfferwallDiscoverView

@Preview
@Composable
fun OfferwallDiscoverScreen(viewModel: OfferwallDiscoverViewModel = OfferwallDiscoverViewModel()) {
    val context = LocalContext.current
    val configuration = LocalConfiguration.current
    val statusMessage by viewModel.statusMessage.collectAsState()
    val placementInput by viewModel.placementInput.collectAsState()
    val isPlugin by viewModel.isChecked.collectAsState()
    val heightInput by viewModel.heightInput.collectAsState()
    val widthInput by viewModel.widthInput.collectAsState()
    val leftInput by viewModel.leftInput.collectAsState()
    val topInput by viewModel.topInput.collectAsState()
    val height by viewModel.height.collectAsState()
    val width by viewModel.width.collectAsState()
    val requestClick by viewModel.requestClick.collectAsState()
    val clearClick by viewModel.clearClick.collectAsState()
    val isOfferShown by viewModel.isOfferShown.collectAsState()
    var orientation by remember { mutableIntStateOf(Configuration.ORIENTATION_PORTRAIT) }
    var screenWidth by remember { mutableIntStateOf(0) }

    // Set default width and height
    LaunchedEffect(Unit) {
        if (height.value == 0f && width.value == 0f) {
            screenWidth = configuration.screenWidthDp.dp.value.toInt()
            viewModel.setWidthInput(screenWidth.toString())
            viewModel.setHeightInput(262.dp.value.toInt().toString())
            viewModel.resizeOffers()
        }
    }
    // Set full width when orientation changes
    if (configuration.orientation != orientation) {
        if (screenWidth == width.value.toInt() && height.value != 0f && width.value != 0f) {
            viewModel.setWidthInput(configuration.screenWidthDp.dp.value.toInt().toString())
            viewModel.resizeOffers()
        }
        screenWidth = configuration.screenWidthDp.dp.value.toInt()
        orientation = configuration.orientation
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .wrapContentSize(Alignment.TopCenter)
            .verticalScroll(rememberScrollState()),
    ) {
        Spacer(modifier = Modifier.size(10.dp))
        Row(modifier = Modifier.align(Alignment.End)) {
            Checkbox(
                checked = isPlugin,
                onCheckedChange = {
                    viewModel.setPluginChecked(it)
                },
            )
            Text(
                modifier = Modifier
                    .align(Alignment.CenterVertically)
                    .padding(end = 10.dp),
                text = stringResource(id = R.string.plugin),
            )
            Spacer(modifier = Modifier.size(10.dp))
        }
        Text(
            text = statusMessage,
            modifier = Modifier
                .align(Alignment.CenterHorizontally)
                .padding(10.dp),
            textAlign = TextAlign.Center,
        )
        Spacer(modifier = Modifier.size(10.dp))

        if (isPlugin) {
            Row(modifier = Modifier.padding(start = 20.dp, end = 20.dp)) {
                Text(
                    text = stringResource(R.string.left),
                    modifier = Modifier
                        .align(Alignment.CenterVertically)
                        .padding(10.dp),
                    textAlign = TextAlign.Center,
                )
                TextField(
                    value = leftInput,
                    singleLine = true,
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
                    modifier = Modifier
                        .width(72.dp),
                    onValueChange = {
                        viewModel.setLeftInput(it)
                    },
                )
                Spacer(modifier = Modifier.size(20.dp))
                Text(
                    text = stringResource(R.string.top),
                    modifier = Modifier
                        .align(Alignment.CenterVertically)
                        .padding(8.dp),
                    textAlign = TextAlign.Center,
                )
                TextField(
                    value = topInput,
                    singleLine = true,
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
                    modifier = Modifier
                        .width(72.dp)
                        .padding(end = 8.dp),
                    onValueChange = {
                        viewModel.setTopInput(it)
                    },
                )
            }
            Spacer(modifier = Modifier.size(10.dp))
        }

        Row(modifier = Modifier.padding(start = 20.dp, end = 20.dp)) {
            Text(
                text = stringResource(R.string.width),
                modifier = Modifier
                    .align(Alignment.CenterVertically)
                    .padding(end = 8.dp),
                textAlign = TextAlign.Center,
            )
            TextField(
                value = widthInput,
                singleLine = true,
                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
                modifier = Modifier
                    .width(72.dp),
                onValueChange = {
                    viewModel.setWidthInput(it)
                },
            )
            Text(
                text = stringResource(R.string.height),
                modifier = Modifier
                    .align(Alignment.CenterVertically)
                    .padding(8.dp),
                textAlign = TextAlign.Center,
            )
            TextField(
                value = heightInput,
                singleLine = true,
                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
                modifier = Modifier
                    .width(72.dp)
                    .padding(end = 8.dp),
                onValueChange = {
                    viewModel.setHeightInput(it)
                },
            )
            Spacer(Modifier.weight(1f))
            Button(modifier = Modifier.align(Alignment.CenterVertically), onClick = {
                viewModel.resizeOffers()
            }) {
                Text(
                    text = stringResource(id = R.string.resize),
                    fontSize = 16.sp,
                )
            }
        }
        Spacer(modifier = Modifier.size(20.dp))
        TextField(
            value = placementInput,
            singleLine = true,
            modifier = Modifier
                .fillMaxWidth(1f)
                .padding(start = 20.dp, end = 20.dp)
                .align(Alignment.CenterHorizontally),
            trailingIcon = {
                Icon(
                    Icons.Default.Clear,
                    contentDescription = stringResource(id = R.string.clear),
                    modifier = Modifier
                        .clickable {
                            viewModel.setPlacementInput("")
                        },
                )
            },
            onValueChange = { placementName ->
                viewModel.setPlacementInput(placementName)
            },
        )
        Row(
            modifier = Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.Top,
            horizontalArrangement = Arrangement.SpaceEvenly,
        ) {
            Button(
                modifier = Modifier
                    .weight(1f)
                    .padding(start = 20.dp, top = 10.dp, end = 10.dp),
                onClick = {
                    viewModel.requestOffers(context)
                },
            ) {
                Text(text = stringResource(id = R.string.request), fontSize = 16.sp)
            }
            Button(
                modifier = Modifier
                    .weight(1f)
                    .padding(start = 10.dp, top = 10.dp, end = 20.dp),
                onClick = {
                    viewModel.clearOffers()
                },
            ) {
                Text(text = stringResource(id = R.string.clear), fontSize = 16.sp)
            }
        }
        Spacer(modifier = Modifier.size(10.dp))
        Box {
            Box(
                modifier = Modifier
                    .alpha(if (!isOfferShown) 1f else 0f)
                    .background(Color.LightGray)
                    .fillMaxWidth(1f)
                    .height(262.dp),
            ) {
                Text(
                    modifier = Modifier.align(Alignment.Center),
                    text = stringResource(id = R.string.offerwall_discover),
                    fontSize = 22.sp,
                )
            }
            AndroidView(
                modifier = Modifier
                    .width(width)
                    .height(height),
                factory = { context ->
                    TJOfferwallDiscoverView(context).apply {
                        setListener(object : TJOfferwallDiscoverListener {
                            override fun requestSuccess() {
                                viewModel.setRequestSuccess()
                            }

                            override fun requestFailure(error: TJError?) {
                                viewModel.setRequestFailure(error)
                            }

                            override fun contentReady() {
                                viewModel.setContentReady(context)
                            }

                            override fun contentError(error: TJError?) {
                                viewModel.setContentError(error)
                            }
                        })
                    }
                },
                update = { owd ->
                    if (requestClick) {
                        owd.requestContent(context, placementInput)
                    }
                    if (clearClick) {
                        owd.clearContent()
                    }
                    viewModel.resetClicks()
                },
            )
        }
    }
}
