// ui/pipeline/PipelineScreen.kt
package com.example.initiateaphonecallapp.ui.pipeline

import android.content.Context
import android.content.Intent
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Phone
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.initiateaphonecallapp.data.model.PipelineResponse
import com.example.initiateaphonecallapp.service.PhoneCallService

@Composable
fun PipelineScreen(modifier: Modifier = Modifier) {
    val viewModel: PipelineViewModel = viewModel()
    val pipelines by viewModel.pipelines.collectAsState()
    val isLoading by viewModel.isLoading.collectAsState()
    val errorMessage by viewModel.errorMessage.collectAsState()
    val isAutoDialing by viewModel.isAutoDialing.collectAsState()
    val currentDialingIndex by viewModel.currentDialingIndex.collectAsState()
    val context = LocalContext.current

    // 获取可拨打的管道列表
    val dialablePipelines = pipelines.filter { it.status == 0 || it.status == 1 }

    // 处理生命周期
    LaunchedEffect(key1 = context) {
        viewModel.registerAutoDialReceiver(context)
    }

    DisposableEffect(key1 = context) {
        onDispose {
            viewModel.unregisterAutoDialReceiver(context)
        }
    }

    // 处理错误消息
    if (errorMessage != null) {
        AlertDialog(
            onDismissRequest = { viewModel.clearError() },
            title = { Text("错误") },
            text = { Text(errorMessage!!) },
            confirmButton = {
                TextButton(onClick = { viewModel.clearError() }) {
                    Text("确定")
                }
            }
        )
    }

    Column(
        modifier = modifier
            .fillMaxSize()
            .padding(16.dp)
    ) {
        // 标题和刷新按钮
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = "客户管道",
                style = MaterialTheme.typography.headlineMedium,
                fontWeight = FontWeight.Bold
            )

            IconButton(
                onClick = { viewModel.loadPipelines() },
                enabled = !isLoading
            ) {
                Icon(
                    imageVector = Icons.Default.Refresh,
                    contentDescription = "刷新"
                )
            }
        }

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

        // 自动拨号控制面板 - 使用可拨打的管道数量
        AutoDialControlPanel(
            isAutoDialing = isAutoDialing,
            currentIndex = currentDialingIndex,
            totalCount = dialablePipelines.size, // 使用可拨打的管道数量
            onStartAutoDial = {
                if (dialablePipelines.isNotEmpty()) {
                    viewModel.startAutoDial()
                    startAutoDial(context, ArrayList(dialablePipelines))
                }
            },
            onStopAutoDial = {
                viewModel.stopAutoDial()
                stopAutoDial(context)
            },
            modifier = Modifier.fillMaxWidth()
        )

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

        if (isLoading) {
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.Center
            ) {
                CircularProgressIndicator()
            }
        } else if (pipelines.isEmpty()) {
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.Center
            ) {
                Text("暂无客户数据")
            }
        } else {
            // 显示统计信息
            Text(
                text = "总计: ${pipelines.size} 个客户，可拨打: ${dialablePipelines.size} 个",
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )

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

            // 管道列表
            LazyColumn(
                modifier = Modifier.fillMaxSize(),
                verticalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                items(pipelines) { pipeline ->
                    PipelineItem(
                        pipeline = pipeline,
                        isCurrentDialing = isAutoDialing &&
                                dialablePipelines.getOrNull(currentDialingIndex)?.id == pipeline.id,
                        onCallClick = {
                            // 修改：手动拨号后继续自动拨号
                            initiatePhoneCallAndContinueAutoDial(
                                context = context,
                                viewModel = viewModel,
                                pipeline = pipeline,
                                dialablePipelines = dialablePipelines
                            )
                        },
                        onStatusChange = { newStatus ->
                            viewModel.updatePipelineStatus(pipeline.id, newStatus)
                        }
                    )
                }
            }
        }
    }
}

