package net.sergeych.toread

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
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.FastForward
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.Palette
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Replay
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.Stop
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarDuration
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
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,
    onDeleted: (String?) -> Unit,
    onDeleteRequested: (
        request: LibraryDeleteRequest,
        remove: () -> Unit,
        restore: () -> Unit,
    ) -> Unit,
    onBack: () -> Unit,
) {
    val stats = remember(book) { BookStats.from(book) }
    val contentPlan = remember(book) { buildReaderContentPlan(book) }
    val listState = rememberLazyListState()
    val scope = rememberCoroutineScope()
    val snackbarHostState = remember { SnackbarHostState() }
    var restored by remember(fileId) { mutableStateOf(false) }
    var markedRead by remember(fileId) { mutableStateOf(false) }
    var libraryItem by remember(fileId) { mutableStateOf<LibraryItem?>(null) }
    var readAloudPanelVisible by remember(fileId) { mutableStateOf(false) }
    var readAloudSettingsVisible by remember(fileId) { mutableStateOf(false) }
    var readAloudResumeSentenceIndex by remember(fileId) { mutableStateOf<Int?>(null) }
    var userScrollGeneration by remember(fileId) { mutableStateOf(0) }
    val readAloudState by ReadAloudPlatform.state.collectAsState()
    val readAloudSettings by ReadAloudPlatform.settingsState.collectAsState()
    val platformName = getPlatform().name
    val showShareAction = platformName.startsWith("Android")
    val showViewFileAction = platformName.startsWith("Java")
    val showReadAloudAction = ReadAloudPlatform.isSupported && contentPlan.sentences.isNotEmpty()
    val activeReadAloudSentence = readAloudState.sentenceIndex
        ?.let { index -> contentPlan.sentences.getOrNull(index) }
        ?.takeIf { readAloudState.active }
    val highlightedSentence = activeReadAloudSentence
        ?.takeIf { readAloudPanelVisible }

    fun showMessage(message: String) {
        scope.launch {
            snackbarHostState.showSnackbar(message, duration = SnackbarDuration.Short)
        }
    }

    fun setReadingStatus(status: BookReadingStatus, successMessage: String) {
        scope.launch {
            if (markLibraryReadingStatus(fileId, status)) {
                libraryItem = loadLibraryItem(fileId) ?: libraryItem?.copy(readingStatus = status)
                if (status == BookReadingStatus.READ) markedRead = true
                if (status == BookReadingStatus.NEW) markedRead = false
                if (status == BookReadingStatus.NOT_INTERESTED) {
                    saveLibraryReadingPosition(
                        fileId,
                        ReadingPosition(listState.firstVisibleItemIndex, listState.firstVisibleItemScrollOffset),
                    )
                    saveActiveReadingFileId(null)
                    onBack()
                    return@launch
                }
                showMessage(successMessage)
            } else {
                showMessage(strings.couldNotUpdateBook)
            }
        }
    }

    LaunchedEffect(fileId) {
        val item = loadLibraryItem(fileId)
        libraryItem = item
        markedRead = item?.readingStatus == BookReadingStatus.READ
        if (item?.readingStatus?.shouldBecomeReadingOnOpen() == true && markLibraryReadingStatus(fileId, BookReadingStatus.READING)) {
            libraryItem = loadLibraryItem(fileId) ?: item.copy(readingStatus = BookReadingStatus.READING)
        }
    }

    DisposableEffect(fileId) {
        onDispose {
            ReadAloudPlatform.stop()
        }
    }

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

    LaunchedEffect(fileId, listState, readAloudState.active, userScrollGeneration) {
        if (readAloudState.active) return@LaunchedEffect
        snapshotFlow {
            ReadingPosition(
                listState.firstVisibleItemIndex,
                listState.firstVisibleItemScrollOffset,
                readAloudResumeSentenceIndex,
            )
        }
            .filter { restored && userScrollGeneration > 0 }
            .distinctUntilChanged()
            .debounce(750)
            .collect { position ->
                saveLibraryReadingPosition(
                    fileId,
                    position.copy(readAloudSentenceIndex = readAloudResumeSentenceIndex),
                )
            }
    }

    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 && libraryItem?.readingStatus != BookReadingStatus.TO_READ }
            .collect {
                markedRead = true
                if (markLibraryReadingStatus(fileId, BookReadingStatus.READ)) {
                    libraryItem = loadLibraryItem(fileId) ?: libraryItem?.copy(readingStatus = BookReadingStatus.READ)
                }
            }
    }

    LaunchedEffect(fileId, readAloudState.active, readAloudState.sentenceIndex) {
        val sentence = activeReadAloudSentence ?: return@LaunchedEffect
        readAloudResumeSentenceIndex = sentence.index
        val itemIndex = sentence.itemIndex
        saveLibraryReadingPosition(fileId, ReadingPosition(itemIndex, 0, sentence.index))
        if (listState.firstVisibleItemIndex != itemIndex || listState.firstVisibleItemScrollOffset != 0) {
            listState.animateScrollToItem(itemIndex, 0)
        }
    }

    Scaffold(
        contentWindowInsets = WindowInsets(0, 0, 0, 0),
        snackbarHost = { SnackbarHost(snackbarHostState) },
        topBar = {
            CompactReaderTopBar(
                title = book.title,
                onThemeToggle = onThemeToggle,
                onBookInfo = {
                    scope.launch {
                        saveLibraryReadingPosition(
                            fileId,
                            ReadingPosition(listState.firstVisibleItemIndex, listState.firstVisibleItemScrollOffset),
                        )
                        onBookInfo()
                    }
                },
                onMarkAsRead = {
                    setReadingStatus(BookReadingStatus.READ, strings.markedAsRead())
                },
                onMarkToRead = {
                    setReadingStatus(BookReadingStatus.TO_READ, strings.markedToRead())
                },
                onNotInterested = {
                    setReadingStatus(BookReadingStatus.NOT_INTERESTED, strings.markedNotInterested())
                },
                onClearMarks = {
                    setReadingStatus(BookReadingStatus.NEW, strings.removedMarks())
                },
                readingStatus = libraryItem?.readingStatus,
                favorite = libraryItem?.favorite == true,
                onFavoriteChange = { favorite ->
                    scope.launch {
                        if (markLibraryFavorite(fileId, favorite)) {
                            libraryItem = loadLibraryItem(fileId) ?: libraryItem?.copy(favorite = favorite)
                            showMessage(if (favorite) strings.addedToFavorites() else strings.removedFromFavorites())
                        } else {
                            showMessage(strings.couldNotUpdateBook)
                        }
                    }
                },
                showShareAction = showShareAction,
                onShare = {
                    scope.launch {
                        val shared = shareLibraryBookFile(fileId)
                        showMessage(if (shared) strings.shareOpened() else strings.couldNotShareBook())
                    }
                },
                showViewFileAction = showViewFileAction,
                onViewFile = {
                    scope.launch {
                        val opened = viewLibraryBookFile(fileId)
                        showMessage(if (opened) strings.openedFileLocation() else strings.couldNotOpenFileLocation())
                    }
                },
                showReadAloudAction = showReadAloudAction,
                onReadAloud = {
                    val position = ReadingPosition(
                        listState.firstVisibleItemIndex,
                        listState.firstVisibleItemScrollOffset,
                        readAloudResumeSentenceIndex,
                    )
                    val startIndex = contentPlan.resumeSentenceIndex(position)
                    ReadAloudPlatform.prepare(fileId, book.title, contentPlan.sentences, startIndex)
                    readAloudPanelVisible = true
                    ReadAloudPlatform.play()
                },
                onDelete = {
                    onDeleteRequested(
                        LibraryDeleteRequest(fileId, book.title),
                        {
                            scope.launch {
                                saveActiveReadingFileId(null)
                            }
                            onDeleted(null)
                        },
                        {
                            scope.launch {
                                saveActiveReadingFileId(fileId)
                            }
                        },
                    )
                },
                onBack = {
                    scope.launch {
                        saveLibraryReadingPosition(
                            fileId,
                            ReadingPosition(listState.firstVisibleItemIndex, listState.firstVisibleItemScrollOffset),
                        )
                        saveActiveReadingFileId(null)
                        onBack()
                    }
                },
            )
        },
    ) {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .padding(it)
                .background(readerBackground()),
        ) {
            Column(Modifier.fillMaxSize()) {
                ContinuousBookReader(
                    book = book,
                    stats = stats,
                    modifier = Modifier.weight(1f),
                    listState = listState,
                    contentPlan = contentPlan,
                    highlightedSentence = highlightedSentence,
                    onUserScroll = { userScrollGeneration += 1 },
                    onImageOpen = onImageOpen,
                )
                if (readAloudPanelVisible && readAloudState.active) {
                    ReadAloudPanel(
                        playing = readAloudState.playing,
                        onPlayStop = {
                            if (readAloudState.playing) {
                                ReadAloudPlatform.stop()
                                readAloudPanelVisible = false
                            } else {
                                ReadAloudPlatform.play()
                            }
                        },
                        onBack = { ReadAloudPlatform.skip(-1) },
                        onForward = { ReadAloudPlatform.skip(1) },
                        onSettings = {
                            ReadAloudPlatform.refreshSettings()
                            readAloudSettingsVisible = true
                        },
                    )
                }
            }
        }
    }

    if (readAloudSettingsVisible) {
        ReadAloudSettingsDialog(
            state = readAloudSettings,
            onDismiss = { readAloudSettingsVisible = false },
            onEngineSelected = { ReadAloudPlatform.selectEngine(it) },
            onVoiceSelected = { ReadAloudPlatform.selectVoice(it) },
        )
    }
}

