package de.softwareapp_hb.privateqrscanner.ui.screens

import android.content.Context
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
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.Email
import androidx.compose.material.icons.filled.History
import androidx.compose.material.icons.filled.Link
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Wifi
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.Switch
import androidx.compose.material3.SwitchDefaults
import androidx.compose.material3.SwipeToDismissBox
import androidx.compose.material3.SwipeToDismissBoxValue
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberSwipeToDismissBoxState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import de.softwareapp_hb.privateqrscanner.R
import de.softwareapp_hb.privateqrscanner.domain.ScanRecord
import de.softwareapp_hb.privateqrscanner.ui.UseCaseView
import de.softwareapp_hb.privateqrscanner.ui.capabilities
import de.softwareapp_hb.privateqrscanner.ui.theme.PrivateQrColors
import de.softwareapp_hb.privateqrscanner.util.HistoryExportFormatter
import de.softwareapp_hb.privateqrscanner.util.Intents
import java.text.DateFormat
import java.util.Date

@Composable
fun HistoryScreen(
    query: String,
    history: List<ScanRecord>,
    useCaseView: UseCaseView,
    historyEnabled: Boolean,
    warningsEnabled: Boolean,
    scanFeedbackEnabled: Boolean,
    onQueryChange: (String) -> Unit,
    onDelete: (Long) -> Unit,
    onClearAll: () -> Unit,
    onHistoryToggle: (Boolean, Boolean) -> Unit,
    onWarningsToggle: (Boolean) -> Unit,
    onScanFeedbackToggle: (Boolean) -> Unit
) {
    val context = LocalContext.current
    val capabilities = useCaseView.capabilities()
    val showDeleteAll = remember { mutableStateOf(false) }
    val selectedItem = remember { mutableStateOf<ScanRecord?>(null) }

    if (showDeleteAll.value) {
        AlertDialog(
            onDismissRequest = { showDeleteAll.value = false },
            title = { Text(stringResource(R.string.delete_all)) },
            text = { Text(stringResource(R.string.confirm_delete_all)) },
            confirmButton = {
                TextButton(onClick = {
                    onClearAll()
                    showDeleteAll.value = false
                }) { Text(stringResource(R.string.confirm)) }
            },
            dismissButton = {
                TextButton(onClick = { showDeleteAll.value = false }) {
                    Text(stringResource(R.string.cancel))
                }
            }
        )
    }

    val detail = selectedItem.value
    if (detail != null) {
        val detailIsBase64 = detail.isBase64Encoded()
        AlertDialog(
            onDismissRequest = { selectedItem.value = null },
            title = { Text(text = detail.localizedDisplayType(context)) },
            text = {
                if (detailIsBase64) {
                    Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
                        Text(text = stringResource(R.string.base64_encoded_notice))
                        Text(text = detail.content)
                    }
                } else {
                    Text(text = detail.content)
                }
            },
            confirmButton = {
                TextButton(onClick = { selectedItem.value = null }) {
                    Text(text = stringResource(R.string.confirm))
                }
            }
        )
    }

    BoxWithConstraints(
        modifier = Modifier
            .fillMaxSize()
            .background(PrivateQrColors.AppBackground)
    ) {
        val wideLayout = maxWidth >= 600.dp

        if (wideLayout) {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(horizontal = 20.dp),
                verticalArrangement = Arrangement.spacedBy(18.dp)
            ) {
                Spacer(modifier = Modifier.height(18.dp))
                HistoryHeader()
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .weight(1f),
                    horizontalArrangement = Arrangement.spacedBy(24.dp)
                ) {
                    Column(
                        modifier = Modifier
                            .weight(1.1f)
                            .fillMaxSize(),
                        verticalArrangement = Arrangement.spacedBy(12.dp)
                    ) {
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Text(
                                text = stringResource(R.string.history),
                                color = PrivateQrColors.TextPrimary,
                                style = MaterialTheme.typography.headlineMedium,
                                fontWeight = FontWeight.ExtraBold
                            )
                            TextButton(
                                onClick = { showDeleteAll.value = true },
                                enabled = history.isNotEmpty(),
                                colors = ButtonDefaults.textButtonColors(
                                    contentColor = Color(0xFFBE123C),
                                    disabledContentColor = PrivateQrColors.TextSecondary.copy(alpha = 0.45f)
                                )
                            ) {
                                Text(stringResource(R.string.delete_all), fontWeight = FontWeight.Bold)
                            }
                        }
                        HistorySearchField(query = query, onQueryChange = onQueryChange)
                        HistoryList(
                            history = history,
                            onDelete = onDelete,
                            onOpenDetails = { selectedItem.value = it },
                            modifier = Modifier.weight(1f)
                        )
                    }

                    Column(
                        modifier = Modifier.weight(0.95f),
                        verticalArrangement = Arrangement.spacedBy(12.dp)
                    ) {
                        Text(
                            text = stringResource(R.string.local_controls),
                            color = PrivateQrColors.TextPrimary,
                            style = MaterialTheme.typography.headlineMedium,
                            fontWeight = FontWeight.ExtraBold
                        )
                        LocalControlsCard(
                            history = history,
                            historyEnabled = historyEnabled,
                            warningsEnabled = warningsEnabled,
                            scanFeedbackEnabled = scanFeedbackEnabled,
                            allowHistoryExport = capabilities.allowHistoryExport,
                            onHistoryToggle = onHistoryToggle,
                            onWarningsToggle = onWarningsToggle,
                            onScanFeedbackToggle = onScanFeedbackToggle
                        )
                    }
                }
                Spacer(modifier = Modifier.height(12.dp))
            }
        } else {
            LazyColumn(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(horizontal = 20.dp),
                verticalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                item {
                    Spacer(modifier = Modifier.height(18.dp))
                    HistoryHeader()
                    Spacer(modifier = Modifier.height(18.dp))
                    Text(
                        text = stringResource(R.string.history),
                        color = PrivateQrColors.TextPrimary,
                        style = MaterialTheme.typography.headlineMedium,
                        fontWeight = FontWeight.ExtraBold
                    )
                    Spacer(modifier = Modifier.height(12.dp))
                    HistorySearchField(query = query, onQueryChange = onQueryChange)
                    Spacer(modifier = Modifier.height(10.dp))
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.spacedBy(8.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        if (capabilities.allowHistoryExport) {
                            ExportButton(
                                text = stringResource(R.string.share_txt),
                                enabled = history.isNotEmpty(),
                                onClick = {
                                    val exportText = HistoryExportFormatter.formatText(localizedHistory(context, history))
                                    Intents.shareContent(context, exportText, "text/plain")
                                }
                            )
                            ExportButton(
                                text = stringResource(R.string.share_csv),
                                enabled = history.isNotEmpty(),
                                onClick = {
                                    val exportCsv = HistoryExportFormatter.formatCsv(localizedHistory(context, history))
                                    Intents.shareContent(context, exportCsv, "text/csv")
                                }
                            )
                            ExportButton(
                                text = stringResource(R.string.share_json),
                                enabled = history.isNotEmpty(),
                                onClick = {
                                    val exportJson = HistoryExportFormatter.formatJson(localizedHistory(context, history))
                                    Intents.shareContent(context, exportJson, "application/json")
                                }
                            )
                        }
                        Spacer(modifier = Modifier.weight(1f))
                        TextButton(
                            onClick = { showDeleteAll.value = true },
                            enabled = history.isNotEmpty(),
                            colors = ButtonDefaults.textButtonColors(
                                contentColor = Color(0xFFBE123C),
                                disabledContentColor = PrivateQrColors.TextSecondary.copy(alpha = 0.45f)
                            )
                        ) {
                            Text(stringResource(R.string.delete_all), fontWeight = FontWeight.Bold)
                        }
                    }
                    Spacer(modifier = Modifier.height(4.dp))
                }

                if (history.isEmpty()) {
                    item {
                        EmptyHistoryCard()
                    }
                } else {
                    items(history, key = { it.id }) { item ->
                        HistoryRow(
                            item = item,
                            onDelete = onDelete,
                            onOpenDetails = { selectedItem.value = item }
                        )
                    }
                }

                item {
                    Spacer(modifier = Modifier.height(24.dp))
                }
            }
        }
    }
}

