package com.telumall.app

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
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.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
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 coil.compose.AsyncImage
import com.telumall.app.ui.theme.TeluMallTheme
import org.json.JSONArray
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLEncoder

data class TeluProduct(
val id: Int,
val name: String,
val price: String,
val regularPrice: String,
val imageUrl: String,
val sku: String,
val description: String
)

class MainActivity : ComponentActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    setContent {
        TeluMallTheme {
            TeluMallHome()
        }
    }
}

}

@Composable
fun TeluMallHome() {

var searchText by rememberSaveable {
    mutableStateOf("")
}

var products by remember {
    mutableStateOf<List<TeluProduct>>(emptyList())
}

var isLoading by remember {
    mutableStateOf(false)
}

var cartMessage by remember {
    mutableStateOf("")
}
val context = LocalContext.current

var errorMessage by remember {
    mutableStateOf("")
}

var selectedProduct by remember {
    mutableStateOf<TeluProduct?>(null)
}

fun loadProducts(search: String = "") {

    isLoading = true
    errorMessage = ""

    Thread {

        try {

            val encodedSearch =
                URLEncoder.encode(search, "UTF-8")

            val apiUrl =
                if (search.isBlank()) {
                    "https://telumall.com/wp-json/wc/store/v1/products?per_page=20"
                } else {
                    "https://telumall.com/wp-json/wc/store/v1/products?per_page=20&search=$encodedSearch"
                }

            val connection =
                URL(apiUrl).openConnection() as HttpURLConnection

            connection.requestMethod = "GET"
            connection.connectTimeout = 15000
            connection.readTimeout = 15000

            val responseCode =
                connection.responseCode

            if (responseCode == 200) {

                val response =
                    connection.inputStream
                        .bufferedReader()
                        .use {
                            it.readText()
                        }

                val jsonArray =
                    JSONArray(response)

                val productList =
                    mutableListOf<TeluProduct>()

                for (i in 0 until jsonArray.length()) {

                    val product =
                        jsonArray.getJSONObject(i)

                    val id =
                        product.optInt("id")

                    val name =
                        product.optString("name")

                    val sku =
                        product.optString("sku")

                    val prices =
                        product.optJSONObject("prices")

                    val rawPrice =
                        prices?.optString("price") ?: ""

                    val rawRegularPrice =
                        prices?.optString("regular_price") ?: ""

                    val minorUnit =
                        prices?.optInt(
                            "currency_minor_unit",
                            2
                        ) ?: 2

                    val price =
                        if (rawPrice.isNotEmpty()) {
                            formatPrice(
                                rawPrice,
                                minorUnit
                            )
                        } else {
                            ""
                        }

                    val regularPrice =
                        if (rawRegularPrice.isNotEmpty()) {
                            formatPrice(
                                rawRegularPrice,
                                minorUnit
                            )
                        } else {
                            ""
                        }

                    val images =
                        product.optJSONArray("images")

                    val imageUrl =
                        if (
                            images != null &&
                            images.length() > 0
                        ) {
                            images
                                .getJSONObject(0)
                                .optString("src")
                        } else {
                            ""
                        }

                    val description =
                        stripHtml(
                            product.optString(
                                "short_description"
                            )
                        )

                    productList.add(
                        TeluProduct(
                            id = id,
                            name = stripHtml(name),
                            price = price,
                            regularPrice = regularPrice,
                            imageUrl = imageUrl,
                            sku = sku,
                            description = description
                        )
                    )
                }

                Handler(
                    Looper.getMainLooper()
                ).post {

                    products = productList
                    isLoading = false
                    errorMessage = ""
                }

            } else {

                Handler(
                    Looper.getMainLooper()
                ).post {

                    products = emptyList()
                    isLoading = false
                    errorMessage =
                        "Products load కాలేదు"
                }
            }

            connection.disconnect()

        } catch (e: Exception) {

            Handler(
                Looper.getMainLooper()
            ).post {

                products = emptyList()
                isLoading = false
                errorMessage =
                    "Internet connection check చేయండి"
            }
        }

    }.start()
}

LaunchedEffect(searchText) {
    loadProducts(searchText)
}

if (selectedProduct != null) {
    ProductDetailsScreen(
        product = selectedProduct!!,
        onBack = {
            selectedProduct = null
            cartMessage = ""
        },
        cartMessage = cartMessage,
        onAddToCart = {
            val addUrl = "https://telumall.com/?add-to-cart=${selectedProduct!!.id}"
            context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(addUrl)))
            cartMessage = "వెబ్‌సైట్‌లో Add to Cart తెరవబడింది."
        },
        onBuyNow = {
            val checkoutUrl = "https://telumall.com/checkout/?add-to-cart=${selectedProduct!!.id}"
            context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(checkoutUrl)))
        },
        onOpenCart = {
            context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://telumall.com/cart/")))
        }
    )
} else {
    LazyColumn(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.White)
            .padding(16.dp)
    ) {
        item {
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                AsyncImage(
                    model = "https://telumall.com/wp-content/uploads/2026/09/telumall_logo.png",
                    contentDescription = "TeluMall Logo",
                    modifier = Modifier
                        .width(155.dp)
                        .height(65.dp),
                    contentScale = ContentScale.Fit
                )

                Row(verticalAlignment = Alignment.CenterVertically) {
                    Text(
                        text = "🛒",
                        fontSize = 25.sp,
                        modifier = Modifier
                            .clickable {
                                context.startActivity(
                                    Intent(
                                        Intent.ACTION_VIEW,
                                        Uri.parse("https://telumall.com/cart/")
                                    )
                                )
                            }
                            .padding(6.dp)
                    )
                    Spacer(modifier = Modifier.width(14.dp))
                    Text(
                        text = "👤",
                        fontSize = 25.sp,
                        modifier = Modifier
                            .clickable {
                                context.startActivity(
                                    Intent(
                                        Intent.ACTION_VIEW,
                                        Uri.parse("https://telumall.com/my-account/")
                                    )
                                )
                            }
                            .padding(6.dp)
                    )
                }
            }

            Spacer(modifier = Modifier.height(8.dp))

            OutlinedTextField(
                value = searchText,
                onValueChange = { searchText = it },
                modifier = Modifier.fillMaxWidth(),
                placeholder = { Text(text = "Search products...") },
                singleLine = true
            )

            Spacer(modifier = Modifier.height(8.dp))

            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .clickable {
                        context.startActivity(
                            Intent(
                                Intent.ACTION_VIEW,
                                Uri.parse("https://telumall.com/track-my-order/")
                            )
                        )
                    },
                shape = RoundedCornerShape(12.dp),
                colors = CardDefaults.cardColors(
                    containerColor = Color(232, 239, 255)
                )
            ) {
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 14.dp, vertical = 12.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(text = "📦", fontSize = 23.sp)
                    Spacer(modifier = Modifier.width(10.dp))
                    Column(modifier = Modifier.weight(1f)) {
                        Text(
                            text = "Track My Order",
                            fontSize = 15.sp,
                            fontWeight = FontWeight.Bold,
                            color = Color(20, 45, 100)
                        )
                        Text(
                            text = "ఆర్డర్ స్థితి తెలుసుకోండి",
                            fontSize = 12.sp,
                            color = Color.DarkGray
                        )
                    }
                    Text(text = "›", fontSize = 25.sp, color = Color(20, 45, 100))
                }
            }

            Spacer(modifier = Modifier.height(14.dp))

            Text(
                text = "TeluMall Products",
                fontSize = 17.sp,
                fontWeight = FontWeight.Bold,
                color = Color(20, 45, 100)
            )

            Spacer(modifier = Modifier.height(10.dp))
        }

        if (isLoading) {
            item {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(30.dp),
                    contentAlignment = Alignment.Center
                ) {
                    CircularProgressIndicator()
                }
            }
        } else if (errorMessage.isNotEmpty()) {
            item {
                Text(
                    text = errorMessage,
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(30.dp),
                    textAlign = TextAlign.Center,
                    color = Color.Red
                )
            }
        } else if (products.isEmpty()) {
            item {
                Text(
                    text = "Products లేవు",
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(30.dp),
                    textAlign = TextAlign.Center,
                    color = Color.Gray
                )
            }
        } else {
            items(products) { product ->
                LiveProductCard(
                    product = product,
                    onClick = { selectedProduct = product }
                )
                Spacer(modifier = Modifier.height(10.dp))
            }
        }
    }
}

}

