package dev.ulfrx.recipe.ui.screens.search

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.lazy.grid.LazyGridState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.composables.icons.lucide.Lucide
import com.composables.icons.lucide.Search
import dev.ulfrx.recipe.navigation.Screen
import dev.ulfrx.recipe.ui.components.empty.EmptyState
import dev.ulfrx.recipe.ui.components.sheet.rememberRecipeBottomSheetState
import dev.ulfrx.recipe.ui.screens.recipesheet.RecipeSheet
import dev.ulfrx.recipe.ui.screens.search.catalog.RecipeCatalogGrid
import dev.ulfrx.recipe.ui.screens.search.catalog.RecipeCatalogViewModel
import dev.ulfrx.recipe.ui.theme.RecipeTheme
import org.jetbrains.compose.resources.stringResource
import org.koin.compose.viewmodel.koinViewModel
import recipe.composeapp.generated.resources.Res
import recipe.composeapp.generated.resources.search_screen_empty_results_subtitle
import recipe.composeapp.generated.resources.search_screen_empty_results_title

@Composable
fun SearchScreen(
    viewModel: ShellSearchViewModel,
    catalogGridState: LazyGridState,
) {
    val catalogViewModel: RecipeCatalogViewModel = koinViewModel()
    val state by viewModel.state.collectAsStateWithLifecycle()
    val catalogState by catalogViewModel.state.collectAsStateWithLifecycle()
    val bottomSheetState = rememberRecipeBottomSheetState<Screen>()

    Box(
        modifier =
            Modifier
                .fillMaxSize()
                .background(RecipeTheme.colors.background),
    ) {
        if (state.isFocused) {
            Box(
                modifier =
                    Modifier
                        .fillMaxSize()
                        .windowInsetsPadding(WindowInsets.statusBars)
                        .padding(top = RecipeTheme.spacing.xl),
            ) {
                EmptyState(
                    icon = Lucide.Search,
                    title = stringResource(Res.string.search_screen_empty_results_title),
                    subtitle = stringResource(Res.string.search_screen_empty_results_subtitle),
                )
            }
        } else {
            RecipeCatalogGrid(
                state = catalogState,
                onRecipeClick = { bottomSheetState.open(Screen.RecipeDetail(it)) },
                gridState = catalogGridState,
                modifier = Modifier.fillMaxSize(),
            )
        }

        RecipeSheet(state = bottomSheetState)
    }
}
