// ui/contact/ContactScreen.kt
package com.example.initiateaphonecallapp.ui.contact

import android.content.Context
import android.content.Intent
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
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.Person
import androidx.compose.material.icons.filled.Phone
import androidx.compose.material.icons.filled.Refresh
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.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.initiateaphonecallapp.data.model.ApiContactsRequest
import com.example.initiateaphonecallapp.data.model.ApiContactsResponse
import com.example.initiateaphonecallapp.service.PhoneCallService
import com.example.initiateaphonecallapp.ui.calllog.AddContactFromCallDialog
import com.example.initiateaphonecallapp.ui.calllog.SuccessDialog

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ContactScreen(
    viewModel: ContactsViewModel = viewModel(),
    modifier: Modifier = Modifier,
    onContactClick: (ApiContactsRequest) -> Unit = {},
    onCallContact: (String) -> Unit = {}
) {
    val contacts by viewModel.contacts.collectAsState()
    val isLoading by viewModel.isLoading.collectAsState()
    val errorMessage by viewModel.errorMessage.collectAsState()
    val context = LocalContext.current
    var showAddContactDialog by remember { mutableStateOf(false) }
    var showSuccessDialog by remember { mutableStateOf(false) } // 新增：成功提示框
    var successMessage by remember { mutableStateOf("") } // 新增：成功消息


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

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

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


    Scaffold(
        topBar = {
            CenterAlignedTopAppBar(
                title = { Text("联系人") },
                actions = {
                     IconButton(onClick = { showAddContactDialog=true }) {
                         Icon(imageVector = Icons.Default.Add, contentDescription = "添加")
                     }
                }
            )
        },
        floatingActionButton = {
            if (errorMessage != null) {
                ExtendedFloatingActionButton(
                    onClick = { viewModel.loadContacts() },
                    icon = { Icon(Icons.Default.Refresh, "刷新") },
                    text = { Text("刷新") }
                )
            }
        }
    ) { innerPadding ->
        Column(
            modifier = modifier
                .fillMaxSize()
                .padding(innerPadding)
        ) {
            when {
                isLoading -> {
                    Box(
                        modifier = Modifier
                            .fillMaxSize()
                            .padding(16.dp),
                        contentAlignment = Alignment.Center
                    ) {
                        CircularProgressIndicator()
                    }
                }
//                errorMessage != null -> {
//                    Box(
//                        modifier = Modifier
//                            .fillMaxSize()
//                            .padding(16.dp),
//                        contentAlignment = Alignment.Center
//                    ) {
//                        Column(
//                            horizontalAlignment = Alignment.CenterHorizontally
//                        ) {
//                            Text(
//                                text = errorMessage!!,
//                                style = MaterialTheme.typography.bodyMedium,
//                                color = MaterialTheme.colorScheme.error
//                            )
//                            Button(
//                                onClick = { viewModel.loadContacts() },
//                                modifier = Modifier.padding(top = 16.dp)
//                            ) {
//                                Text("重试")
//                            }
//                        }
//                    }
//                }
                contacts.isEmpty() -> {
                    Box(
                        modifier = Modifier
                            .fillMaxSize()
                            .padding(16.dp),
                        contentAlignment = Alignment.Center
                    ) {
                        Text(
                            text = "暂无联系人",
                            style = MaterialTheme.typography.bodyLarge
                        )
                    }
                }
                else -> {
                    LazyColumn {
                        items(contacts) { contact ->
                            ContactItem(
                                contact = contact,
                                onContactClick = { onContactClick(contact) },
                                onCallContact = onCallContact,
                                modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp)
                            )
                        }
                    }
                }
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ContactItem(
    contact: ApiContactsRequest,
    onContactClick: (ApiContactsRequest) -> Unit,
    onCallContact: (String) -> Unit,
    modifier: Modifier = Modifier
) {
    val context = LocalContext.current

    Card(
        onClick = { onContactClick(contact) },
        modifier = modifier
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            // 第一行：联系人信息和拨号按钮
            androidx.compose.foundation.layout.Row(
                verticalAlignment = androidx.compose.ui.Alignment.CenterVertically,
                modifier = Modifier.fillMaxWidth()
            ) {
                // 联系人信息
                androidx.compose.foundation.layout.Row(
                    verticalAlignment = androidx.compose.ui.Alignment.CenterVertically,
                    modifier = Modifier.weight(1f)
                ) {
                    Icon(
                        imageVector = Icons.Default.Person,
                        contentDescription = "联系人",
                        modifier = Modifier.padding(end = 12.dp)
                    )
                    Column {
                        Text(
                            text = contact.name,
                            style = MaterialTheme.typography.titleMedium
                        )
                        Text(
                            text = contact.phone,
                            style = MaterialTheme.typography.bodyMedium,
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                            modifier = Modifier.padding(top = 4.dp)
                        )
                    }
                }

                // 拨号按钮
                IconButton(
                    onClick = {
                        onCallContact(contact.phone)
                        initiatePhoneCall(context, contact.phone)
                    }
                ) {
                    Icon(
                        imageVector = Icons.Default.Phone,
                        contentDescription = "拨打电话",
                        tint = MaterialTheme.colorScheme.primary
                    )
                }
            }


        }
    }
}

/**
 * 启动电话拨号服务
 */
fun initiatePhoneCall(context: Context, phoneNumber: String) {
    val intent = Intent(context, PhoneCallService::class.java).apply {
        action = "ACTION_INITIATE_CALL"
        putExtra("PHONE_NUMBER", phoneNumber)
    }
    ContextCompat.startForegroundService(context, intent)
}