@Composable
private fun CompactReaderTopBar(
    title: String,
    onThemeToggle: () -> Unit,
    onBookInfo: () -> Unit,
    onMarkAsRead: () -> Unit,
    onMarkToRead: () -> Unit,
    onNotInterested: () -> Unit,
    onClearMarks: () -> Unit,
    readingStatus: BookReadingStatus?,
    favorite: Boolean,
    onFavoriteChange: (Boolean) -> Unit,
    showShareAction: Boolean,
    onShare: () -> Unit,
    showViewFileAction: Boolean,
    onViewFile: () -> Unit,
    showReadAloudAction: Boolean,
    onReadAloud: () -> Unit,
    onDelete: () -> Unit,
    onBack: () -> Unit,
) {
    var menuOpen by remember { mutableStateOf(false) }

    ThemedTopBarSurface {
        Row(
            modifier = Modifier.fillMaxWidth().height(48.dp),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            IconButton(onClick = onBack) {
                Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = strings.backToLibrary)
            }
            Text(
                title,
                style = MaterialTheme.typography.titleSmall,
                maxLines = 1,
                modifier = Modifier.weight(1f),
            )
            IconButton(onClick = onThemeToggle) {
                Icon(Icons.Filled.Palette, contentDescription = strings.readerTheme)
            }
            if (showReadAloudAction) {
                IconButton(onClick = onReadAloud) {
                    Icon(Icons.AutoMirrored.Filled.VolumeUp, contentDescription = strings.readAloud)
                }
            }
            Box {
                IconButton(onClick = { menuOpen = true }) {
                    Icon(Icons.Filled.MoreVert, contentDescription = strings.readerMenu)
                }
                DropdownMenu(expanded = menuOpen, onDismissRequest = { menuOpen = false }) {
                    DropdownMenuItem(
                        text = { Text(strings.info) },
                        onClick = {
                            menuOpen = false
                            onBookInfo()
                        },
                    )
                    HorizontalDivider()
                    DropdownMenuItem(
                        text = { Text(strings.markAsRead) },
                        onClick = {
                            menuOpen = false
                            onMarkAsRead()
                        },
                    )
                    if (readingStatus == BookReadingStatus.TO_READ) {
                        DropdownMenuItem(
                            text = { Text(strings.removeToRead) },
                            onClick = {
                                menuOpen = false
                                onClearMarks()
                            },
                        )
                    } else {
                        DropdownMenuItem(
                            text = { Text(strings.markToRead) },
                            onClick = {
                                menuOpen = false
                                onMarkToRead()
                            },
                        )
                    }
                    DropdownMenuItem(
                        text = { Text(strings.notInterested) },
                        onClick = {
                            menuOpen = false
                            onNotInterested()
                        },
                    )
                    DropdownMenuItem(
                        text = { Text(strings.clearMarks) },
                        onClick = {
                            menuOpen = false
                            onClearMarks()
                        },
                    )
                    DropdownMenuItem(
                        text = { Text(if (favorite) strings.removeFavorite else strings.addFavorite) },
                        onClick = {
                            menuOpen = false
                            onFavoriteChange(!favorite)
                        },
                    )
                    if (showShareAction || showViewFileAction) {
                        HorizontalDivider()
                    }
                    if (showShareAction) {
                        DropdownMenuItem(
                            text = { Text(strings.share) },
                            onClick = {
                                menuOpen = false
                                onShare()
                            },
                        )
                    }
                    if (showViewFileAction) {
                        DropdownMenuItem(
                            text = { Text(strings.viewFile) },
                            onClick = {
                                menuOpen = false
                                onViewFile()
                            },
                        )
                    }
                    HorizontalDivider()
                    DropdownMenuItem(
                        text = { Text(strings.delete) },
                        onClick = {
                            menuOpen = false
                            onDelete()
                        },
                    )
                }
            }
        }
    }
}

