package ui

import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.*
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.Card
import androidx.compose.material.Divider
import androidx.compose.material.MaterialTheme
import androidx.compose.material.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.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.launch
import model.KisSession
import model.RealTimeTrade
import network.AiService

@Composable
fun AiAnalysisView(stockName: String, currentPrice: String, trades: List<model.RealTimeTrade>) {
    var aiOpinion by remember { mutableStateOf("분석 대기 중...") }
    var isLoading by remember { mutableStateOf(false) }
    val scope = rememberCoroutineScope()

    // KisSession의 전역 설정을 참조
    val isModelConfigured = remember(KisSession.config.modelPath) {
        val path = KisSession.config.modelPath
        path.isNotEmpty() && java.io.File(path).exists()
    }

    Card(
        elevation = 2.dp,
        backgroundColor = if (isModelConfigured) Color(0xFFF1F3F4) else Color(0xFFFFEBEE),
        modifier = Modifier.fillMaxWidth()
    ) {
        Column(modifier = Modifier.padding(12.dp)) {
            Row(verticalAlignment = Alignment.CenterVertically) {
                Text(
                    text = if (isModelConfigured) "🤖 AI 투자 전략" else "⚠️ AI 설정 필요",
                    fontWeight = FontWeight.Bold,
                    color = if (isModelConfigured) Color(0xFF1A73E8) else Color.Red
                )
                Spacer(Modifier.weight(1f))
                Button(
                    onClick = {
                        scope.launch {
                            isLoading = true
                            aiOpinion = "데이터 분석 중..."
                            aiOpinion = network.AiService.fetchAnalysis(stockName, currentPrice, trades)
                            isLoading = false
                        }
                    },
                    enabled = isModelConfigured && !isLoading
                ) {
                    Text(if (isLoading) "분석 중" else "분석 실행", fontSize = 11.sp)
                }
            }
            Divider(Modifier.padding(vertical = 8.dp))
            Text(text = aiOpinion, style = MaterialTheme.typography.body2)
        }
    }
}