package de.sebse.fuplanner2.ui.details

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.platform.LocalContext
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.database.Course
import de.sebse.fuplanner2.ui.details.components.AnnouncementItem
import de.sebse.fuplanner2.ui.details.components.LecturerItem
import de.sebse.fuplanner2.ui.details.components.QuickLinks
import de.sebse.fuplanner2.ui.shared.Heading
import de.sebse.fuplanner2.ui.theme.AppTheme
import de.sebse.fuplanner2.ui.tools.previews.AnnouncementPreviewProvider
import de.sebse.fuplanner2.ui.tools.previews.CoursePreviewProvider
import de.sebse.fuplanner2.ui.tools.viewmodels.DetailsViewModel
import de.sebse.fuplanner2.ui.tools.viewmodels.DetailsViewModelFactory
import kotlin.math.min

@Composable
fun CourseDetailsScreen(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
    val context = LocalContext.current
    LaunchedEffect(title) {
        title?.let { tools.setTitle(it) }
    }
    LaunchedEffect(true) {
        coursesViewModel.refresh(context)
    }
    CourseDetailsScreen(course, announcements, id)
}

@Composable
fun CourseDetailsScreen(course: Course?, announcement: List<Announcement>?, id: Long) {
    val announcements = announcement?.subList(0, min(announcement.size, 3)) ?: listOf()
    LazyColumn {
        item {
            QuickLinks(courseId = id)
            Heading(stringResource(R.string.lecturers))
        }
        items(course?.lecturers ?: listOf()) {
            LecturerItem(lecturer = it, courseTitle = course?.title ?: "")
        }
        item {
            Heading(stringResource(R.string.announcements))
        }
        items(items = announcements) {
            AnnouncementItem(it)
        }
        // TODO: Add current assignments, upcoming events
    }
}

@Preview
@Composable
fun CourseDetailsScreenPreview(@PreviewParameter(CoursePreviewProvider::class, 1) course: Course) {
    AppTheme {
        CourseDetailsScreen(course, AnnouncementPreviewProvider().values.take(3).toList(), course.uid!!)
    }
}
