package net.sergeych.toread

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.PaddingValues
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.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.Card
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
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.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import net.sergeych.toread.fb2.Fb2Book

@Composable
@OptIn(ExperimentalMaterial3Api::class)
internal fun BookInfoScreen(
    fileId: String,
    book: Fb2Book,
    onImageOpen: (ViewedBookImage) -> Unit,
    onBack: () -> Unit,
) {
    val stats = remember(book) { BookStats.from(book) }
    var extras by remember(fileId) { mutableStateOf<BookInfoExtras?>(null) }

    LaunchedEffect(fileId) {
        extras = loadBookInfoExtras(fileId)
    }

    Scaffold(
        topBar = {
            CenterAlignedTopAppBar(
                title = { Text("Book info") },
                navigationIcon = {
                    IconButton(onClick = onBack) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back to reader")
                    }
                },
                colors = themedTopAppBarColors(),
            )
        },
    ) {
        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .padding(it)
                .background(readerBackground()),
            contentPadding = PaddingValues(12.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp),
        ) {
            item {
                InfoSection("Title Info") {
                    CoverAndTitle(book, onImageOpen = onImageOpen)
                    DetailLine("Title", book.title)
                    DetailLine("Authors", book.authors.joinToString { it.displayName }.ifBlank { "Unknown author" })
                    DetailLine("Language", book.language?.uppercase() ?: "Not specified")
                    DetailLine("Date", book.date ?: "Not specified")
                    DetailLine("Genres", book.genres.joinToString().ifBlank { "Not specified" })
                    DetailLine("Source", book.sourceLanguage?.uppercase() ?: "Not specified")
                    if (book.annotation.isNullOrBlank().not()) {
                        Text(book.annotation.orEmpty(), style = MaterialTheme.typography.bodyMedium, lineHeight = 20.sp)
                    }
                }
            }
            item {
                InfoSection("Statistics") {
                    Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
                        StatBlock("Words", stats.words.formatCompact())
                        StatBlock("Sections", stats.sections.toString())
                        StatBlock("Images", stats.images.toString())
                    }
                }
            }
            item {
                InfoSection("Last Reading Position") {
                    val position = extras?.lastReadingPosition
                    if (position == null) {
                        Text("No saved position", style = MaterialTheme.typography.bodyMedium)
                    } else {
                        DetailLine("List item", position.itemIndex.toString())
                        DetailLine("Scroll offset", "${position.scrollOffset}px")
                    }
                }
            }
            item {
                InfoSection("Bookmarks") {
                    val bookmarks = extras?.bookmarks.orEmpty()
                    if (extras == null) {
                        Text("Loading...", style = MaterialTheme.typography.bodyMedium)
                    } else if (bookmarks.isEmpty()) {
                        Text("No bookmarks", style = MaterialTheme.typography.bodyMedium)
                    } else {
                        bookmarks.forEach { bookmark ->
                            BookmarkInfoLine(bookmark)
                        }
                    }
                }
            }
            item {
                InfoSection("Notes") {
                    val notes = extras?.notes.orEmpty()
                    if (extras == null) {
                        Text("Loading...", style = MaterialTheme.typography.bodyMedium)
                    } else if (notes.isEmpty()) {
                        Text("No notes", style = MaterialTheme.typography.bodyMedium)
                    } else {
                        notes.forEach { note ->
                            NoteInfoLine(note)
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun InfoSection(title: String, content: @Composable ColumnScope.() -> Unit) {
    Card(shape = RoundedCornerShape(8.dp), colors = quietCardColors(), modifier = Modifier.fillMaxWidth()) {
        Column(Modifier.padding(14.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
            Text(title, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
            content()
        }
    }
}

@Composable
private fun BookmarkInfoLine(bookmark: BookmarkInfo) {
    Column(verticalArrangement = Arrangement.spacedBy(2.dp), modifier = Modifier.fillMaxWidth()) {
        Text(bookmark.title?.ifBlank { null } ?: "Bookmark", style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.SemiBold)
        bookmark.selectedText?.ifBlank { null }?.let {
            Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.secondary, maxLines = 3)
        }
        Text(bookmark.progress.progressLabel(), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.outline)
    }
}

@Composable
private fun NoteInfoLine(note: NoteInfo) {
    Column(verticalArrangement = Arrangement.spacedBy(2.dp), modifier = Modifier.fillMaxWidth()) {
        Text(note.text, style = MaterialTheme.typography.bodyMedium, maxLines = 4)
        Text(note.progress.progressLabel(), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.outline)
    }
}
