package com.pixelized.biblib.ui.composable.scaffold

import androidx.activity.compose.BackHandler
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.ModalBottomSheetLayout
import androidx.compose.material.ModalBottomSheetState
import androidx.compose.material.ModalBottomSheetValue.Hidden
import androidx.compose.material.rememberModalBottomSheetState
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import com.pixelized.biblib.ui.screen.home.detail.DetailScreen
import com.pixelized.biblib.ui.theme.color.ShadowPalette
import kotlinx.coroutines.launch

val LocalDetailBottomSheetState = staticCompositionLocalOf<DetailBottomSheetState> {
    error("LocalBottomDetailController is not ready yet")
}

@OptIn(ExperimentalMaterialApi::class)
@Composable
fun DetailBottomSheet(
    bottomDetailState: DetailBottomSheetState = rememberDetailBottomSheetState(),
    onAuthor: (String?, Int?) -> Unit,
    onSeries: (String?, Int?) -> Unit,
    content: @Composable () -> Unit,
) {
    val scope = rememberCoroutineScope()

    CompositionLocalProvider(
        LocalDetailBottomSheetState provides bottomDetailState
    ) {
        ModalBottomSheetLayout(
            scrimColor = ShadowPalette.scrim,
            sheetState = bottomDetailState.bottomSheetState,
            sheetContent = {
                DetailScreen(
                    bookId = bottomDetailState.bookId,
                    onAuthor = onAuthor,
                    onSeries = onSeries,
                )
            },
            content = content,
        )

        BackHandler(bottomDetailState.bottomSheetState.isVisible) {
            scope.launch {
                bottomDetailState.collapse()
            }
        }
    }
}

@OptIn(ExperimentalMaterialApi::class)
@Composable
fun rememberDetailBottomSheetState(
    bottomSheetState: ModalBottomSheetState = rememberModalBottomSheetState(
        initialValue = Hidden,
        skipHalfExpanded = true,
    ),
): DetailBottomSheetState {
    val detail = rememberSaveable(bottomSheetState) {
        mutableStateOf<Int?>(null)
    }
    return remember(bottomSheetState) {
        DetailBottomSheetState(
            bottomSheetState = bottomSheetState,
            bookDetail = detail,
        )
    }
}

@OptIn(ExperimentalMaterialApi::class)
@Stable
class DetailBottomSheetState constructor(
    val bottomSheetState: ModalBottomSheetState,
    bookDetail: MutableState<Int?>,
) {
    var bookId: Int? by bookDetail
        private set

    suspend fun expandBookDetail(id: Int) {
        bookId = id
        bottomSheetState.show()
    }

    suspend fun collapse() {
        bottomSheetState.hide()
    }
}