@Composable
private fun HistorySearchField(
    query: String,
    onQueryChange: (String) -> Unit
) {
    OutlinedTextField(
        value = query,
        onValueChange = onQueryChange,
        modifier = Modifier.fillMaxWidth(),
        leadingIcon = {
            Icon(
                imageVector = Icons.Default.Search,
                contentDescription = null,
                tint = PrivateQrColors.Teal700
            )
        },
        placeholder = { Text(stringResource(R.string.search)) },
        singleLine = true,
        shape = RoundedCornerShape(20.dp),
        colors = OutlinedTextFieldDefaults.colors(
            focusedBorderColor = PrivateQrColors.Teal300,
            unfocusedBorderColor = PrivateQrColors.Divider,
            focusedContainerColor = PrivateQrColors.Surface,
            unfocusedContainerColor = PrivateQrColors.Surface
        )
    )
}

@Composable
private fun HistoryList(
    history: List<ScanRecord>,
    onDelete: (Long) -> Unit,
    onOpenDetails: (ScanRecord) -> Unit,
    modifier: Modifier = Modifier
) {
    LazyColumn(
        modifier = modifier.fillMaxWidth(),
        verticalArrangement = Arrangement.spacedBy(12.dp)
    ) {
        if (history.isEmpty()) {
            item {
                EmptyHistoryCard()
            }
        } else {
            items(history, key = { it.id }) { item ->
                HistoryRow(
                    item = item,
                    onDelete = onDelete,
                    onOpenDetails = { onOpenDetails(item) }
                )
            }
        }
    }
}

