package de.sebse.fuplanner2.ui.details_announcements

import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
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.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.tooling.preview.PreviewParameter
import androidx.lifecycle.viewmodel.compose.viewModel
import de.sebse.fuplanner2.R
import de.sebse.fuplanner2.Tools
import de.sebse.fuplanner2.database.Announcement
import de.sebse.fuplanner2.ui.shared.Heading
import de.sebse.fuplanner2.ui.shared.HtmlText
import de.sebse.fuplanner2.ui.theme.AppTheme
import de.sebse.fuplanner2.ui.tools.previews.AnnouncementPreviewProvider
import de.sebse.fuplanner2.ui.tools.viewmodels.AnnouncementViewModel
import de.sebse.fuplanner2.ui.tools.viewmodels.AnnouncementViewModelFactory
import de.sebse.fuplanner2.ui.tools.viewmodels.DetailsViewModel
import de.sebse.fuplanner2.ui.tools.viewmodels.DetailsViewModelFactory

@Composable
fun CourseAnnouncementScreen(tools: Tools, id: Long, announcementId: Long) {
    val coursesViewModel: DetailsViewModel =
        viewModel(factory = DetailsViewModelFactory(id))
    val announcementViewModel: AnnouncementViewModel =
        viewModel(factory = AnnouncementViewModelFactory(announcementId))
    val course by coursesViewModel.course.observeAsState()
    val announcement by announcementViewModel.observeAsState()
    val title = course?.title ?: stringResource(id = R.string.description)
    LaunchedEffect(title) {
        tools.setTitle(title)
    }
    announcement?.let { CourseAnnouncementScreen(it) }
}

@Composable
fun CourseAnnouncementScreen(announcement: Announcement) {
    val scrollState = rememberScrollState()
    Column(
        modifier = Modifier.verticalScroll(scrollState)
    ) {
        Heading(text = announcement.title)
        HtmlText(
            html = announcement.body,
            modifier = Modifier.fillMaxWidth()
        )
    }
}

@Preview
@Composable
fun CourseAnnouncementScreenPreview(@PreviewParameter(AnnouncementPreviewProvider::class, 2) announcement: Announcement) {
    AppTheme {
        CourseAnnouncementScreen(announcement)
    }
}
