package de.sebse.fuplanner2.ui.details_announcements

import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.lifecycle.viewmodel.compose.viewModel
import de.sebse.fuplanner2.MenuItem
import de.sebse.fuplanner2.R
import de.sebse.fuplanner2.Tools
import de.sebse.fuplanner2.database.Announcement
import de.sebse.fuplanner2.ui.details.components.AnnouncementItem
import de.sebse.fuplanner2.ui.theme.AppTheme
import de.sebse.fuplanner2.ui.tools.previews.AnnouncementPreviewProvider
import de.sebse.fuplanner2.ui.tools.viewmodels.DetailsViewModel
import de.sebse.fuplanner2.ui.tools.viewmodels.DetailsViewModelFactory

@Composable
fun CourseAnnouncementsScreen(tools: Tools, id: Long) {
    val coursesViewModel: DetailsViewModel =
        viewModel(factory = DetailsViewModelFactory(id))
    val course by coursesViewModel.course.observeAsState()
    val announcements by coursesViewModel.announcements.observeAsState()
    val title = course?.title ?: stringResource(id = R.string.description)
    LaunchedEffect(title) {
        tools.setTitle(title)
    }
    announcements?.let { CourseAnnouncementsScreen(it) { uid ->
        tools.navTo("${MenuItem.Courses.route}/$id/announcements/${uid}")
    } }
}

@Composable
fun CourseAnnouncementsScreen(announcements: List<Announcement>, onClick: (Long) -> Unit) {
    LazyColumn {
        items(announcements) {
            AnnouncementItem(it) {
                it.uid?.let { uid -> onClick(uid) }
            }
        }
    }
}

@Preview
@Composable
fun CourseAnnouncementsScreenPreview() {
    AppTheme {
        CourseAnnouncementsScreen(
            AnnouncementPreviewProvider().values.take(10).toList()
        ) { }
    }
}
