package de.softwareapp_hb.privateqrscanner.ui.screens

import android.content.Context
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material.icons.filled.Share
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.IconToggleButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
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.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import de.softwareapp_hb.privateqrscanner.R
import de.softwareapp_hb.privateqrscanner.ui.BatchScanRecord
import de.softwareapp_hb.privateqrscanner.ui.theme.PrivateQrColors
import de.softwareapp_hb.privateqrscanner.util.ClipboardUtil
import de.softwareapp_hb.privateqrscanner.util.Intents
import java.text.DateFormat
import java.util.Date

@Composable
internal fun OverlayIconToggle(
    checked: Boolean,
    onCheckedChange: (Boolean) -> Unit,
    label: String,
    checkedImageVector: androidx.compose.ui.graphics.vector.ImageVector,
    uncheckedImageVector: androidx.compose.ui.graphics.vector.ImageVector,
    showLabel: Boolean = true
) {
    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        modifier = Modifier
            .background(
                color = Color.Black.copy(alpha = 0.35f),
                shape = RoundedCornerShape(12.dp)
            )
            .padding(horizontal = 10.dp, vertical = 8.dp)
    ) {
        IconToggleButton(
            checked = checked,
            onCheckedChange = onCheckedChange
        ) {
            Icon(
                imageVector = if (checked) checkedImageVector else uncheckedImageVector,
                contentDescription = label,
                tint = if (checked) Color(0xFF4AE3A3) else Color.White
            )
        }
        if (showLabel) {
            Text(
                text = label,
                color = Color.White,
                textAlign = TextAlign.Center
            )
        }
    }
}

@Composable
internal fun BatchResultsPanel(
    results: List<BatchScanRecord>,
    onClear: () -> Unit,
    allowShare: Boolean
) {
    val context = LocalContext.current
    val timeFormat = remember { DateFormat.getTimeInstance(DateFormat.SHORT) }

    Box(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 12.dp, vertical = 12.dp),
        contentAlignment = Alignment.BottomCenter
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .background(
                    color = PrivateQrColors.Deep.copy(alpha = 0.88f),
                    shape = RoundedCornerShape(28.dp)
                )
                .padding(20.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = stringResource(R.string.batch_captures_count, results.size),
                    color = Color.White,
                    style = MaterialTheme.typography.titleLarge,
                    fontWeight = FontWeight.ExtraBold
                )
                if (allowShare) {
                    TextButton(
                        onClick = { Intents.shareText(context, buildBatchExport(context, results)) },
                        enabled = results.isNotEmpty(),
                        colors = ButtonDefaults.textButtonColors(
                            containerColor = PrivateQrColors.Mint,
                            contentColor = PrivateQrColors.Teal700,
                            disabledContainerColor = PrivateQrColors.Mint.copy(alpha = 0.32f),
                            disabledContentColor = PrivateQrColors.Teal700.copy(alpha = 0.45f)
                        ),
                        shape = RoundedCornerShape(18.dp)
                    ) {
                        Text(stringResource(R.string.share_batch), fontWeight = FontWeight.ExtraBold)
                    }
                }
            }
            results.take(3).forEach { item ->
                val contentText = if (item.result.isBase64Encoded) {
                    stringResource(R.string.base64_encoded_inline, item.result.content)
                } else {
                    item.result.content
                }
                HorizontalDivider(color = Color.White.copy(alpha = 0.12f))
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    Column(modifier = Modifier.weight(1f)) {
                        Text(
                            text = "${item.result.localizedDisplayType(context)}: $contentText",
                            color = Color.White.copy(alpha = 0.92f),
                            style = MaterialTheme.typography.titleMedium,
                            fontWeight = FontWeight.Bold,
                            maxLines = 1
                        )
                        Text(
                            text = timeFormat.format(Date(item.timestamp)),
                            color = Color.White.copy(alpha = 0.7f),
                            style = MaterialTheme.typography.bodyMedium,
                            fontWeight = FontWeight.SemiBold
                        )
                    }
                    Row {
                        IconButton(onClick = { ClipboardUtil.copy(context, item.result.content) }) {
                            Icon(
                                imageVector = Icons.Default.ContentCopy,
                                contentDescription = stringResource(R.string.copy),
                                tint = Color.White
                            )
                        }
                        if (allowShare) {
                            IconButton(onClick = { Intents.shareText(context, item.result.content) }) {
                                Icon(
                                    imageVector = Icons.Default.Share,
                                    contentDescription = stringResource(R.string.share),
                                    tint = Color.White
                                )
                            }
                        }
                    }
                }
            }
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .background(Color(0xFF831843).copy(alpha = 0.42f), RoundedCornerShape(18.dp))
                    .padding(horizontal = 14.dp, vertical = 12.dp),
                horizontalArrangement = Arrangement.spacedBy(10.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(text = "▲", color = Color(0xFFFF7A9A), fontWeight = FontWeight.ExtraBold)
                Text(
                    text = stringResource(R.string.batch_ticket_privacy_note),
                    color = Color.White,
                    style = MaterialTheme.typography.labelLarge,
                    fontWeight = FontWeight.ExtraBold,
                    modifier = Modifier.weight(1f)
                )
            }
            TextButton(
                onClick = onClear,
                enabled = results.isNotEmpty(),
                colors = ButtonDefaults.textButtonColors(contentColor = PrivateQrColors.Mint)
            ) {
                Text(stringResource(R.string.clear_batch), fontWeight = FontWeight.Bold)
            }
            if (results.isEmpty()) {
                Text(
                    text = stringResource(R.string.aim_center_hint),
                    color = Color.White.copy(alpha = 0.68f),
                    style = MaterialTheme.typography.bodyMedium
                )
            }
            if (!allowShare && results.isNotEmpty()) {
                Text(
                    text = stringResource(R.string.batch_ticket_privacy_note),
                    color = Color.White.copy(alpha = 0.68f),
                    style = MaterialTheme.typography.bodyMedium
                )
            }
        }
    }
}

private fun buildBatchExport(context: Context, results: List<BatchScanRecord>): String {
    if (results.isEmpty()) return ""
    val formatter = DateFormat.getDateTimeInstance()
    return results.joinToString(separator = "\n\n") { item ->
        val encoding = if (item.result.isBase64Encoded) "\nEncoding: Base64" else ""
        "${formatter.format(Date(item.timestamp))}\n${item.result.localizedDisplayType(context)}$encoding\n${item.result.content}"
    }
}

@Composable
internal fun PermissionContent(
    showSettingsHint: Boolean,
    onRequestPermission: () -> Unit,
    onOpenSettings: () -> Unit
) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(24.dp),
        verticalArrangement = Arrangement.Center
    ) {
        Text(text = stringResource(R.string.camera_permission_title))
        Text(text = stringResource(R.string.camera_permission_rationale))
        Button(onClick = onRequestPermission) {
            Text(text = stringResource(R.string.request_camera))
        }
        if (showSettingsHint) {
            TextButton(onClick = onOpenSettings) {
                Text(stringResource(R.string.open_settings))
            }
        }
    }
}
