package com.hx.chathx

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.hx.chathx.ui.theme.ChatHXTheme

class MainActivity : ComponentActivity() {

    private val gson = Gson()
    private val client = OkHttpClient.Builder()
        .readTimeout(30, TimeUnit.SECONDS)
        .connectTimeout(30, TimeUnit.SECONDS)
        .build()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            ChatHXTheme { // Use the app's theme
                ChatScreen()
            }
        }
    }
}

@Composable
fun ChatScreen() {
    val messages = remember { mutableStateListOf<ChatMessage>() }
    var userInput by remember { mutableStateOf("") }
    val isLoading = remember { mutableStateOf(false) }

    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Bottom
    ) {
        // Chat Message Area
        LazyColumn(
            modifier = Modifier
                .fillMaxWidth()
                .weight(1f),
            contentPadding = PaddingValues(16.dp)
        ) {
            items(messages) { message ->
                MessageCard(message)
            }
        }

        // User Input Area
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            OutlinedTextField(
                value = userInput,
                onValueChange = { userInput = it },
                label = { Text("Type your question...") },
                modifier = Modifier
                    .weight(1f)
                    .padding(end = 8.dp)
            )

            Button(
                onClick = {
                    sendMessage(userInput, messages, isLoading)
                    userInput = "" // Clear input after sending
                },
                modifier = Modifier.wrapContentSize(),
                enabled = !isLoading.value  // Disable button while loading
            ) {
                if (isLoading.value) {
                    CircularProgressIndicator(color = Color.White)
                } else {
                    Text("Send")
                }
            }
        }
    }
}

@Composable
fun MessageCard(message: ChatMessage) {
    // Different layout for user and AI messages
    if (message.isUser) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(8.dp),
            horizontalArrangement = Arrangement.End
        ) {
            Text(
                text = message.text,
                color = Color.White,
                fontWeight = FontWeight.Bold,
                modifier = Modifier
                    .padding(8.dp)
                    .background(Color.Blue) // Example user message color
            )
        }
    } else {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(8.dp),
            horizontalArrangement = Arrangement.Start
        ) {
            Text(
                text = message.text,
                color = Color.Black,
                fontWeight = FontWeight.Bold,
                modifier = Modifier
                    .padding(8.dp)
                    .background(Color.LightGray) // Example AI message color
            )
        }
    }
}

data class ChatMessage(val text: String, val isUser: Boolean)

// Function to send message to your Flask server
fun sendMessage(
    message: String,
    messages: MutableList<ChatMessage>,
    isLoading: MutableState<Boolean>
) {
    messages.add(ChatMessage(message, true))
    isLoading.value = true

    val url = "http://10.0.2.2:5000/api/chat" // Update with your Flask server URL
    val requestBody = RequestBody.create(
        MediaType.parse("application/json"),
        gson.toJson(mapOf("message" to message))
    )
    val request = Request.Builder()
        .url(url)
        .post(requestBody)
        .build()

    client.newCall(request).enqueue(object : Callback {
        override fun onFailure(call: Call, e: IOException) {
            Log.e("ChatHX", "Network error: ${e.message}", e)
            isLoading.value = false
        }

        override fun onResponse(call: Call, response: Response) {
            isLoading.value = false
            if (response.isSuccessful) {
                try {
                    val responseBody = response.body()?.string()
                    if (responseBody != null) {
                        val responseJson: JsonElement = gson.fromJson(responseBody, JsonElement::class.java)
                        val answer = responseJson.asJsonObject.get("answer").asString
                        val questions = responseJson.asJsonObject.get("follow_up_questions").asJsonArray

                        // Add AI's response
                        messages.add(ChatMessage(answer, false))

                        // Add follow-up questions
                        for (question in questions) {
                            messages.add(ChatMessage(question.asString, false))
                        }
                    } else {
                        Log.e("ChatHX", "Empty response body")
                    }
                } catch (e: Exception) {
                    Log.e("ChatHX", "Error parsing response: ${e.message}", e)
                }
            } else {
                Log.e("ChatHX", "Server error: ${response.code}")
            }
        }
    })
}

@Composable
fun ChatHXTheme(content: @Composable () -> Unit) {
    MaterialTheme(
        colors = darkColors( // Use dark colors as per your screenshot
            primary = Color(0xFF1976D2), // Example primary color, customize as needed
            surface = Color(0xFF121212)  // Example surface color
        )
    ) {
        content()
    }
}