@Composable
fun LiveProductCard(
product: TeluProduct,
onClick: () -> Unit
) {

Card(
    onClick = onClick,
    modifier =
        Modifier.fillMaxWidth(),
    shape =
        RoundedCornerShape(14.dp),
    colors =
        CardDefaults.cardColors(
            containerColor =
                Color(248, 248, 248)
        )
) {

    Row(
        modifier =
            Modifier
                .fillMaxWidth()
                .padding(8.dp),
        verticalAlignment =
            Alignment.CenterVertically
    ) {

        AsyncImage(
            model = product.imageUrl,
            contentDescription =
                product.name,
            modifier =
                Modifier.size(90.dp),
            contentScale =
                ContentScale.Crop
        )

        Spacer(
            modifier =
                Modifier.width(10.dp)
        )

        Column(
            modifier =
                Modifier.weight(1f)
        ) {

            Text(
                text = product.name,
                fontSize = 13.sp,
                fontWeight =
                    FontWeight.Medium,
                maxLines = 2
            )

            Spacer(
                modifier =
                    Modifier.height(4.dp)
            )

            Text(
                text = product.price,
                fontSize = 15.sp,
                fontWeight =
                    FontWeight.Bold,
                color =
                    Color(20, 45, 100)
            )

            if (
                product.sku.isNotBlank()
            ) {

                Text(
                    text =
                        "SKU: ${product.sku}",
                    fontSize = 10.sp,
                    color =
                        Color.Gray
                )
            }
        }
    }
}

}

