/*
 * Book's Story — free and open-source Material You eBook reader.
 * Copyright (C) 2024-2026 Acclorite
 * SPDX-License-Identifier: GPL-3.0-only
 */

package org.dueattendant149.bookshelf.ui.library

import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.platform.LocalContext
import kotlinx.coroutines.flow.SharedFlow
import org.dueattendant149.bookshelf.R
import org.dueattendant149.bookshelf.presentation.book_info.BookInfoScreen
import org.dueattendant149.bookshelf.presentation.browse.BrowseScreen
import org.dueattendant149.bookshelf.presentation.history.HistoryScreen
import org.dueattendant149.bookshelf.presentation.library.LibraryEffect
import org.dueattendant149.bookshelf.presentation.reader.ReaderScreen
import org.dueattendant149.bookshelf.presentation.settings.LibrarySettingsScreen
import org.dueattendant149.bookshelf.ui.common.helpers.showToast
import org.dueattendant149.bookshelf.ui.navigator.LocalNavigator

@Composable
fun LibraryEffects(effects: SharedFlow<LibraryEffect>, focusRequester: FocusRequester) {
    val context = LocalContext.current
    val navigator = LocalNavigator.current

    LaunchedEffect(effects, focusRequester, context, navigator) {
        effects.collect { effect ->
            when (effect) {
                is LibraryEffect.OnRequestFocus -> {
                    focusRequester.requestFocus()
                }

                is LibraryEffect.OnBooksMoved -> {
                    context.getString(R.string.books_moved)
                        .showToast(context = context)
                }

                is LibraryEffect.OnBooksDeleted -> {
                    context.getString(R.string.books_deleted)
                        .showToast(context = context)
                }

                is LibraryEffect.OnNavigateToLibrarySettings -> {
                    navigator.push(LibrarySettingsScreen)
                }

                is LibraryEffect.OnNavigateToBrowse -> {
                    navigator.push(BrowseScreen)
                }

                is LibraryEffect.OnNavigateToBookInfo -> {
                    navigator.push(BookInfoScreen(bookId = effect.id))
                }

                is LibraryEffect.OnNavigateToReader -> {
                    HistoryScreen.insertHistoryChannel.trySend(effect.id)
                    navigator.push(ReaderScreen(effect.id))
                }
            }
        }
    }
}