// ui/calllog/CallLogScreen.kt
package com.example.initiateaphonecallapp.ui.calllog

import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
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.Add
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material.icons.filled.Call
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.Phone
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Warning
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.initiateaphonecallapp.data.model.CallRecord
import com.example.initiateaphonecallapp.data.model.toCallRecord
import com.example.initiateaphonecallapp.enums.CallStatus
import com.example.initiateaphonecallapp.enums.CallStatus.*
import com.example.initiateaphonecallapp.ui.contact.ContactsViewModel
import com.example.initiateaphonecallapp.utils.TimeRangeUtils
import java.text.SimpleDateFormat
import java.util.*

@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
@Composable
fun CallLogScreen(
    viewModel: CallLogViewModel = viewModel(),
    contactsViewModel: ContactsViewModel = viewModel(),
    modifier: Modifier = Modifier,
    onCallRecordClick: (CallRecord) -> Unit = {},
    onCallBack: (String) -> Unit = {},
    onPlayAudio: (String?) -> Unit = {}
) {
    val callRecords by viewModel.callRecords.collectAsState()
    val isLoading by viewModel.isLoading.collectAsState()
    val errorMessage by viewModel.errorMessage.collectAsState()
    val selectedTimeRange by viewModel.selectedTimeRange.collectAsState()

    // 新增：音频播放相关状态
    val currentlyPlayingAudio by viewModel.currentlyPlayingAudio.collectAsState()
    val playbackError by viewModel.playbackError.collectAsState()

    // 添加联系人相关状态
    var showAddContactDialog by remember { mutableStateOf(false) }
    var selectedPhoneNumber by remember { mutableStateOf("") }
    var showSuccessDialog by remember { mutableStateOf(false) } // 新增：成功提示框
    var successMessage by remember { mutableStateOf("") } // 新增：成功消息
    val context = LocalContext.current


    // 监听播放错误
    LaunchedEffect(playbackError) {
        playbackError?.let { error ->
            // 可以在这里显示错误提示，比如使用 Snackbar
            println("播放错误: $error")
            // 或者显示一个错误对话框
        }
    }

    // 监听添加联系人结果
    val addContactResult by contactsViewModel.addContactResult.collectAsState()
    LaunchedEffect(addContactResult) {
        addContactResult?.let { result ->
            if (result.code == 200) {
                // 显示成功提示
                successMessage = result.msg.takeIf { it.isNotBlank() } ?: "联系人添加成功"
                showSuccessDialog = true
                contactsViewModel.clearAddContactResult()
                showAddContactDialog = false
            }
        }
    }

    // 监听添加联系人错误
    val addContactError by contactsViewModel.errorMessage.collectAsState()
    LaunchedEffect(addContactError) {
        addContactError?.let { error ->
            // 可以在这里显示错误提示
            contactsViewModel.clearError()
        }
    }

    // 初始加载全部数据
    LaunchedEffect(Unit) {
        viewModel.loadCallRecords("全部")
    }

    Scaffold(
        snackbarHost = {
            // 可以在这里添加 Snackbar 来显示播放错误
            SnackbarHost(hostState = remember { SnackbarHostState() })
        },
        topBar = {
            CallLogTopBar(
                selectedTimeRange = selectedTimeRange,
                onTimeRangeSelected = { range ->
                    val request = when (range) {
                        "今天" -> TimeRangeUtils.createTodayRequest()
                        "本周" -> TimeRangeUtils.createWeekRequest()
                        "本月" -> TimeRangeUtils.createMonthRequest()
                        else -> null
                    }
                    viewModel.loadCallRecords(range, request)
                }
            )
        },
        floatingActionButton = {
            if (errorMessage != null) {
                ExtendedFloatingActionButton(
                    onClick = { viewModel.refresh() },
                    icon = { Icon(Icons.Default.Refresh, "刷新") },
                    text = { Text("刷新") }
                )
            }
        }
    ) { innerPadding ->
        when {
            isLoading -> {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(innerPadding),
                    contentAlignment = Alignment.Center
                ) {
                    CircularProgressIndicator()
                }
            }
            errorMessage != null -> {
                ErrorState(
                    message = errorMessage!!,
                    onRetry = { viewModel.refresh() },
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(innerPadding)
                )
            }
            else -> {
                CallLogContent(
                    callRecords = callRecords,
                    onCallRecordClick = onCallRecordClick,
                    onCallBack = onCallBack,
                    onPlayAudio = { audioUrl ->
                        audioUrl?.let {
                            viewModel.playAudio(it)
                        }
                    },
                    onAddContact = { phoneNumber ->
                        selectedPhoneNumber = phoneNumber
                        showAddContactDialog = true
                    },
                    currentlyPlayingAudio = currentlyPlayingAudio, // 传递当前播放状态
                    modifier = Modifier.padding(innerPadding)
                )
            }
        }

        // 添加联系人对话框
        if (showAddContactDialog) {
            AddContactFromCallDialog(
                phoneNumber = selectedPhoneNumber,
                onDismiss = { showAddContactDialog = false },
                onConfirm = { name, phone ->
                    contactsViewModel.addContact(name, phone)
                }
            )
        }

        // 成功提示对话框
        if (showSuccessDialog) {
            SuccessDialog(
                message = successMessage,
                onDismiss = { showSuccessDialog = false }
            )
        }
    }
}

