package com.durian.tssparty.presentation.screens

import android.content.Intent
import android.net.Uri
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.durian.tssparty.data.local.TransactionRecordEntity
import com.durian.tssparty.domain.model.EnergyPointsToken
import com.durian.tssparty.domain.model.FuturePointsToken
import com.durian.tssparty.domain.model.GreenPointsToken
import com.durian.tssparty.domain.model.NetworkType
import java.text.SimpleDateFormat
import java.util.*

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TransactionHistoryScreen(
    shareId: Long,
    walletAddress: String,
    transactions: List<TransactionRecordEntity>,
    networkType: NetworkType,
    isSyncing: Boolean,
    syncResultMessage: String? = null,
    onBack: () -> Unit,
    onRefresh: () -> Unit,
    onClearSyncMessage: () -> Unit = {}
) {
    val context = LocalContext.current
    val snackbarHostState = remember { SnackbarHostState() }

    // Show snackbar when sync result message changes
    LaunchedEffect(syncResultMessage) {
        syncResultMessage?.let { message ->
            snackbarHostState.showSnackbar(message)
            onClearSyncMessage()
        }
    }

    Scaffold(
        snackbarHost = { SnackbarHost(snackbarHostState) },
        topBar = {
            TopAppBar(
                title = { Text("交易记录") },
                navigationIcon = {
                    IconButton(onClick = onBack) {
                        Icon(Icons.Default.ArrowBack, contentDescription = "返回")
                    }
                },
                actions = {
                    if (isSyncing) {
                        CircularProgressIndicator(
                            modifier = Modifier
                                .size(24.dp)
                                .padding(end = 8.dp),
                            strokeWidth = 2.dp
                        )
                    } else {
                        IconButton(onClick = onRefresh) {
                            Icon(Icons.Default.Refresh, contentDescription = "刷新")
                        }
                    }
                }
            )
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .padding(horizontal = 16.dp)
        ) {
            // Wallet address header
            Card(
                modifier = Modifier.fillMaxWidth(),
                colors = CardDefaults.cardColors(
                    containerColor = MaterialTheme.colorScheme.surfaceVariant
                )
            ) {
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(12.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Icon(
                        Icons.Default.AccountBalanceWallet,
                        contentDescription = null,
                        modifier = Modifier.size(20.dp),
                        tint = MaterialTheme.colorScheme.primary
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text(
                        text = walletAddress,
                        style = MaterialTheme.typography.bodySmall,
                        fontFamily = FontFamily.Monospace,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis
                    )
                }
            }

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

            // Transaction count
            Text(
                text = "共 ${transactions.size} 条记录",
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )

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

            if (transactions.isEmpty()) {
                // Empty state
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    Column(horizontalAlignment = Alignment.CenterHorizontally) {
                        Icon(
                            imageVector = Icons.Default.Receipt,
                            contentDescription = null,
                            modifier = Modifier.size(80.dp),
                            tint = MaterialTheme.colorScheme.outline
                        )
                        Spacer(modifier = Modifier.height(16.dp))
                        Text(
                            text = "暂无交易记录",
                            style = MaterialTheme.typography.titleLarge,
                            color = MaterialTheme.colorScheme.outline
                        )
                        Spacer(modifier = Modifier.height(8.dp))
                        Text(
                            text = if (isSyncing) "正在同步中..." else "发起转账后将在此显示",
                            style = MaterialTheme.typography.bodyMedium,
                            color = MaterialTheme.colorScheme.outline
                        )
                    }
                }
            } else {
                // Transaction list
                LazyColumn(
                    verticalArrangement = Arrangement.spacedBy(8.dp),
                    contentPadding = PaddingValues(bottom = 16.dp)
                ) {
                    items(
                        items = transactions.sortedByDescending { it.createdAt },
                        key = { it.id }
                    ) { tx ->
                        TransactionItemCard(
                            transaction = tx,
                            walletAddress = walletAddress,
                            networkType = networkType,
                            onClick = {
                                // Open transaction in block explorer
                                val explorerUrl = getExplorerUrl(networkType, tx.txHash)
                                val intent = Intent(Intent.ACTION_VIEW, Uri.parse(explorerUrl))
                                context.startActivity(intent)
                            }
                        )
                    }
                }
            }
        }
    }
}

