package ru.durakscore.app

import androidx.compose.ui.res.painterResource
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.graphics.Color
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Card
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.background
import androidx.compose.foundation.Image
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import java.util.Date

private data class AuditLogItem(
    val id: String,
    val type: String,
    val eventAt: Timestamp?,
    val actorName: String,
    val title: String,
    val details: List<String>,
    val isTest: Boolean = false
)

@Composable
fun AuditLogScreen(
    access: UserAccess,
    onBack: () -> Unit
) {
    var logs by remember { mutableStateOf<List<AuditLogItem>>(emptyList()) }
    var isLoading by remember { mutableStateOf(true) }
    var errorText by remember { mutableStateOf<String?>(null) }

    val canView =
        access.role == "admin" ||
            access.role == "scorekeeper"

    LaunchedEffect(
        canView
    ) {

        if (
            !canView
        ) {
            isLoading =
                false

            errorText =
                "Нет доступа к журналу действий"

            return@LaunchedEffect
        }

        val user =
            DurakAuthSession.current()

        if (
            user ==
            null
        ) {
            isLoading =
                false

            errorText =
                "Пользователь не авторизован"

            return@LaunchedEffect
        }

        DurakServerApi
            .loadAuditLogs(
                user =
                    user,
                onSuccess = {
                        serverLogs ->

                    logs =
                        serverLogs
                            .map {
                                    log ->

                                AuditLogItem(
                                    id =
                                        log.id,
                                    type =
                                        log.type,
                                    eventAt =
                                        log.eventAtEpochMillis
                                            ?.let {
                                                Timestamp(
                                                    Date(
                                                        it
                                                    )
                                                )
                                            },
                                    actorName =
                                        log.actorName,
                                    title =
                                        log.title,
                                    details =
                                        log.details,
                                    isTest =
                                        log.isTest
                                )
                            }

                    errorText =
                        null

                    isLoading =
                        false
                },
                onError = {
                        message ->

                    if (
                        logs.isEmpty()
                    ) {
                        errorText =
                            message.ifBlank {
                                "Не удалось загрузить журнал действий"
                            }
                    }

                    isLoading =
                        false
                }
            )
    }

    PokerScreen {
        PokerBackTextButton(onClick = onBack)

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

        GothicAuditHeader()

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

        when {
            isLoading -> {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.Center,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    CircularProgressIndicator(color = PokerPalette.Gold)
                }
            }

            errorText != null -> {
                PokerPanel {
                    Text(
                        text = errorText!!,
                        color = PokerPalette.Danger,
                        fontSize = 17.sp
                    )
                }
            }

            logs.isEmpty() -> {
                PokerPanel {
                    Text(
                        text = "В журнале пока нет записей",
                        color = PokerPalette.TextPrimary,
                        fontSize = 18.sp
                    )
                }
            }

            else -> {
                logs.forEach { log ->
                    AuditPokerCard(log)
                    Spacer(modifier = Modifier.height(14.dp))
                }
            }
        }
    }
}

@Composable
private fun GothicAuditHeader() {
    val fontScale = LocalDensity.current.fontScale
    val heroMinHeight =
        when {
            fontScale >= 1.30f -> 150.dp
            fontScale >= 1.15f -> 132.dp
            else -> 112.dp
        }

    Card(
        modifier =
            Modifier
                .fillMaxWidth()
                .heightIn(min = heroMinHeight),
        colors =
            CardDefaults.cardColors(
                containerColor = Color(0xF2070908)
            ),
        border =
            BorderStroke(
                1.dp,
                PokerPalette.GoldDark
            ),
        shape = RoundedCornerShape(16.dp)
    ) {
        Box(
            modifier =
                Modifier
                    .fillMaxWidth()
                    .heightIn(min = heroMinHeight)
        ) {
            Image(
                painter =
                    painterResource(
                        id = R.drawable.gothic_audit_jester
                    ),
                contentDescription = null,
                contentScale = ContentScale.Fit,
                modifier =
                    Modifier
                        .align(Alignment.CenterEnd)
                        .size(
                            width = 105.dp,
                            height = heroMinHeight
                        )
            )

            Column(
                modifier =
                    Modifier
                        .fillMaxWidth()
                        .padding(
                            start = 14.dp,
                            top = 14.dp,
                            end =
                                if (fontScale >= 1.25f) {
                                    62.dp
                                } else {
                                    95.dp
                                },
                            bottom = 10.dp
                        )
            ) {
                Text(
                    text = "ЖУРНАЛ ДЕЙСТВИЙ",
                    color = PokerPalette.TextPrimary,
                    fontFamily = PokerDisplayFont,
                    fontSize =
                        if (fontScale >= 1.25f) {
                            16.sp
                        } else {
                            18.sp
                        },
                    lineHeight = 22.sp,
                    fontWeight = FontWeight.Black,
                    maxLines = 3,
                    softWrap = true
                )

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

                Box(
                    modifier =
                        Modifier
                            .width(48.dp)
                            .height(2.dp)
                            .background(PokerPalette.CrimsonBright)
                )

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

                Text(
                    text = "Изменения счёта и служебные события",
                    color = PokerPalette.TextSecondary,
                    fontSize = 10.sp,
                    lineHeight = 13.sp,
                    maxLines = 4,
                    softWrap = true
                )
            }
        }
    }
}

@Composable
private fun AuditPokerCard(
    log: AuditLogItem
) {
    PokerPanel {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = log.title,
                color = PokerPalette.TextPrimary,
                fontSize = 18.sp,
                fontWeight = FontWeight.Bold,
                modifier = Modifier.weight(1f)
            )

            if (log.isTest) {
                PokerBadge(text = "ТЕСТ")
            }
        }

        if (log.eventAt != null) {
            Spacer(modifier = Modifier.height(6.dp))
            Text(
                text = formatMoscowDateTime(log.eventAt),
                color = PokerPalette.TextSecondary,
                fontSize = 13.sp
            )
        }

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

        log.details.forEach { line ->
            Text(
                text = line,
                color = PokerPalette.TextPrimary,
                fontSize = 16.sp
            )
            Spacer(modifier = Modifier.height(5.dp))
        }

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

        Text(
            text = "Выполнил: ${log.actorName}",
            color = PokerPalette.TextSecondary,
            fontSize = 14.sp,
            fontWeight = FontWeight.Medium
        )
    }
}
