package com.example.initiateaphonecallapp.ui.home


import android.content.Intent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Call
import androidx.compose.material.icons.filled.Phone
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.initiateaphonecallapp.data.model.CallRecord
import com.example.initiateaphonecallapp.manager.CallRecordManager
import com.example.initiateaphonecallapp.service.PhoneCallService
import com.example.initiateaphonecallapp.service.WebSocketService
import com.example.initiateaphonecallapp.ui.theme.InitiateAPhoneCallAppTheme


@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HomeScreen(
    authToken: String,
    viewModel: HomeViewModel = viewModel(),
    onLogout: () -> Unit = {},
    modifier: Modifier
) {
    val context = LocalContext.current
    val callRecords by viewModel.callRecords.collectAsState()
    val currentCall by viewModel.currentCall.collectAsState()
    val recentCall by viewModel.recentCall.collectAsState()
    val webSocketStatus by viewModel.webSocketStatus.collectAsState()
    val receivedMessages by viewModel.receivedMessages.collectAsState()
    val uploadStatus by viewModel.uploadStatus.collectAsState()
    val autoScanStatus by viewModel.autoScanStatus.collectAsState()

    // 启动服务
    LaunchedEffect(authToken) {
        println("🏠 HomeScreen: 启动服务，token: ${authToken.take(20)}...")

        val webSocketIntent = Intent(context, WebSocketService::class.java).apply {
            action = "CONNECT"
            putExtra("TOKEN", authToken)
        }
        context.startService(webSocketIntent)

        // 启动电话服务
        context.startService(Intent(context, PhoneCallService::class.java))

        println("🏠 HomeScreen: 服务启动完成")
    }

    InitiateAPhoneCallAppTheme {
        Scaffold(
            topBar = {
                TopAppBar(
                    title = { Text("电话呼叫系统") },
                    actions = {
                        IconButton(onClick = onLogout) {
                            Text("退出")
                        }
                    }
                )
            }
        ) { innerPadding ->
            LazyColumn(
                modifier = Modifier
                    .padding(innerPadding)
                    .fillMaxSize()
            ) {
                // WebSocket 状态显示
                item {
                    Card(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(16.dp)
                    ) {
                        Column(
                            modifier = Modifier.padding(16.dp)
                        ) {
                            Row(verticalAlignment = Alignment.CenterVertically) {
                                Box(
                                    modifier = Modifier
                                        .size(12.dp)
                                        .background(
                                            color = when (webSocketStatus) {
                                                WebSocketService.WebSocketStatus.CONNECTED -> androidx.compose.ui.graphics.Color.Green
                                                WebSocketService.WebSocketStatus.CONNECTING -> androidx.compose.ui.graphics.Color.Yellow
                                                else -> androidx.compose.ui.graphics.Color.Red
                                            },
                                            shape = androidx.compose.foundation.shape.CircleShape
                                        )
                                )
                                Spacer(modifier = Modifier.width(8.dp))
                                Text(
                                    text = when (webSocketStatus) {
                                        WebSocketService.WebSocketStatus.CONNECTED -> "WebSocket 已连接"
                                        WebSocketService.WebSocketStatus.CONNECTING -> "WebSocket 连接中"
                                        WebSocketService.WebSocketStatus.DISCONNECTED -> "WebSocket 未连接"
                                        WebSocketService.WebSocketStatus.ERROR -> "WebSocket 连接错误"
                                    },
                                    fontSize = 16.sp,
                                    fontWeight = FontWeight.Medium
                                )
                            }

                            Spacer(modifier = Modifier.height(8.dp))
                            Text(
                                text = "收到 ${receivedMessages.size} 条消息",
                                fontSize = 14.sp,
                                color = androidx.compose.ui.graphics.Color.Gray
                            )

                            Spacer(modifier = Modifier.height(12.dp))
                            Button(
                                onClick = { viewModel.reconnectWebSocket(authToken) },
                                modifier = Modifier.fillMaxWidth(),
                                colors = ButtonDefaults.buttonColors(
                                    containerColor = when (webSocketStatus) {
                                        WebSocketService.WebSocketStatus.CONNECTED -> androidx.compose.ui.graphics.Color.Green
                                        WebSocketService.WebSocketStatus.CONNECTING -> androidx.compose.ui.graphics.Color.Yellow
                                        else -> androidx.compose.ui.graphics.Color.Red
                                    }
                                )
                            ) {
                                Icon(
                                    imageVector = Icons.Default.Phone,
                                    contentDescription = "重连",
                                    modifier = Modifier.size(18.dp)
                                )
                                Spacer(modifier = Modifier.width(8.dp))
                                Text(
                                    text = when (webSocketStatus) {
                                        WebSocketService.WebSocketStatus.CONNECTED -> "连接正常"
                                        WebSocketService.WebSocketStatus.CONNECTING -> "连接中..."
                                        else -> "重连 WebSocket"
                                    },
                                    fontSize = 14.sp
                                )
                            }
                        }
                    }
                }

                // 自动扫描状态显示（调试用）
                if (autoScanStatus.isNotEmpty()) {
                    item {
                        Card(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(16.dp),
                            colors = CardDefaults.cardColors(
                                containerColor = androidx.compose.ui.graphics.Color(0xFFE3F2FD)
                            )
                        ) {
                            Column(
                                modifier = Modifier.padding(16.dp)
                            ) {
                                Text(
                                    text = "自动文件扫描状态",
                                    fontWeight = FontWeight.Bold,
                                    fontSize = 16.sp,
                                    color = androidx.compose.ui.graphics.Color.Blue
                                )
                                Spacer(modifier = Modifier.height(8.dp))
                                Text(autoScanStatus)


                            }
                        }
                    }
                }

                // 上传状态显示
                item {
                    when (uploadStatus) {
                        CallRecordManager.UploadStatus.UPLOADING -> {
                            Card(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(16.dp),
                                colors = CardDefaults.cardColors(
                                    containerColor = androidx.compose.ui.graphics.Color(0xFFE8F5E8)
                                )
                            ) {
                                Row(
                                    modifier = Modifier.padding(16.dp),
                                    verticalAlignment = Alignment.CenterVertically
                                ) {
                                    CircularProgressIndicator(
                                        modifier = Modifier.size(16.dp)
                                    )
                                    Spacer(modifier = Modifier.width(12.dp))
                                    Text(
                                        text = "正在自动上传通话记录...",
                                        color = androidx.compose.ui.graphics.Color.Blue,
                                        fontWeight = FontWeight.Medium
                                    )
                                }
                            }
                        }
                        CallRecordManager.UploadStatus.SUCCESS -> {
                            Card(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(16.dp),
                                colors = CardDefaults.cardColors(
                                    containerColor = androidx.compose.ui.graphics.Color(0xFFE8F5E8)
                                )
                            ) {
                                Row(
                                    modifier = Modifier.padding(16.dp),
                                    verticalAlignment = Alignment.CenterVertically
                                ) {
                                    Icon(
                                        imageVector = Icons.Default.Call,
                                        contentDescription = "成功",
                                        tint = androidx.compose.ui.graphics.Color.Green
                                    )
                                    Spacer(modifier = Modifier.width(12.dp))
                                    Text(
                                        text = "上传成功",
                                        color = androidx.compose.ui.graphics.Color.Green,
                                        fontWeight = FontWeight.Medium
                                    )
                                }
                            }
                        }
                        CallRecordManager.UploadStatus.FAILED -> {
                            Card(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(16.dp),
                                colors = CardDefaults.cardColors(
                                    containerColor = androidx.compose.ui.graphics.Color(0xFFFFEBEE)
                                )
                            ) {
                                Column(
                                    modifier = Modifier.padding(16.dp)
                                ) {
                                    Row(
                                        verticalAlignment = Alignment.CenterVertically
                                    ) {
                                        Icon(
                                            imageVector = Icons.Default.Call,
                                            contentDescription = "失败",
                                            tint = androidx.compose.ui.graphics.Color.Red
                                        )
                                        Spacer(modifier = Modifier.width(12.dp))
                                        Text(
                                            text = "上传失败",
                                            color = androidx.compose.ui.graphics.Color.Red,
                                            fontWeight = FontWeight.Medium
                                        )
                                    }
                                    Spacer(modifier = Modifier.height(8.dp))
                                    Text(
                                        text = "系统将自动重试，或您可以手动重新上传",
                                        fontSize = 14.sp,
                                        color = androidx.compose.ui.graphics.Color.Gray
                                    )
                                    Spacer(modifier = Modifier.height(8.dp))
                                    Button(
                                        onClick = { viewModel.manuallyUploadRecentCall() },
                                        modifier = Modifier.fillMaxWidth()
                                    ) {
                                        Text("重新上传")
                                    }
                                }
                            }
                        }
                        else -> {}
                    }
                }

                // 当前通话状态
                currentCall?.let { call ->
                    item {
                        Card(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(16.dp)
                        ) {
                            Column(
                                modifier = Modifier.padding(16.dp)
                            ) {
                                Text(
                                    text = "当前通话",
                                    fontWeight = FontWeight.Bold,
                                    fontSize = 18.sp,
                                    color = androidx.compose.ui.graphics.Color.Blue
                                )
                                Spacer(modifier = Modifier.height(8.dp))
                                Text("📞 号码: ${call.phoneNumber}")
                                Text("🕐 开始时间: ${call.formattedStartTime}")
                                Text("📍 状态: ${call.status}")

                                Spacer(modifier = Modifier.height(12.dp))
                                Button(
                                    onClick = {
                                        CallRecordManager.endCallRecord()
                                        println("📞 手动结束通话")
                                    },
                                    modifier = Modifier.fillMaxWidth(),
                                    colors = ButtonDefaults.buttonColors(
                                        containerColor = androidx.compose.ui.graphics.Color.Red
                                    )
                                ) {
                                    Text("结束通话")
                                }
                            }
                        }
                    }
                }

                // 最近通话记录
                recentCall?.let { call ->
                    item {
                        Card(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(16.dp),
                            colors = CardDefaults.cardColors(
                                containerColor = if (call.uploaded) androidx.compose.ui.graphics.Color(0xFFE8F5E8)
                                else androidx.compose.ui.graphics.Color(0xFFFFF8E1)
                            )
                        ) {
                            Column(
                                modifier = Modifier.padding(16.dp)
                            ) {
                                Text(
                                    text = "最近通话记录",
                                    fontWeight = FontWeight.Bold,
                                    fontSize = 18.sp,
                                    color = if (call.uploaded) androidx.compose.ui.graphics.Color.Green
                                    else androidx.compose.ui.graphics.Color(0xFFFF9800)
                                )
                                Spacer(modifier = Modifier.height(8.dp))
                                Text("📞 号码: ${call.phoneNumber}")
                                Text("🕐 开始时间: ${call.formattedStartTime}")
                                Text("🕐 结束时间: ${call.formattedEndTime}")
                                Text("⏱️ 时长: ${call.formattedDuration}")
                                Text("🎵 音频文件: ${call.audioFileName ?: "自动查找中..."}")
                                Text("📍 状态: ${call.status}")
                                Text(
                                    text = if (call.uploaded) "✅ 已上传" else "⏳ ${if (call.audioFileName != null) "准备上传" else "查找文件中"}",
                                    color = if (call.uploaded) androidx.compose.ui.graphics.Color.Green
                                    else androidx.compose.ui.graphics.Color(0xFFFF9800)
                                )

                                if (!call.uploaded && call.audioFileName != null) {
                                    Spacer(modifier = Modifier.height(8.dp))
                                    Button(
                                        onClick = { viewModel.manuallyUploadRecentCall() },
                                        modifier = Modifier.fillMaxWidth()
                                    ) {
                                        Text("手动上传")
                                    }
                                }

                                Spacer(modifier = Modifier.height(8.dp))
                                Button(
                                    onClick = { viewModel.clearRecentCall() },
                                    modifier = Modifier.fillMaxWidth(),
                                    colors = ButtonDefaults.buttonColors(
                                        containerColor = androidx.compose.ui.graphics.Color.Gray
                                    )
                                ) {
                                    Text("清除记录")
                                }
                            }
                        }
                    }
                }

                // 添加底部空间
                item {
                    Spacer(modifier = Modifier.height(32.dp))
                }
            }
        }
    }
}