@Composable
private fun LocalControlsCard(
    history: List<ScanRecord>,
    historyEnabled: Boolean,
    warningsEnabled: Boolean,
    scanFeedbackEnabled: Boolean,
    allowHistoryExport: Boolean,
    onHistoryToggle: (Boolean, Boolean) -> Unit,
    onWarningsToggle: (Boolean) -> Unit,
    onScanFeedbackToggle: (Boolean) -> Unit
) {
    val context = LocalContext.current

    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(containerColor = PrivateQrColors.Surface),
        shape = RoundedCornerShape(28.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
    ) {
        Column(
            modifier = Modifier.padding(20.dp),
            verticalArrangement = Arrangement.spacedBy(10.dp)
        ) {
            LocalControlRow(
                title = stringResource(R.string.save_history),
                checked = historyEnabled,
                onCheckedChange = { onHistoryToggle(it, false) }
            )
            LocalControlRow(
                title = stringResource(R.string.security_warnings),
                checked = warningsEnabled,
                onCheckedChange = onWarningsToggle
            )
            LocalControlRow(
                title = stringResource(R.string.scan_feedback),
                checked = scanFeedbackEnabled,
                onCheckedChange = onScanFeedbackToggle
            )
        }
    }

    if (allowHistoryExport) {
        Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
            ExportButton(
                text = stringResource(R.string.share_txt),
                enabled = history.isNotEmpty(),
                onClick = {
                    Intents.shareContent(
                        context,
                        HistoryExportFormatter.formatText(localizedHistory(context, history)),
                        "text/plain"
                    )
                }
            )
            ExportButton(
                text = stringResource(R.string.share_csv),
                enabled = history.isNotEmpty(),
                onClick = {
                    Intents.shareContent(
                        context,
                        HistoryExportFormatter.formatCsv(localizedHistory(context, history)),
                        "text/csv"
                    )
                }
            )
            ExportButton(
                text = stringResource(R.string.share_json),
                enabled = history.isNotEmpty(),
                onClick = {
                    Intents.shareContent(
                        context,
                        HistoryExportFormatter.formatJson(localizedHistory(context, history)),
                        "application/json"
                    )
                }
            )
        }
    }
}