@Composable
private fun TransactionItemCard(
    transaction: TransactionRecordEntity,
    walletAddress: String,
    networkType: NetworkType,
    onClick: () -> Unit
) {
    val isSent = transaction.direction == "SENT" ||
            transaction.fromAddress.equals(walletAddress, ignoreCase = true)

    val statusColor = when (transaction.status) {
        "CONFIRMED" -> Color(0xFF4CAF50)  // Green
        "FAILED" -> MaterialTheme.colorScheme.error
        else -> Color(0xFFFF9800)  // Orange for PENDING
    }

    val tokenColor = when (transaction.tokenType) {
        "GREEN_POINTS" -> Color(0xFF4CAF50)
        "ENERGY_POINTS" -> Color(0xFF2196F3)
        "FUTURE_POINTS" -> Color(0xFF9C27B0)
        else -> MaterialTheme.colorScheme.primary  // KAVA
    }

    val tokenName = when (transaction.tokenType) {
        "GREEN_POINTS" -> GreenPointsToken.NAME
        "ENERGY_POINTS" -> EnergyPointsToken.NAME
        "FUTURE_POINTS" -> FuturePointsToken.NAME
        else -> "KAVA"
    }

    Card(
        modifier = Modifier
            .fillMaxWidth()
            .clickable { onClick() }
    ) {
        Column(
            modifier = Modifier.padding(12.dp)
        ) {
            // Row 1: Direction icon + Amount + Status
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Row(verticalAlignment = Alignment.CenterVertically) {
                    // Direction icon
                    Box(
                        modifier = Modifier
                            .size(36.dp)
                            .clip(RoundedCornerShape(8.dp))
                            .background(
                                if (isSent)
                                    MaterialTheme.colorScheme.errorContainer
                                else
                                    Color(0xFFE8F5E9)
                            ),
                        contentAlignment = Alignment.Center
                    ) {
                        Icon(
                            imageVector = if (isSent) Icons.Default.ArrowUpward else Icons.Default.ArrowDownward,
                            contentDescription = if (isSent) "发送" else "接收",
                            tint = if (isSent)
                                MaterialTheme.colorScheme.error
                            else
                                Color(0xFF4CAF50),
                            modifier = Modifier.size(20.dp)
                        )
                    }

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

                    // Amount and token
                    Column {
                        Row(verticalAlignment = Alignment.CenterVertically) {
                            Text(
                                text = "${if (isSent) "-" else "+"}${transaction.amount}",
                                style = MaterialTheme.typography.titleMedium,
                                fontWeight = FontWeight.Bold,
                                color = if (isSent)
                                    MaterialTheme.colorScheme.error
                                else
                                    Color(0xFF4CAF50)
                            )
                            Spacer(modifier = Modifier.width(4.dp))
                            Text(
                                text = tokenName,
                                style = MaterialTheme.typography.bodySmall,
                                color = tokenColor
                            )
                        }
                        Text(
                            text = if (isSent) "发送" else "接收",
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                }

                // Status badge
                Surface(
                    color = statusColor.copy(alpha = 0.15f),
                    shape = RoundedCornerShape(4.dp)
                ) {
                    Text(
                        text = when (transaction.status) {
                            "CONFIRMED" -> "已确认"
                            "FAILED" -> "失败"
                            else -> "待确认"
                        },
                        modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp),
                        style = MaterialTheme.typography.labelSmall,
                        color = statusColor
                    )
                }
            }

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

            Divider(color = MaterialTheme.colorScheme.outlineVariant)

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

            // Row 2: Address (to/from)
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Column {
                    Text(
                        text = if (isSent) "发送至" else "来自",
                        style = MaterialTheme.typography.labelSmall,
                        color = MaterialTheme.colorScheme.outline
                    )
                    Text(
                        text = if (isSent) shortenAddress(transaction.toAddress) else shortenAddress(transaction.fromAddress),
                        style = MaterialTheme.typography.bodySmall,
                        fontFamily = FontFamily.Monospace
                    )
                }

                Column(horizontalAlignment = Alignment.End) {
                    Text(
                        text = "时间",
                        style = MaterialTheme.typography.labelSmall,
                        color = MaterialTheme.colorScheme.outline
                    )
                    Text(
                        text = formatTimestamp(transaction.createdAt),
                        style = MaterialTheme.typography.bodySmall
                    )
                }
            }

            // Row 3: Tx Hash (abbreviated)
            Spacer(modifier = Modifier.height(4.dp))
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "交易哈希: ${shortenTxHash(transaction.txHash)}",
                    style = MaterialTheme.typography.labelSmall,
                    color = MaterialTheme.colorScheme.outline,
                    fontFamily = FontFamily.Monospace
                )
                Spacer(modifier = Modifier.width(4.dp))
                Icon(
                    Icons.Default.OpenInNew,
                    contentDescription = "查看详情",
                    modifier = Modifier.size(12.dp),
                    tint = MaterialTheme.colorScheme.outline
                )
            }

            // Row 4: Fee (if confirmed)
            if (transaction.status == "CONFIRMED" && transaction.txFee.isNotEmpty()) {
                Spacer(modifier = Modifier.height(4.dp))
                Text(
                    text = "手续费: ${transaction.txFee} KAVA",
                    style = MaterialTheme.typography.labelSmall,
                    color = MaterialTheme.colorScheme.outline
                )
            }
        }
    }
}

private fun shortenAddress(address: String): String {
    return if (address.length > 16) {
        "${address.take(10)}...${address.takeLast(6)}"
    } else {
        address
    }
}

private fun shortenTxHash(txHash: String): String {
    return if (txHash.length > 20) {
        "${txHash.take(10)}...${txHash.takeLast(8)}"
    } else {
        txHash
    }
}

private fun formatTimestamp(timestamp: Long): String {
    val sdf = SimpleDateFormat("MM-dd HH:mm", Locale.getDefault())
    return sdf.format(Date(timestamp))
}

private fun getExplorerUrl(networkType: NetworkType, txHash: String): String {
    return when (networkType) {
        NetworkType.MAINNET -> "https://kavascan.com/tx/$txHash"
        NetworkType.TESTNET -> "https://testnet.kavascan.com/tx/$txHash"
    }
}