// 成功提示对话框组件
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SuccessDialog(
    message: String,
    onDismiss: () -> Unit,
    modifier: Modifier = Modifier
) {
    AlertDialog(
        onDismissRequest = onDismiss,
        title = {
            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {
                Icon(
                    imageVector = Icons.Default.CheckCircle,
                    contentDescription = "成功",
                    tint = MaterialTheme.colorScheme.primary,
                    modifier = Modifier.padding(end = 8.dp)
                )
                Text("操作成功")
            }
        },
        text = {
            Text(message)
        },
        confirmButton = {
            Button(onClick = onDismiss) {
                Text("确定")
            }
        }
    )
}


// 其他组件保持不变（CallLogTopBar、ErrorState、CallStatistics、StatItem、DateGroupHeader、CallStatusIcon等）
// 只需要确保删除了重复的 CallLogContent 函数

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun CallLogContent(
    callRecords: List<CallRecord>,
    onCallRecordClick: (CallRecord) -> Unit,
    onCallBack: (String) -> Unit,
    onPlayAudio: (String?) -> Unit,
    onAddContact: (String) -> Unit, // 确保这个参数存在
    currentlyPlayingAudio: String?, // 新增：当前播放的音频URL
    modifier: Modifier = Modifier
) {
    Column(modifier = modifier) {
        // 统计信息
        if (callRecords.isNotEmpty()) {
            CallStatistics(
                callRecords = callRecords,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp)
            )
        }

        if (callRecords.isEmpty()) {
            EmptyCallLog(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(16.dp)
            )
        } else {
            val groupedRecords = callRecords.groupBy { record ->
                when {
                    isToday(record.startTime) -> "今天"
                    isYesterday(record.startTime) -> "昨天"
                    isThisWeek(record.startTime) -> "本周"
                    isThisMonth(record.startTime) -> "本月"
                    else -> "更早"
                }
            }

            LazyColumn {
                groupedRecords.forEach { (dateGroup, records) ->
                    stickyHeader {
                        DateGroupHeader(
                            dateGroup = dateGroup,
                            recordCount = records.size,
                            modifier = Modifier
                                .fillMaxWidth()
                                .background(MaterialTheme.colorScheme.background)
                                .padding(horizontal = 16.dp, vertical = 8.dp)
                        )
                    }

                    items(records) { record ->
                        CallRecordItem(
                            record = record,
                            onCallRecordClick = { onCallRecordClick(record) },
                            onCallBack = { onCallBack(record.phoneNumber) },
                            onPlayAudio = { onPlayAudio(record.audioFileUri) },
                            onAddContact = { onAddContact(record.phoneNumber) }, // 传递电话号码
                            isPlaying = record.audioFileUri == currentlyPlayingAudio, // 传递播放状态
                            modifier = Modifier.padding(horizontal = 16.dp, vertical = 2.dp)
                        )
                    }
                }
            }
        }
    }
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CallLogTopBar(
    selectedTimeRange: String,
    onTimeRangeSelected: (String) -> Unit
) {
    var expanded by remember { mutableStateOf(false) }
    val timeRanges = listOf("全部", "今天", "本周", "本月")

    CenterAlignedTopAppBar(
        title = {
            Text("通话记录", fontWeight = FontWeight.Bold)
        },
        actions = {
            Box {
                TextButton(onClick = { expanded = true }) {
                    Text(selectedTimeRange)
                    Icon(Icons.Default.ArrowDropDown, contentDescription = "选择时间范围")
                }
                DropdownMenu(
                    expanded = expanded,
                    onDismissRequest = { expanded = false }
                ) {
                    timeRanges.forEach { range ->
                        DropdownMenuItem(
                            text = { Text(range) },
                            onClick = {
                                onTimeRangeSelected(range)
                                expanded = false
                            }
                        )
                    }
                }
            }
        }
    )
}

@Composable
fun ErrorState(
    message: String,
    onRetry: () -> Unit,
    modifier: Modifier = Modifier
) {
    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center,
        modifier = modifier
    ) {
        Icon(
            imageVector = Icons.Default.Warning,
            contentDescription = "错误",
            tint = MaterialTheme.colorScheme.error,
            modifier = Modifier.size(64.dp)
        )
        Text(
            text = message,
            style = MaterialTheme.typography.bodyMedium,
            color = MaterialTheme.colorScheme.onSurfaceVariant,
            modifier = Modifier.padding(16.dp)
        )
        Button(onClick = onRetry) {
            Text("重试")
        }
    }
}