@Composable
private fun ReadAloudPanel(
    playing: Boolean,
    onPlayStop: () -> Unit,
    onBack: () -> Unit,
    onForward: () -> Unit,
    onSettings: () -> Unit,
) {
    Surface(
        tonalElevation = 3.dp,
        shadowElevation = 4.dp,
        color = MaterialTheme.colorScheme.surface,
        modifier = Modifier.fillMaxWidth(),
    ) {
        Row(
            modifier = Modifier.fillMaxWidth().height(56.dp).padding(horizontal = 12.dp),
            horizontalArrangement = Arrangement.Center,
            verticalAlignment = Alignment.CenterVertically,
        ) {
            IconButton(onClick = onBack) {
                Icon(Icons.Filled.Replay, contentDescription = strings.previousSentence)
            }
            IconButton(onClick = onPlayStop) {
                Icon(
                    if (playing) Icons.Filled.Stop else Icons.Filled.PlayArrow,
                    contentDescription = if (playing) strings.stopReading else strings.startReading,
                )
            }
            IconButton(onClick = onForward) {
                Icon(Icons.Filled.FastForward, contentDescription = strings.nextSentence)
            }
            IconButton(onClick = onSettings) {
                Icon(Icons.Filled.Settings, contentDescription = strings.readAloudSettings)
            }
        }
    }
}