@Composable
fun ProductDetailsScreen(
product: TeluProduct,
onBack: () -> Unit,
cartMessage: String,
onAddToCart: () -> Unit,
onBuyNow: () -> Unit,
onOpenCart: () -> Unit
) {

Column(
    modifier =
        Modifier
            .fillMaxSize()
            .background(Color.White)
            .padding(16.dp)
) {

    Row(
        modifier = Modifier.fillMaxWidth().padding(bottom = 12.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(
            text = "←  Back",
            fontSize = 17.sp,
            fontWeight = FontWeight.Bold,
            color = Color(20, 45, 100),
            modifier = Modifier.clickable { onBack() }
        )
        Spacer(modifier = Modifier.weight(1f))
        Text(
            text = "🛒",
            fontSize = 25.sp,
            modifier = Modifier
                .clickable { onOpenCart() }
                .padding(6.dp)
        )
    }

    Card(
        shape =
            RoundedCornerShape(18.dp),
        colors =
            CardDefaults.cardColors(
                containerColor =
                    Color(248, 248, 248)
            ),
        modifier =
            Modifier.fillMaxWidth()
    ) {

        AsyncImage(
            model = product.imageUrl,
            contentDescription =
                product.name,
            modifier =
                Modifier
                    .fillMaxWidth()
                    .height(300.dp),
            contentScale =
                ContentScale.Fit
        )
    }

    Spacer(
        modifier =
            Modifier.height(18.dp)
    )

    Text(
        text = product.name,
        fontSize = 20.sp,
        fontWeight =
            FontWeight.Bold
    )

    Spacer(
        modifier =
            Modifier.height(10.dp)
    )

    Text(
        text = product.price,
        fontSize = 22.sp,
        fontWeight =
            FontWeight.Bold,
        color =
            Color(20, 45, 100)
    )

    if (
        product.regularPrice.isNotBlank() &&
        product.regularPrice != product.price
    ) {

        Spacer(
            modifier =
                Modifier.height(4.dp)
        )

        Text(
            text =
                "MRP: ${product.regularPrice}",
            fontSize = 14.sp,
            color =
                Color.Gray
        )
    }

    if (
        product.sku.isNotBlank()
    ) {

        Spacer(
            modifier =
                Modifier.height(8.dp)
        )

        Text(
            text =
                "SKU: ${product.sku}",
            fontSize = 12.sp,
            color =
                Color.Gray
        )
    }

    Spacer(
        modifier =
            Modifier.height(18.dp)
    )

    if (
        product.description.isNotBlank()
    ) {

        Text(
            text = "Description",
            fontSize = 17.sp,
            fontWeight =
                FontWeight.Bold
        )

        Spacer(
            modifier =
                Modifier.height(6.dp)
        )

        Text(
            text =
                product.description,
            fontSize = 14.sp,
            color =
                Color.DarkGray
        )
    }

    Spacer(
        modifier =
            Modifier.height(25.dp)
    )

    Card(
        modifier =
            Modifier.fillMaxWidth(),
        shape =
            RoundedCornerShape(14.dp),
        colors =
            CardDefaults.cardColors(
                containerColor =
                    Color(20, 45, 100)
            ),
        onClick = {
            onAddToCart()
        }
    ) {

        Text(
            text = "🛒  Add to Cart",
            modifier =
                Modifier
                    .fillMaxWidth()
                    .padding(16.dp),
            textAlign =
                TextAlign.Center,
            fontSize = 17.sp,
            fontWeight =
                FontWeight.Bold,
            color = Color.White
        )
    }
    if (cartMessage.isNotEmpty()) {
        Text(
            text = cartMessage,
            color = Color(0, 128, 0),
            fontSize = 14.sp,
            modifier = Modifier.padding(top = 12.dp)
        )
    }

    Spacer(modifier = Modifier.height(10.dp))

    Card(
        modifier = Modifier
            .fillMaxWidth()
            .clickable { onBuyNow() },
        shape = RoundedCornerShape(14.dp),
        colors = CardDefaults.cardColors(
            containerColor = Color(0, 128, 72)
        )
    ) {
        Text(
            text = "⚡  Buy Now  /  ఇప్పుడే కొనండి",
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            textAlign = TextAlign.Center,
            fontSize = 16.sp,
            fontWeight = FontWeight.Bold,
            color = Color.White
        )
    }
    Spacer(modifier = Modifier.height(12.dp))
    Text(
        text = "Add to Cart మరియు Buy Now ద్వారా TeluMall వెబ్‌సైట్ తెరుచుకుంటుంది; అక్కడే నిజమైన కార్ట్/చెక్అవుట్ పూర్తి చేయండి.",
        fontSize = 12.sp,
        color = Color.DarkGray
    )
}

}

fun formatPrice(
rawPrice: String,
minorUnit: Int
): String {

return try {

    val value =
        rawPrice.toLong()

    val divisor =
        Math.pow(
            10.0,
            minorUnit.toDouble()
        )

    val finalPrice =
        value / divisor

    "₹%.0f".format(finalPrice)

} catch (e: Exception) {

    rawPrice
}

}

fun stripHtml(
text: String
): String {

return text
    .replace(
        Regex("<[^>]*>"),
        ""
    )
    .replace(
        "&",
        "&"
    )
    .replace(
        "'",
        "'"
    )
    .replace(
        """,
        "\""
    )
    .trim()

}

Shopping Cart
0
0
Your Cart
Empty CartYour cart is emptyReturn to Shop
Secure Checkout
Fast Shipping
Easy Returns
Scroll to Top
Track My Order