package com.rosetta.messenger.ui.crashlogs

import android.content.Intent
import android.widget.Toast
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.material.icons.Icons
import compose.icons.TablerIcons
import compose.icons.tablericons.*
import androidx.compose.material.icons.filled.BugReport
import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Share
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.AnnotatedString
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 androidx.compose.ui.unit.sp
import androidx.core.content.FileProvider
import com.rosetta.messenger.utils.CrashReportManager
import java.io.File
import java.text.SimpleDateFormat
import java.util.*

private const val MAX_CRASH_PREVIEW_CHARS = 180_000
private const val MAX_CRASH_PREVIEW_LINES = 2_500
private const val MAX_CLIPBOARD_COPY_CHARS = 120_000

private fun buildCrashPreview(content: String): String {
    if (content.length <= MAX_CRASH_PREVIEW_CHARS) return content
    val clipped = content.take(MAX_CRASH_PREVIEW_CHARS).trimEnd()
    return buildString(clipped.length + 128) {
        append(clipped)
        append("\n\n--- LOG TRUNCATED IN VIEW ---\n")
        append("Use the share button to export the full crash log.")
    }
}

private fun buildSafeClipboardLog(content: String): Pair<String, Boolean> {
    if (content.length <= MAX_CLIPBOARD_COPY_CHARS) return content to false
    val clipped = content.take(MAX_CLIPBOARD_COPY_CHARS).trimEnd()
    val safeText = buildString(clipped.length + 220) {
        append(clipped)
        append("\n\n--- LOG TRUNCATED FOR CLIPBOARD ---\n")
        append("Crash log is too large for clipboard transfer. ")
        append("Use Share to export the full log file.")
    }
    return safeText to true
}

private fun shareCrashLog(context: android.content.Context, crashReport: CrashReportManager.CrashReport) {
    val exportDir = File(context.cacheDir, "shared_crash_reports").apply { mkdirs() }
    val safeBaseName = crashReport.fileName
        .substringBeforeLast(".")
        .replace(Regex("[^a-zA-Z0-9._-]"), "_")
        .ifBlank { "crash_log" }
    val exportFile = File(exportDir, "${safeBaseName}_${System.currentTimeMillis()}.txt")
    exportFile.writeText(crashReport.content)
    val uri = FileProvider.getUriForFile(context, "${context.packageName}.provider", exportFile)

    val shareIntent = Intent(Intent.ACTION_SEND).apply {
        type = "text/plain"
        putExtra(Intent.EXTRA_SUBJECT, "Rosetta crash log: ${crashReport.fileName}")
        putExtra(Intent.EXTRA_STREAM, uri)
        addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
    }
    context.startActivity(Intent.createChooser(shareIntent, "Share crash log"))
}

/**
 * Экран для просмотра crash logs
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CrashLogsScreen(
    onBackClick: () -> Unit
) {
    val context = LocalContext.current
    var crashReports by remember { mutableStateOf<List<CrashReportManager.CrashReport>>(emptyList()) }
    var selectedReport by remember { mutableStateOf<CrashReportManager.CrashReport?>(null) }
    var showDeleteAllDialog by remember { mutableStateOf(false) }
    var showDeleteDialog by remember { mutableStateOf<String?>(null) }
    
    // Загружаем crash reports
    LaunchedEffect(Unit) {
        crashReports = CrashReportManager.getCrashReports(context)
    }
    
    // Функция для обновления списка
    fun refreshReports() {
        crashReports = CrashReportManager.getCrashReports(context)
    }
    
    if (selectedReport != null) {
        // Показываем детали краша
        CrashDetailScreen(
            crashReport = selectedReport!!,
            onBackClick = { selectedReport = null },
            onDelete = {
                CrashReportManager.deleteCrashReport(context, selectedReport!!.fileName)
                refreshReports()
                selectedReport = null
            }
        )
    } else {
        // Список крашей
        Scaffold(
            topBar = {
                TopAppBar(
                    title = { Text("Crash Logs") },
                    navigationIcon = {
                        IconButton(onClick = onBackClick) {
                            Icon(TablerIcons.ChevronLeft, contentDescription = "Back")
                        }
                    },
                    actions = {
                        if (crashReports.isNotEmpty()) {
                            IconButton(onClick = { showDeleteAllDialog = true }) {
                                Icon(Icons.Default.Delete, contentDescription = "Delete All")
                            }
                        }
                    }
                )
            }
        ) { paddingValues ->
            if (crashReports.isEmpty()) {
                // Пустое состояние
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(paddingValues),
                    contentAlignment = Alignment.Center
                ) {
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally,
                        verticalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        Icon(
                            imageVector = Icons.Default.BugReport,
                            contentDescription = null,
                            modifier = Modifier.size(64.dp),
                            tint = MaterialTheme.colorScheme.primary.copy(alpha = 0.5f)
                        )
                        Text(
                            text = "No crash reports",
                            style = MaterialTheme.typography.bodyLarge,
                            color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f)
                        )
                        Text(
                            text = "Great! Your app is running smoothly",
                            style = MaterialTheme.typography.bodyMedium,
                            color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.4f)
                        )
                    }
                }
            } else {
                // Список crash reports
                LazyColumn(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(paddingValues),
                    contentPadding = PaddingValues(16.dp),
                    verticalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    items(crashReports) { report ->
                        CrashReportItem(
                            crashReport = report,
                            onClick = { selectedReport = report },
                            onDelete = { showDeleteDialog = report.fileName }
                        )
                    }
                }
            }
        }
        
        // Диалог удаления всех
        if (showDeleteAllDialog) {
            AlertDialog(
                onDismissRequest = { showDeleteAllDialog = false },
                title = { Text("Delete All Crash Reports?") },
                text = { Text("This will permanently delete all ${crashReports.size} crash reports.") },
                confirmButton = {
                    TextButton(
                        onClick = {
                            CrashReportManager.deleteAllCrashReports(context)
                            refreshReports()
                            showDeleteAllDialog = false
                        }
                    ) {
                        Text("Delete All")
                    }
                },
                dismissButton = {
                    TextButton(onClick = { showDeleteAllDialog = false }) {
                        Text("Cancel")
                    }
                }
            )
        }
        
        // Диалог удаления одного
        if (showDeleteDialog != null) {
            AlertDialog(
                onDismissRequest = { showDeleteDialog = null },
                title = { Text("Delete Crash Report?") },
                text = { Text("This will permanently delete this crash report.") },
                confirmButton = {
                    TextButton(
                        onClick = {
                            CrashReportManager.deleteCrashReport(context, showDeleteDialog!!)
                            refreshReports()
                            showDeleteDialog = null
                        }
                    ) {
                        Text("Delete")
                    }
                },
                dismissButton = {
                    TextButton(onClick = { showDeleteDialog = null }) {
                        Text("Cancel")
                    }
                }
            )
        }
    }
}

/**
 * Элемент списка с crash report
 */
