package de.softwareapp_hb.privateqrscanner.ui.screens

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.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.IconToggleButton
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.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.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 = Color.Black.copy(alpha = 0.42f),
                    shape = RoundedCornerShape(14.dp)
                )
                .padding(12.dp),
            verticalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            Text(
                text = stringResource(R.string.batch_captures_count, results.size),
                color = Color.White
            )
            results.take(3).forEach { item ->
                val contentText = if (item.result.isBase64Encoded) {
                    stringResource(R.string.base64_encoded_inline, item.result.content)
                } else {
                    item.result.content
                }
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    Column(modifier = Modifier.weight(1f)) {
                        Text(
                            text = "${item.result.displayType}: $contentText",
                            color = Color.White.copy(alpha = 0.92f),
                            maxLines = 1
                        )
                        Text(
                            text = timeFormat.format(Date(item.timestamp)),
                            color = Color.White.copy(alpha = 0.7f)
                        )
                    }
                    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(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                TextButton(onClick = onClear, enabled = results.isNotEmpty()) {
                    Text(stringResource(R.string.clear_batch))
                }
                if (allowShare) {
                    TextButton(
                        onClick = { Intents.shareText(context, buildBatchExport(results)) },
                        enabled = results.isNotEmpty()
                    ) {
                        Text(stringResource(R.string.share_batch))
                    }
                }
            }
        }
    }
}

private fun buildBatchExport(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.displayType}$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))
            }
        }
    }
}