@Composable
fun AutoDialControlPanel(
    isAutoDialing: Boolean,
    currentIndex: Int,
    totalCount: Int,
    onStartAutoDial: () -> Unit,
    onStopAutoDial: () -> Unit,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier,
        colors = CardDefaults.cardColors(
            containerColor = if (isAutoDialing) Color(0xFFFFF8E1) else Color(0xFFF5F5F5)
        )
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Column {
                    Text(
                        text = if (isAutoDialing) "自动拨号进行中" else "自动拨号",
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.Bold
                    )
                    if (isAutoDialing) {
                        Text(
                            text = "进度: ${currentIndex + 1}/$totalCount",
                            style = MaterialTheme.typography.bodyMedium,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    } else {
                        Text(
                            text = "每10秒自动拨打下一个",
                            style = MaterialTheme.typography.bodyMedium,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                }

                if (isAutoDialing) {
                    FilledTonalButton(
                        onClick = onStopAutoDial,
                        colors = ButtonDefaults.filledTonalButtonColors(
                            containerColor = Color(0xFFF44336)
                        )
                    ) {
                        Icon(
                            imageVector = Icons.Default.Close,
                            contentDescription = "停止自动拨号",
                            modifier = Modifier.size(18.dp)
                        )
                        Spacer(modifier = Modifier.width(8.dp))
                        Text("停止")
                    }
                } else {
                    FilledTonalButton(
                        onClick = onStartAutoDial,
                        colors = ButtonDefaults.filledTonalButtonColors(
                            containerColor = Color(0xFF4CAF50)
                        )
                    ) {
                        Icon(
                            imageVector = Icons.Default.PlayArrow,
                            contentDescription = "开始自动拨号",
                            modifier = Modifier.size(18.dp)
                        )
                        Spacer(modifier = Modifier.width(8.dp))
                        Text("开始自动拨号")
                    }
                }
            }

            if (isAutoDialing) {
                Spacer(modifier = Modifier.height(8.dp))
                LinearProgressIndicator(
                    progress = if (totalCount > 0) (currentIndex + 1).toFloat() / totalCount else 0f,
                    modifier = Modifier.fillMaxWidth(),
                    color = Color(0xFF4CAF50)
                )
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PipelineItem(
    pipeline: PipelineResponse,
    isCurrentDialing: Boolean = false,
    onCallClick: () -> Unit,
    onStatusChange: (Int) -> Unit
) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp),
        colors = if (isCurrentDialing) {
            CardDefaults.cardColors(containerColor = Color(0xFFE8F5E8))
        } else {
            CardDefaults.cardColors()
        }
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            // 客户信息和电话按钮
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Column {
                    Text(
                        text = pipeline.name,
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.Bold
                    )
                    Spacer(modifier = Modifier.height(4.dp))
                    Text(
                        text = pipeline.phone,
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                    Spacer(modifier = Modifier.height(4.dp))
                    // 显示状态
                    StatusBadge(status = pipeline.status)
                }

                // 拨打电话按钮
                FilledTonalButton(
                    onClick = onCallClick,
                    colors = ButtonDefaults.filledTonalButtonColors(
                        containerColor = Color(0xFF4CAF50)
                    )
                ) {
                    Icon(
                        imageVector = Icons.Default.Phone,
                        contentDescription = "拨打电话",
                        modifier = Modifier.size(18.dp)
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text("从此处拨打")
                }
            }

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

//            // 状态选择器
//            StatusSelector(
//                currentStatus = pipeline.status,
//                onStatusChange = onStatusChange
//            )
        }
    }
}

// 状态徽章组件
@Composable
fun StatusBadge(status: Int) {
    val (text, color) = when (status) {
        0 -> Pair("未联系", Color(0xFFFF5722)) // 橙色
        1 -> Pair("未接通", Color(0xFF2196F3)) // 蓝色
        else -> Pair("已接通", Color(0xFF757575))
    }

    Surface(
        shape = MaterialTheme.shapes.small,
        color = color.copy(alpha = 0.1f),
        border = BorderStroke(1.dp, color.copy(alpha = 0.3f))
    ) {
        Text(
            text = text,
            style = MaterialTheme.typography.labelSmall,
            color = color,
            modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp)
        )
    }
}