@Composable
private fun CrashReportItem(
    crashReport: CrashReportManager.CrashReport,
    onClick: () -> Unit,
    onDelete: () -> Unit
) {
    val dateFormat = remember { SimpleDateFormat("dd MMM yyyy, HH:mm:ss", Locale.getDefault()) }
    val exceptionType = remember {
        crashReport.content.lines()
            .find { it.startsWith("Exception Type:") }
            ?.substringAfter("Exception Type: ")
            ?.substringAfterLast(".")
            ?: "Unknown"
    }
    
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .clickable(onClick = onClick),
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.3f)
        )
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Column(
                modifier = Modifier.weight(1f),
                verticalArrangement = Arrangement.spacedBy(4.dp)
            ) {
                Row(
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Icon(
                        imageVector = Icons.Default.BugReport,
                        contentDescription = null,
                        modifier = Modifier.size(20.dp),
                        tint = MaterialTheme.colorScheme.error
                    )
                    Text(
                        text = exceptionType,
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.Bold
                    )
                }
                Text(
                    text = dateFormat.format(Date(crashReport.timestamp)),
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f)
                )
            }
            
            IconButton(onClick = onDelete) {
                Icon(
                    imageVector = Icons.Default.Delete,
                    contentDescription = "Delete",
                    tint = MaterialTheme.colorScheme.error
                )
            }
        }
    }
}

/**
 * Детальный просмотр crash report
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun CrashDetailScreen(
    crashReport: CrashReportManager.CrashReport,
    onBackClick: () -> Unit,
    onDelete: () -> Unit
) {
    var showDeleteDialog by remember { mutableStateOf(false) }
    val clipboardManager = LocalClipboardManager.current
    val context = LocalContext.current
    val crashPreview = remember(crashReport.content) {
        buildCrashPreview(crashReport.content)
    }
    
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("Crash Details") },
                navigationIcon = {
                    IconButton(onClick = onBackClick) {
                        Icon(TablerIcons.ChevronLeft, contentDescription = "Back")
                    }
                },
                actions = {
                    IconButton(
                        onClick = {
                            runCatching {
                                val (safeClipboardText, wasTruncated) = buildSafeClipboardLog(crashReport.content)
                                clipboardManager.setText(AnnotatedString(safeClipboardText))
                                val message = if (wasTruncated) {
                                    "Log is too large. Copied trimmed text. Use Share for full log."
                                } else {
                                    "Full log copied"
                                }
                                Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
                            }.onFailure {
                                Toast.makeText(context, "Failed to copy log", Toast.LENGTH_SHORT).show()
                            }
                        }
                    ) {
                        Icon(Icons.Default.ContentCopy, contentDescription = "Copy Full Log")
                    }
                    IconButton(onClick = {
                        runCatching {
                            shareCrashLog(context, crashReport)
                        }.onFailure {
                            Toast.makeText(context, "Failed to share crash log", Toast.LENGTH_SHORT).show()
                        }
                    }) {
                        Icon(Icons.Default.Share, contentDescription = "Share")
                    }
                    IconButton(onClick = { showDeleteDialog = true }) {
                        Icon(Icons.Default.Delete, contentDescription = "Delete")
                    }
                }
            )
        }
    ) { paddingValues ->
        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .background(MaterialTheme.colorScheme.surface),
            contentPadding = PaddingValues(16.dp)
        ) {
            item {
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    colors = CardDefaults.cardColors(
                        containerColor = MaterialTheme.colorScheme.surfaceVariant
                    )
                ) {
                    Text(
                        text = crashPreview,
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(16.dp),
                        fontFamily = FontFamily.Monospace,
                        fontSize = 12.sp,
                        lineHeight = 18.sp,
                        maxLines = MAX_CRASH_PREVIEW_LINES,
                        overflow = TextOverflow.Clip
                    )
                }
            }
        }
        
        if (showDeleteDialog) {
            AlertDialog(
                onDismissRequest = { showDeleteDialog = false },
                title = { Text("Delete Crash Report?") },
                text = { Text("This will permanently delete this crash report.") },
                confirmButton = {
                    TextButton(
                        onClick = {
                            showDeleteDialog = false
                            onDelete()
                        }
                    ) {
                        Text("Delete")
                    }
                },
                dismissButton = {
                    TextButton(onClick = { showDeleteDialog = false }) {
                        Text("Cancel")
                    }
                }
            )
        }
    }
}
