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(strings.bookInfo) },
                navigationIcon = {
                    IconButton(onClick = onBack) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = strings.backToReader)
                    }
                },
                colors = themedTopAppBarColors(),
            )
        },
    ) {
        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .padding(it)
                .background(readerBackground()),
            contentPadding = PaddingValues(12.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp),
        ) {
            item {
                InfoSection(strings.titleInfo) {
                    CoverAndTitle(book, onImageOpen = onImageOpen)
                    DetailLine(strings.title, book.title)
                    DetailLine(strings.authors, book.authors.joinToString { it.displayName }.ifBlank { strings.unknownAuthor })
                    DetailLine(strings.language, book.language?.uppercase() ?: strings.notSpecified)
                    DetailLine(strings.date, book.date ?: strings.notSpecified)
                    DetailLine(strings.genres, book.genres.joinToString().ifBlank { strings.notSpecified })
                    DetailLine(strings.source, book.sourceLanguage?.uppercase() ?: strings.notSpecified)
                    if (book.annotation.isNullOrBlank().not()) {
                        Text(book.annotation.orEmpty(), style = MaterialTheme.typography.bodyMedium, lineHeight = 20.sp)
                    }
                }
            }
            item {
                InfoSection(strings.statistics) {
                    Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
                        StatBlock(strings.words, stats.words.formatCompact())
                        StatBlock(strings.sections, stats.sections.toString())
                        StatBlock(strings.images, stats.images.toString())
                    }
                }
            }
            item {
                InfoSection(strings.sourceFile) {
                    if (extras == null) {
                        Text(strings.loading, style = MaterialTheme.typography.bodyMedium)
                    } else {
                        DetailLine(strings.fileName, extras?.sourceFileName?.ifBlank { null } ?: strings.notSpecified)
                        DetailLine(strings.filePath, extras?.sourceFilePath?.ifBlank { null } ?: strings.notSpecified)
                    }
                }
            }
            item {
                InfoSection(strings.lastReadingPosition) {
                    val position = extras?.lastReadingPosition
                    if (position == null) {
                        Text(strings.noSavedPosition, style = MaterialTheme.typography.bodyMedium)
                    } else {
                        DetailLine(strings.listItem, position.itemIndex.toString())
                        DetailLine(strings.scrollOffset, "${position.scrollOffset}px")
                    }
                }
            }
            item {
                InfoSection(strings.bookmarks) {
                    val bookmarks = extras?.bookmarks.orEmpty()
                    if (extras == null) {
                        Text(strings.loading, style = MaterialTheme.typography.bodyMedium)
                    } else if (bookmarks.isEmpty()) {
                        Text(strings.noBookmarks, style = MaterialTheme.typography.bodyMedium)
                    } else {
                        bookmarks.forEach { bookmark ->
                            BookmarkInfoLine(bookmark)
                        }
                    }
                }
            }
            item {
                InfoSection(strings.notes) {
                    val notes = extras?.notes.orEmpty()
                    if (extras == null) {
                        Text(strings.loading, style = MaterialTheme.typography.bodyMedium)
                    } else if (notes.isEmpty()) {
                        Text(strings.noNotes, 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 } ?: strings.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)
    }
}
