package net.sergeych.toread

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.automirrored.filled.VolumeUp
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.Palette
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.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import net.sergeych.toread.fb2.Fb2Book
import net.sergeych.toread.storage.BookReadingStatus
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.launch

@Composable
@OptIn(ExperimentalMaterial3Api::class, FlowPreview::class)
internal fun BookView(
    fileId: String,
    book: Fb2Book,
    onImageOpen: (ViewedBookImage) -> Unit,
    onThemeToggle: () -> Unit,
    onBookInfo: () -> Unit,
    onBack: () -> Unit,
) {
    val stats = remember(book) { BookStats.from(book) }
    val listState = rememberLazyListState()
    val scope = rememberCoroutineScope()
    var restored by remember(fileId) { mutableStateOf(false) }
    var markedRead by remember(fileId) { mutableStateOf(false) }

    LaunchedEffect(fileId) {
        markLibraryReadingStatus(fileId, BookReadingStatus.READING)
    }

    LaunchedEffect(fileId) {
        loadLibraryReadingPosition(fileId)?.let { position ->
            listState.scrollToItem(position.itemIndex, position.scrollOffset)
        }
        restored = true
    }

    LaunchedEffect(fileId, listState) {
        snapshotFlow {
            ReadingPosition(listState.firstVisibleItemIndex, listState.firstVisibleItemScrollOffset)
        }
            .filter { restored }
            .distinctUntilChanged()
            .debounce(750)
            .collect { saveLibraryReadingPosition(fileId, it) }
    }

    LaunchedEffect(fileId, listState) {
        snapshotFlow {
            val layoutInfo = listState.layoutInfo
            val lastVisible = layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
            layoutInfo.totalItemsCount > 0 && lastVisible >= layoutInfo.totalItemsCount - 1
        }
            .filter { restored && it && !markedRead }
            .collect {
                markedRead = true
                markLibraryReadingStatus(fileId, BookReadingStatus.READ)
            }
    }

    Scaffold(
        contentWindowInsets = WindowInsets(0, 0, 0, 0),
        topBar = {
            CompactReaderTopBar(
                title = book.title,
                onThemeToggle = onThemeToggle,
                onBookInfo = {
                    scope.launch {
                        saveLibraryReadingPosition(
                            fileId,
                            ReadingPosition(listState.firstVisibleItemIndex, listState.firstVisibleItemScrollOffset),
                        )
                        onBookInfo()
                    }
                },
                onBack = {
                    scope.launch {
                        saveLibraryReadingPosition(
                            fileId,
                            ReadingPosition(listState.firstVisibleItemIndex, listState.firstVisibleItemScrollOffset),
                        )
                        saveActiveReadingFileId(null)
                        onBack()
                    }
                },
            )
        },
    ) {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .padding(it)
                .background(readerBackground()),
        ) {
            ContinuousBookReader(
                book = book,
                stats = stats,
                modifier = Modifier.fillMaxSize(),
                listState = listState,
                onImageOpen = onImageOpen,
            )
        }
    }
}

@Composable
private fun CompactReaderTopBar(
    title: String,
    onThemeToggle: () -> Unit,
    onBookInfo: () -> Unit,
    onBack: () -> Unit,
) {
    ThemedTopBarSurface {
        Row(
            modifier = Modifier.fillMaxWidth().height(48.dp),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            IconButton(onClick = onBack) {
                Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back to library")
            }
            Text(
                title,
                style = MaterialTheme.typography.titleSmall,
                maxLines = 1,
                modifier = Modifier.weight(1f),
            )
            IconButton(onClick = onThemeToggle) {
                Icon(Icons.Filled.Palette, contentDescription = "Theme")
            }
            IconButton(onClick = onBookInfo) {
                Icon(Icons.Filled.Info, contentDescription = "Properties")
            }
            IconButton(onClick = { }) {
                Icon(Icons.AutoMirrored.Filled.VolumeUp, contentDescription = "Read aloud")
            }
        }
    }
}
