package ui

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Button
import androidx.compose.material.Card
import androidx.compose.material.CircularProgressIndicator
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 kotlinx.coroutines.launch
import model.KisSession
import service.AutoTradingManager

@Composable
fun AiAnalysisView(stockCode:String,stockName: String, currentPrice: String, trades: List<model.RealTimeTrade>) {
    var aiOpinion by remember { mutableStateOf("분석 대기 중...") }
    var code by remember(stockCode) {
        aiOpinion = ""
        mutableStateOf(stockCode.isNotEmpty())
    }
    var isAnalyzing 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
            .fillMaxHeight()
            .fillMaxWidth()
            .verticalScroll(rememberScrollState()) // 스크롤 활성화
            .padding(16.dp)
            .background(Color(0xFFF5F5F5), RoundedCornerShape(8.dp))) {
            Row(verticalAlignment = Alignment.CenterVertically) {
                Text(
                    text = if (isModelConfigured) "${stockName} AI 투자 전략" else "⚠️ AI 설정 필요",
                    fontWeight = FontWeight.Bold,
                    color = if (isModelConfigured) Color(0xFF1A73E8) else Color.Red
                )
                Spacer(Modifier.weight(1f))
                Button(
                    onClick = {
                        scope.launch {
                            isAnalyzing = true
                            try {
                                AutoTradingManager.addStock(stockCode) { msg,success ->
                                    aiOpinion = msg
                                    isAnalyzing = !success
                                }
                                // 실시간 데이터 수집부터 분석까지 한 번에 실행
//                                StockAnalysisManager.analyzeStockWithMultiData(
//                                    stockCode = stockCode,
//                                    stockName = stockName,
//                                    result =  {
//                                        aiOpinion = it
//                                    }
//                                )
                            } catch (e: Exception) {
                                aiOpinion = "분석 중 오류 발생: ${e.message}"
                                println(aiOpinion)
                                isAnalyzing = false
                            } finally {
//                                isAnalyzing = false
                            }
                        }
                    },
                    enabled = !isAnalyzing && code
                ) {
                    if (isAnalyzing) {
                        CircularProgressIndicator(modifier = Modifier.size(20.dp), color = Color.White)
                        Spacer(Modifier.width(8.dp))
                        Text("뉴스 분석 중...")
                    } else {
                        Text("분석 요청")
                    }
                }
            }
            Divider(Modifier.padding(vertical = 8.dp))
            Text(text = aiOpinion, style = MaterialTheme.typography.body2)
        }
    }
}