@Composable
private fun LocalControlRow(
    title: String,
    checked: Boolean,
    onCheckedChange: (Boolean) -> Unit
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .height(58.dp),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(
            text = title,
            color = PrivateQrColors.TextPrimary,
            style = MaterialTheme.typography.titleMedium,
            fontWeight = FontWeight.ExtraBold
        )
        Switch(
            checked = checked,
            onCheckedChange = onCheckedChange,
            colors = SwitchDefaults.colors(
                checkedThumbColor = PrivateQrColors.Surface,
                checkedTrackColor = PrivateQrColors.Teal700,
                uncheckedThumbColor = PrivateQrColors.Surface,
                uncheckedTrackColor = PrivateQrColors.TextSecondary.copy(alpha = 0.35f)
            )
        )
    }
}

@Composable
private fun HistoryHeader() {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(14.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Image(
            painter = painterResource(id = R.drawable.ic_launcher_legacy),
            contentDescription = null,
            modifier = Modifier.size(64.dp)
        )
        Column {
            Text(
                text = stringResource(R.string.app_name),
                color = PrivateQrColors.TextPrimary,
                style = MaterialTheme.typography.headlineSmall,
                fontWeight = FontWeight.ExtraBold
            )
            Text(
                text = stringResource(R.string.history_header_subtitle),
                color = PrivateQrColors.TextSecondary,
                style = MaterialTheme.typography.bodyMedium,
                fontWeight = FontWeight.Bold
            )
        }
    }
    Spacer(modifier = Modifier.height(18.dp))
    Card(
        colors = CardDefaults.cardColors(containerColor = Color.Transparent),
        shape = RoundedCornerShape(30.dp)
    ) {
        Column(
            modifier = Modifier
                .background(
                    Brush.linearGradient(
                        colors = listOf(PrivateQrColors.Navy, PrivateQrColors.Teal900)
                    )
                )
                .padding(24.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            Text(
                text = stringResource(R.string.history_hero_title),
                color = PrivateQrColors.Surface,
                style = MaterialTheme.typography.headlineMedium,
                fontWeight = FontWeight.ExtraBold
            )
            Text(
                text = stringResource(R.string.history_hero_subtitle),
                color = PrivateQrColors.Mint,
                style = MaterialTheme.typography.titleMedium
            )
            Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                PrivacyPill(stringResource(R.string.privacy_pill_no_ads))
                PrivacyPill(stringResource(R.string.privacy_pill_no_tracking))
                PrivacyPill(stringResource(R.string.privacy_pill_no_account))
            }
        }
    }
}

@Composable
private fun PrivacyPill(text: String) {
    Box(
        modifier = Modifier
            .background(
                color = PrivateQrColors.Mint.copy(alpha = 0.12f),
                shape = RoundedCornerShape(16.dp)
            )
            .padding(horizontal = 14.dp, vertical = 9.dp),
        contentAlignment = Alignment.Center
    ) {
        Text(
            text = text,
            color = PrivateQrColors.Mint,
            style = MaterialTheme.typography.labelLarge,
            fontWeight = FontWeight.ExtraBold
        )
    }
}

@Composable
private fun ExportButton(
    text: String,
    enabled: Boolean,
    onClick: () -> Unit
) {
    TextButton(
        onClick = onClick,
        enabled = enabled,
        colors = ButtonDefaults.textButtonColors(
            containerColor = PrivateQrColors.Mint,
            contentColor = PrivateQrColors.Teal700,
            disabledContainerColor = PrivateQrColors.Mint.copy(alpha = 0.45f),
            disabledContentColor = PrivateQrColors.Teal700.copy(alpha = 0.45f)
        ),
        shape = RoundedCornerShape(15.dp)
    ) {
        Text(text = text, fontWeight = FontWeight.ExtraBold)
    }
}