// 状态选择器组件
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun StatusSelector(
    currentStatus: Int,
    onStatusChange: (Int) -> Unit
) {
    var expanded by remember { mutableStateOf(false) }

    val statusOptions = listOf(
        "未联系" to 0,
        "未接通" to 1,
        "已接通" to 2,
        "已预约" to 3,
        "已成交" to 4
    )

    val currentStatusText = statusOptions.find { it.second == currentStatus }?.first ?: "未知状态"

    Box(
        modifier = Modifier.fillMaxWidth()
    ) {
        ExposedDropdownMenuBox(
            expanded = expanded,
            onExpandedChange = { expanded = !expanded }
        ) {
            OutlinedTextField(
                value = currentStatusText,
                onValueChange = {},
                readOnly = true,
                trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) },
                modifier = Modifier
                    .fillMaxWidth()
                    .menuAnchor(),
                label = { Text("更新状态") },
                colors = ExposedDropdownMenuDefaults.outlinedTextFieldColors()
            )

            ExposedDropdownMenu(
                expanded = expanded,
                onDismissRequest = { expanded = false }
            ) {
                statusOptions.forEach { (text, value) ->
                    DropdownMenuItem(
                        text = { Text(text) },
                        onClick = {
                            onStatusChange(value)
                            expanded = false
                        }
                    )
                }
            }
        }
    }
}

// 拨打电话的函数
private fun initiatePhoneCall(context: Context, phoneNumber: String, pipelineId: String) {
    val intent = Intent(context, PhoneCallService::class.java).apply {
        action = "ACTION_INITIATE_CALL"
        putExtra("PHONE_NUMBER", phoneNumber)
        putExtra("PIPELINE_ID", pipelineId)
    }
    context.startService(intent)
}

// 新增：手动拨号后继续自动拨号的函数
private fun initiatePhoneCallAndContinueAutoDial(
    context: Context,
    viewModel: PipelineViewModel,
    pipeline: PipelineResponse,
    dialablePipelines: List<PipelineResponse>
) {
    // 先拨打当前电话
    initiatePhoneCall(context, pipeline.phone, pipeline.id)

    // 找到当前管道在可拨打列表中的位置
    val currentIndex = dialablePipelines.indexOfFirst { it.id == pipeline.id }
    if (currentIndex != -1) {
        // 如果当前不是自动拨号状态，则启动自动拨号
        if (!viewModel.isAutoDialing.value) {
            viewModel.startAutoDial()
            viewModel.updateDialingIndex(currentIndex)
            startAutoDialFromCurrent(context, ArrayList(dialablePipelines), currentIndex)
        } else {
            // 如果已经是自动拨号状态，则更新当前索引
            viewModel.updateDialingIndex(currentIndex)
            // 通知服务更新当前索引
            updateAutoDialIndex(context, ArrayList(dialablePipelines), currentIndex)
        }
    }
}

// 新增：从指定位置开始自动拨号
private fun startAutoDialFromCurrent(
    context: Context,
    pipelineList: ArrayList<PipelineResponse>,
    startIndex: Int
) {
    val intent = Intent(context, PhoneCallService::class.java).apply {
        action = "ACTION_START_AUTO_DIAL_FROM_CURRENT"
        putExtra("PIPELINE_LIST", pipelineList)
        putExtra("START_INDEX", startIndex)
    }
    context.startService(intent)
}

// 新增：更新自动拨号索引
private fun updateAutoDialIndex(
    context: Context,
    pipelineList: ArrayList<PipelineResponse>,
    currentIndex: Int
) {
    val intent = Intent(context, PhoneCallService::class.java).apply {
        action = "ACTION_UPDATE_DIAL_INDEX"
        putExtra("PIPELINE_LIST", pipelineList)
        putExtra("CURRENT_INDEX", currentIndex)
    }
    context.startService(intent)
}

// 开始自动拨号
private fun startAutoDial(context: Context, pipelineList: ArrayList<PipelineResponse>) {
    val intent = Intent(context, PhoneCallService::class.java).apply {
        action = "ACTION_START_AUTO_DIAL"
        putExtra("PIPELINE_LIST", pipelineList)
    }
    context.startService(intent)
}

// 停止自动拨号
private fun stopAutoDial(context: Context) {
    val intent = Intent(context, PhoneCallService::class.java).apply {
        action = "ACTION_STOP_AUTO_DIAL"
    }
    context.startService(intent)
}