package org.octopus.randomfacts

import android.content.Context
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalClipboard
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.android.billingclient.api.AcknowledgePurchaseParams
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.octopus.randomfacts.core.shared.Const
import org.octopus.randomfacts.core.shared.HttpClient
import org.octopus.randomfacts.core.shared.PreferenceDataStore
import org.octopus.randomfacts.ui.theme.greenColor
import org.octopus.randomfacts.ui.theme.myFontFamily
import org.octopus.randomfacts.ui.theme.orangeColor
import org.octopus.randomfacts.core.billing.OctopusBillingClient
import org.octopus.randomfacts.core.billing.PurchaseState

// --------------------------- Main Activity ---------------------------
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            RandomFactsScreen(this)
        }
    }
}


// --------------------------- Composable Screen ---------------------------
@Composable
fun RandomFactsScreen(activity: ComponentActivity) {
    val clipboardManager = LocalClipboard.current
    var coins by remember { mutableIntStateOf(0) }
    val scope = rememberCoroutineScope()
    var response by remember { mutableStateOf(Const.DEFAULT_FACT_PLACEHOLDER) }
    var unlocked by remember { mutableStateOf(false) }
    var isInitialized by remember { mutableStateOf(false) }

    val billingClient = OctopusBillingClient(activity) {
        if (it == PurchaseState.OK) {
            unlocked = true
        }
    }
    billingClient.init(onlyCheck = true)

    LaunchedEffect(Unit) {
        response = PreferenceDataStore.loadFact(activity)
        val savedCoins = PreferenceDataStore.loadCoins(activity)
        val lastUpdate = PreferenceDataStore.loadTimestamp(activity)
        val hoursPassed = ((System.currentTimeMillis() - lastUpdate) / Const.COIN_INCREMENT_INTERVAL).toInt()
        coins = (savedCoins + hoursPassed).coerceAtMost(Const.MAX_COINS)
        PreferenceDataStore.saveCoins(activity, coins)
        isInitialized = true
    }

    LaunchedEffect(isInitialized) {
        if (!isInitialized) return@LaunchedEffect

        snapshotFlow { coins }
            .collect { currentCoins ->
                if (currentCoins < Const.MAX_COINS) {
                    val lastUpdate = PreferenceDataStore.loadTimestamp(activity)
                    val elapsed = System.currentTimeMillis() - lastUpdate
                    delay(Const.COIN_INCREMENT_INTERVAL - elapsed)
                    while (true) {
                        val actualCoins = PreferenceDataStore.loadCoins(activity)
                        if (actualCoins >= Const.MAX_COINS) break

                        val lastUpdate = PreferenceDataStore.loadTimestamp(activity)
                        val elapsed = System.currentTimeMillis() - lastUpdate

                        if (elapsed >= Const.COIN_INCREMENT_INTERVAL) {
                            PreferenceDataStore.saveCoins(activity, actualCoins + 1)
                            PreferenceDataStore.saveTimestamp(activity, System.currentTimeMillis())
                            coins = actualCoins + 1
                        } else {
                            delay(Const.COIN_INCREMENT_INTERVAL - elapsed)
                        }
                    }
                }
            }
    }



    LaunchedEffect(response) {
        PreferenceDataStore.saveFact(activity, response)
    }

    Box(modifier = Modifier.fillMaxSize()) {
        Image(
            painter = painterResource(id = R.drawable.bg),
            contentDescription = null,
            modifier = Modifier.fillMaxSize(),
            contentScale = ContentScale.Crop
        )

        Text(
            text = "RANDOM FACT",
            fontFamily = myFontFamily,
            fontWeight = FontWeight.Bold,
            fontSize = 28.sp,
            color = Color.Black,
            modifier = Modifier
                .align(Alignment.TopCenter)
                .padding(top = 72.dp)
        )


        Column(
            modifier = Modifier.align(Alignment.Center),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Box(modifier = Modifier.padding(16.dp)) {
                Text(
                    text = response,
                    fontFamily = myFontFamily,
                    fontWeight = FontWeight.Normal,
                    fontSize = 16.sp,
                    color = Color.Black,
                    textAlign = TextAlign.Center,
                    modifier = Modifier
                        .background(
                            color = Color.White.copy(alpha = 0.85f),
                            shape = RoundedCornerShape(16.dp)
                        )
                        .border(1.dp, Color.Gray, RoundedCornerShape(16.dp))
                        .padding(16.dp)
                        .clickable(true) {
                            clipboardManager.nativeClipboard.setText(AnnotatedString(response))
                        }
                )
            }
        }

        // Get fact button
        Button(
            modifier = Modifier
                .align(Alignment.BottomCenter)
                .padding(8.dp, 206.dp),
            onClick = {
                scope.launch(Dispatchers.IO) {
                    if (unlocked) {
                        HttpClient.fetchFact { response = it }
                    } else {
                        var savedCoins = PreferenceDataStore.loadCoins(activity)
                        if (savedCoins > 0) {
                            savedCoins--
                            PreferenceDataStore.saveCoins(activity, savedCoins)
                            coins = savedCoins
                            HttpClient.fetchFact {
                                response = it
                            }
                        } else {
                            scope.launch(Dispatchers.Main) {
                                Toast.makeText(activity, "No more coins", Toast.LENGTH_SHORT).show()
                            }
                        }
                    }
                }
            },
            colors = ButtonDefaults.buttonColors(
                containerColor = orangeColor,
                contentColor = Color.White
            )
        ) {
            val factText = buildString {
                append("Get fact")
                if (!unlocked && coins > 0) {
                    append(" ($coins coin")
                    if (coins > 1) append("s")
                    append(")")
                }
            }
            Text(
                fontFamily = myFontFamily,
                fontWeight = FontWeight.Bold,
                text = factText

            )
        }

        if (!unlocked) {
            Column(
                modifier = Modifier
                    .align(Alignment.BottomCenter)
                    .padding(16.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Text(
                    color = Color.White,
                    text = Const.BOTTOM_TOOLTIP
                )

                Button(
                    modifier = Modifier.padding(16.dp),
                    onClick = { billingClient.init() },
                    colors = ButtonDefaults.buttonColors(
                        containerColor = greenColor,
                        contentColor = Color.White
                    )
                ) {
                    Text(
                        fontFamily = myFontFamily,
                        fontWeight = FontWeight.Bold,
                        text = "Get unlimited coins"
                    )
                }
            }
        }

    }
}