@Composable
fun CallStatistics(
    callRecords: List<CallRecord>,
    modifier: Modifier = Modifier
) {
    val completedCount = callRecords.count { it.status == COMPLETED }
    val failedCount = callRecords.count { it.status == FAILED }
    val totalDuration = callRecords.sumOf { it.duration }
    val hasRecordings = callRecords.count { it.audioFileUri != null }

    Card(
        modifier = modifier
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            Text(
                "通话统计",
                style = MaterialTheme.typography.titleSmall,
                modifier = Modifier.padding(bottom = 8.dp)
            )

            Row(
                horizontalArrangement = Arrangement.SpaceBetween,
                modifier = Modifier.fillMaxWidth()
            ) {
                StatItem("成功", completedCount.toString())
                StatItem("失败", failedCount.toString())
                StatItem("录音", hasRecordings.toString())
                StatItem("总时长", "${totalDuration / 60}分钟 ${totalDuration % 60}秒")
            }
        }
    }
}

@Composable
fun StatItem(label: String, value: String, modifier: Modifier = Modifier) {
    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        modifier = modifier
    ) {
        Text(
            value,
            style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold),
            color = MaterialTheme.colorScheme.primary
        )
        Text(
            label,
            style = MaterialTheme.typography.bodySmall,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
    }
}

@Composable
fun DateGroupHeader(
    dateGroup: String,
    recordCount: Int,
    modifier: Modifier = Modifier
) {
    Row(
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically,
        modifier = modifier
    ) {
        Text(
            dateGroup,
            style = MaterialTheme.typography.titleSmall,
            fontWeight = FontWeight.SemiBold,
            color = MaterialTheme.colorScheme.primary
        )
        Text(
            "$recordCount 条记录",
            style = MaterialTheme.typography.bodySmall,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
    }
}

@Composable
fun CallStatusIcon(
    status: CallStatus,
    modifier: Modifier = Modifier
) {
    val (icon, tint) = when (status) {
        COMPLETED -> Icons.Default.CheckCircle to MaterialTheme.colorScheme.primary
        FAILED -> Icons.Default.Info to MaterialTheme.colorScheme.error
        INITIATED -> Icons.Default.Phone to MaterialTheme.colorScheme.secondary
        DIALING -> TODO()
        CONNECTED -> TODO()
        ENDED -> TODO()
        NOT_CONNECTED -> TODO()
    }

    Icon(
        imageVector = icon,
        contentDescription = status.name,
        tint = tint,
        modifier = modifier
    )
}

fun getStatusDisplayText(status: CallStatus): String {
    return when (status) {
        COMPLETED -> "成功"
        FAILED -> "失败"
        INITIATED -> "进行中"
        DIALING -> TODO()
        CONNECTED -> TODO()
        ENDED -> TODO()
        NOT_CONNECTED -> TODO()
    }
}

@Composable
fun getStatusColor(status: CallStatus): androidx.compose.ui.graphics.Color {
    return when (status) {
        COMPLETED -> MaterialTheme.colorScheme.primary
        FAILED -> MaterialTheme.colorScheme.error
        INITIATED -> MaterialTheme.colorScheme.secondary
        DIALING -> TODO()
        CONNECTED -> TODO()
        ENDED -> TODO()
        NOT_CONNECTED -> TODO()
    }
}

@Composable
fun EmptyCallLog(
    modifier: Modifier = Modifier
) {
    Box(
        contentAlignment = Alignment.Center,
        modifier = modifier
    ) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Icon(
                imageVector = Icons.Default.Call,
                contentDescription = "无通话记录",
                tint = MaterialTheme.colorScheme.onSurfaceVariant,
                modifier = Modifier.size(64.dp)
            )
            Text(
                text = "暂无通话记录",
                style = MaterialTheme.typography.bodyLarge,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                modifier = Modifier.padding(top = 16.dp)
            )
        }
    }
}

// 时间格式化辅助函数
fun formatTimeOnly(date: Date): String {
    return SimpleDateFormat("HH:mm", Locale.getDefault()).format(date)
}

// 时间分组辅助函数
private fun isToday(date: Date): Boolean {
    val today = Calendar.getInstance()
    val target = Calendar.getInstance().apply { time = date }
    return today.get(Calendar.YEAR) == target.get(Calendar.YEAR) &&
            today.get(Calendar.DAY_OF_YEAR) == target.get(Calendar.DAY_OF_YEAR)
}

private fun isYesterday(date: Date): Boolean {
    val yesterday = Calendar.getInstance().apply { add(Calendar.DAY_OF_YEAR, -1) }
    val target = Calendar.getInstance().apply { time = date }
    return yesterday.get(Calendar.YEAR) == target.get(Calendar.YEAR) &&
            yesterday.get(Calendar.DAY_OF_YEAR) == target.get(Calendar.DAY_OF_YEAR)
}

private fun isThisWeek(date: Date): Boolean {
    val weekStart = Calendar.getInstance().apply {
        set(Calendar.DAY_OF_WEEK, firstDayOfWeek)
    }
    val target = Calendar.getInstance().apply { time = date }
    return !target.before(weekStart) && !isToday(date) && !isYesterday(date)
}

private fun isThisMonth(date: Date): Boolean {
    val monthStart = Calendar.getInstance().apply { set(Calendar.DAY_OF_MONTH, 1) }
    val target = Calendar.getInstance().apply { time = date }
    return !target.before(monthStart) && !isThisWeek(date) && !isToday(date) && !isYesterday(date)
}