@Composable
private fun ReadAloudSettingsDialog(
    state: ReadAloudSettingsState,
    onDismiss: () -> Unit,
    onEngineSelected: (String?) -> Unit,
    onVoiceSelected: (String?) -> Unit,
) {
    var engineMenuOpen by remember { mutableStateOf(false) }
    var voiceMenuOpen by remember { mutableStateOf(false) }
    val selectedEngineLabel = state.engines.firstOrNull { it.id == state.selectedEngineId }?.label ?: strings.systemDefault
    val selectedVoiceLabel = state.voices.firstOrNull { it.id == state.selectedVoiceId }
        ?.let { "${it.label} (${it.localeTag})" }
        ?: strings.autoRussian

    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text(strings.readAloud) },
        text = {
            Column {
                Text(strings.ttsEngine, style = MaterialTheme.typography.labelMedium)
                Box {
                    TextButton(onClick = { engineMenuOpen = true }) {
                        Text(selectedEngineLabel)
                    }
                    DropdownMenu(expanded = engineMenuOpen, onDismissRequest = { engineMenuOpen = false }) {
                        DropdownMenuItem(
                            text = { Text(strings.systemDefault) },
                            onClick = {
                                engineMenuOpen = false
                                onEngineSelected(null)
                            },
                        )
                        state.engines.forEach { engine ->
                            DropdownMenuItem(
                                text = { Text(engine.label) },
                                onClick = {
                                    engineMenuOpen = false
                                    onEngineSelected(engine.id)
                                },
                            )
                        }
                    }
                }

                Text(strings.offlineVoice, style = MaterialTheme.typography.labelMedium)
                Box {
                    TextButton(onClick = { voiceMenuOpen = true }, enabled = !state.loading && state.voices.isNotEmpty()) {
                        Text(selectedVoiceLabel)
                    }
                    DropdownMenu(expanded = voiceMenuOpen, onDismissRequest = { voiceMenuOpen = false }) {
                        DropdownMenuItem(
                            text = { Text(strings.autoRussian) },
                            onClick = {
                                voiceMenuOpen = false
                                onVoiceSelected(null)
                            },
                        )
                        state.voices.forEach { voice ->
                            DropdownMenuItem(
                                text = { Text("${voice.label} (${voice.localeTag})") },
                                onClick = {
                                    voiceMenuOpen = false
                                    onVoiceSelected(voice.id)
                                },
                            )
                        }
                    }
                }

                if (state.loading) {
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        CircularProgressIndicator()
                        Text(strings.loadingVoices, modifier = Modifier.padding(start = 12.dp))
                    }
                }
                state.message?.let { Text(it, color = MaterialTheme.colorScheme.error) }
            }
        },
        confirmButton = {
            TextButton(onClick = onDismiss) {
                Text(strings.done)
            }
        },
    )
}