@Composable
private fun EmptyHistoryCard() {
    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(containerColor = PrivateQrColors.Surface),
        shape = RoundedCornerShape(24.dp)
    ) {
        Column(
            modifier = Modifier.padding(20.dp),
            verticalArrangement = Arrangement.spacedBy(6.dp)
        ) {
            Text(
                text = stringResource(R.string.no_saved_scans_yet),
                color = PrivateQrColors.TextPrimary,
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.ExtraBold
            )
            Text(
                text = stringResource(R.string.empty_history_description),
                color = PrivateQrColors.TextSecondary,
                style = MaterialTheme.typography.bodyMedium
            )
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun HistoryRow(
    item: ScanRecord,
    onDelete: (Long) -> Unit,
    onOpenDetails: () -> Unit
) {
    val context = LocalContext.current
    val dismissState = rememberSwipeToDismissBoxState(
        confirmValueChange = {
            if (it == SwipeToDismissBoxValue.EndToStart || it == SwipeToDismissBoxValue.StartToEnd) {
                onDelete(item.id)
                true
            } else {
                false
            }
        }
    )

    SwipeToDismissBox(
        state = dismissState,
        backgroundContent = {},
        content = {
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .clickable { onOpenDetails() },
                colors = CardDefaults.cardColors(containerColor = PrivateQrColors.Surface),
                shape = RoundedCornerShape(24.dp),
                elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
            ) {
                Row(
                    modifier = Modifier.padding(18.dp),
                    horizontalArrangement = Arrangement.spacedBy(14.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Box(
                        modifier = Modifier
                            .size(52.dp)
                            .background(
                                color = PrivateQrColors.Mint.copy(alpha = 0.55f),
                                shape = RoundedCornerShape(16.dp)
                            ),
                        contentAlignment = Alignment.Center
                    ) {
                        Icon(
                            imageVector = iconForType(item.type),
                            contentDescription = null,
                            tint = PrivateQrColors.Teal700
                        )
                    }
                    Column(modifier = Modifier.weight(1f)) {
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Text(
                                text = item.localizedDisplayType(context),
                                color = PrivateQrColors.TextPrimary,
                                style = MaterialTheme.typography.titleMedium,
                                fontWeight = FontWeight.ExtraBold
                            )
                            Text(
                                text = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT)
                                    .format(Date(item.timestamp)),
                                color = PrivateQrColors.TextSecondary,
                                style = MaterialTheme.typography.labelMedium,
                                maxLines = 1
                            )
                        }
                        Text(
                            text = if (item.isBase64Encoded()) {
                                stringResource(R.string.base64_encoded_inline, item.content)
                            } else {
                                item.content
                            },
                            color = PrivateQrColors.TextSecondary,
                            style = MaterialTheme.typography.bodyLarge,
                            maxLines = 2,
                            overflow = TextOverflow.Ellipsis
                        )
                    }
                }
            }
        }
    )
}

private fun iconForType(type: String): ImageVector {
    return when {
        type.equals("URL", ignoreCase = true) -> Icons.Default.Link
        type.equals("Email", ignoreCase = true) -> Icons.Default.Email
        type.equals("WiFi", ignoreCase = true) -> Icons.Default.Wifi
        else -> Icons.Default.History
    }
}

private fun localizedHistory(context: Context, history: List<ScanRecord>): List<ScanRecord> {
    return history.map { item ->
        item.copy(type = item.localizedDisplayType(context))
    }
}

private fun ScanRecord.isBase64Encoded(): Boolean {
    return type.contains("base64", ignoreCase = true)
}