@Composable
fun CallRecordItem(record: CallRecord) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 4.dp),
        colors = CardDefaults.cardColors(
            containerColor = if (record.uploaded) androidx.compose.ui.graphics.Color(0xFFE8F5E8)
            else androidx.compose.ui.graphics.Color(0xFFFFF3E0)
        )
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.SpaceBetween,
                modifier = Modifier.fillMaxWidth()
            ) {
                Text(
                    text = record.phoneNumber,
                    fontWeight = FontWeight.Bold,
                    fontSize = 16.sp,
                    color = androidx.compose.ui.graphics.Color.Black
                )

                // 上传状态指示器
                Row(
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Box(
                        modifier = Modifier
                            .size(8.dp)
                            .background(
                                color = if (record.uploaded) androidx.compose.ui.graphics.Color.Green
                                else androidx.compose.ui.graphics.Color.Red,
                                shape = androidx.compose.foundation.shape.CircleShape
                            )
                    )
                    Spacer(modifier = Modifier.width(4.dp))
                    Text(
                        text = if (record.uploaded) "已上传" else "未上传",
                        fontSize = 12.sp,
                        color = if (record.uploaded) androidx.compose.ui.graphics.Color.Green
                        else androidx.compose.ui.graphics.Color.Red
                    )
                }
            }

            Spacer(modifier = Modifier.height(8.dp))
            Text("📞 号码: ${record.phoneNumber}", fontSize = 14.sp)
            Text("🕐 开始: ${record.formattedStartTime}", fontSize = 14.sp)
            Text("🕐 结束: ${record.formattedEndTime}", fontSize = 14.sp)
            Text("⏱️ 时长: ${record.formattedDuration}", fontSize = 14.sp)
            Text("🎵 音频: ${record.audioFileName ?: "无"}", fontSize = 14.sp)
            Text("📍 状态: ${record.status}", fontSize = 14.sp)

            if (record.uploaded) {
                Text(
                    text = "✅ 上传成功",
                    fontSize = 12.sp,
                    color = androidx.compose.ui.graphics.Color.Green,
                    modifier = Modifier.padding(top = 4.dp)
                )
            }
        }
    }
}
