/*
 * SPDX-License-Identifier: GPL-3.0-or-later
 */
package com.runicgateway.app.ui.news

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ScrollableTabRow
import androidx.compose.material3.Tab
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.runicgateway.app.R
import com.runicgateway.app.data.api.dto.PostDto
import com.runicgateway.app.data.repository.ContentRepository.PostCategory
import com.runicgateway.app.ui.UiState
import com.runicgateway.app.ui.components.EmptyView
import com.runicgateway.app.ui.components.ErrorView
import com.runicgateway.app.ui.components.LoadingView
import com.runicgateway.app.ui.components.ShardCard

/** News hub with category tabs and a post list (PLAN.md §6.1). */
@Composable
fun NewsScreen(
    onOpenPost: (categoryUrlSlug: String, idOrSlug: String) -> Unit,
    modifier: Modifier = Modifier,
    viewModel: NewsViewModel = hiltViewModel(),
) {
    val category by viewModel.category.collectAsStateWithLifecycle()
    val state by viewModel.state.collectAsStateWithLifecycle()

    Column(modifier = modifier.fillMaxSize()) {
        ScrollableTabRow(selectedTabIndex = PostCategory.entries.indexOf(category)) {
            PostCategory.entries.forEach { cat ->
                Tab(
                    selected = cat == category,
                    onClick = { viewModel.selectCategory(cat) },
                    text = { Text(stringResource(categoryLabel(cat))) },
                )
            }
        }

        when (val s = state) {
            is UiState.Loading -> LoadingView()
            is UiState.Error -> ErrorView(s.kind, onRetry = viewModel::load)
            is UiState.Success -> {
                if (s.data.isEmpty()) {
                    EmptyView(stringResource(R.string.news_empty))
                } else {
                    PostList(s.data, category.urlSlug, onOpenPost)
                }
            }
        }
    }
}

@Composable
private fun PostList(
    posts: List<PostDto>,
    categoryUrlSlug: String,
    onOpenPost: (String, String) -> Unit,
) {
    LazyColumn(
        modifier = Modifier.fillMaxSize().padding(horizontal = 16.dp),
    ) {
        items(posts, key = { it.id }) { post ->
            PostRow(post) { onOpenPost(categoryUrlSlug, post.slug ?: post.id.toString()) }
        }
    }
}

@Composable
private fun PostRow(post: PostDto, onClick: () -> Unit) {
    ShardCard(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 6.dp)
            .clickable(onClick = onClick),
    ) {
        Column(Modifier.padding(16.dp)) {
            Text(post.title, style = MaterialTheme.typography.titleMedium)
            post.publishedAt?.let { date ->
                Text(
                    text = date,
                    style = MaterialTheme.typography.labelSmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    modifier = Modifier.padding(top = 2.dp),
                )
            }
            post.excerpt?.takeIf { it.isNotBlank() }?.let { excerpt ->
                Text(
                    text = excerpt,
                    style = MaterialTheme.typography.bodyMedium,
                    modifier = Modifier.padding(top = 8.dp),
                )
            }
        }
    }
}

private fun categoryLabel(category: PostCategory): Int = when (category) {
    PostCategory.NEWS -> R.string.news_cat_news
    PostCategory.FIVE_ON_FRIDAY -> R.string.news_cat_five_on_friday
    PostCategory.NEWSLETTER -> R.string.news_cat_newsletter
    PostCategory.SCREENSHOTS -> R.string.news_cat_screenshots
}
