package ru.fincode.tsudesk.feature.news.presentation.screen

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.paging.compose.collectAsLazyPagingItems
import coil.compose.AsyncImage

@Composable
fun NewsScreen(
    modifier: Modifier = Modifier,
    viewModel: NewsViewModel
) {
    val state by viewModel.state.collectAsState()
    val pagingItems = viewModel.newsPaging.collectAsLazyPagingItems()
    val colors = MaterialTheme.colorScheme

    LazyColumn(
        modifier = Modifier
            .fillMaxSize()
            .background(colors.surface),
        contentPadding = PaddingValues(bottom = 88.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {

        item {
            NewsHeader(
                query = state.query,
                onQueryChange = {
                    viewModel.onEvent(NewsEvent.QueryChanged(it))
                }
            )
        }

        items(
            count = pagingItems.itemCount,
            key = { index -> pagingItems[index]?.id ?: "placeholder_$index" }
        ) { index ->

            val item = pagingItems[index] ?: return@items

            NewsCard(
                title = item.title,
                dateText = item.dateText,
                category = item.category,
                imageUrl = item.imageUrl,
                onClick = { //TODO: open news details
                }
            )
        }
    }
}

@Composable
private fun NewsHeader(
    query: String,
    onQueryChange: (String) -> Unit
) {
    val colors = MaterialTheme.colorScheme

    Column(
        modifier = Modifier
            .fillMaxWidth()
            .background(
                colors.primaryContainer,
                shape = RoundedCornerShape(
                    bottomStart = 40.dp,
                    bottomEnd = 40.dp
                )
            )
            .padding(20.dp)
    ) {

        Text(
            "Новости",
            style = MaterialTheme.typography.headlineLarge,
            color = colors.onPrimaryContainer
        )

        Spacer(Modifier.height(6.dp))

        Text(
            "ТулГУ · Последние обновления",
            style = MaterialTheme.typography.bodyMedium,
            color = colors.onPrimaryContainer.copy(alpha = 0.8f)
        )

        Spacer(Modifier.height(16.dp))

        OutlinedTextField(
            value = query,
            onValueChange = onQueryChange,
            modifier = Modifier.fillMaxWidth(),
            singleLine = true,
            placeholder = { Text("Поиск новостей...") },
            colors = OutlinedTextFieldDefaults.colors(
                focusedBorderColor = colors.outline,
                unfocusedBorderColor = colors.outline.copy(alpha = 0.5f),
                focusedContainerColor = colors.surfaceContainer,
                unfocusedContainerColor = colors.surfaceContainer
            ),
            shape = RoundedCornerShape(20.dp)
        )
    }
}

@Composable
private fun NewsCard(
    title: String,
    dateText: String,
    category: String,
    imageUrl: String?,
    onClick: () -> Unit
) {
    val colors = MaterialTheme.colorScheme

    Card(
        modifier = Modifier
            .padding(horizontal = 16.dp)
            .fillMaxWidth(),
        onClick = onClick,
        shape = RoundedCornerShape(28.dp),
        colors = CardDefaults.cardColors(
            containerColor = colors.surfaceContainer
        )
    ) {

        Column {

            if (!imageUrl.isNullOrBlank()) {
                AsyncImage(
                    model = imageUrl,
                    contentDescription = null,
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(190.dp)
                )
            }

            Column(Modifier.padding(20.dp)) {

                Row(
                    horizontalArrangement = Arrangement.spacedBy(12.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {

                    Surface(
                        color = colors.primaryContainer,
                        shape = RoundedCornerShape(12.dp)
                    ) {
                        Text(
                            category.uppercase(),
                            style = MaterialTheme.typography.labelSmall,
                            color = colors.onPrimaryContainer,
                            modifier = Modifier.padding(horizontal = 10.dp, vertical = 4.dp)
                        )
                    }

                    Text(
                        dateText,
                        style = MaterialTheme.typography.labelMedium,
                        color = colors.onSurfaceVariant
                    )
                }

                Spacer(Modifier.height(12.dp))

                Text(
                    text = title,
                    style = MaterialTheme.typography.titleLarge,
                    color = colors.onSurface,
                    maxLines = 2,
                    overflow = TextOverflow.Ellipsis
                )
            }
        }
    }
}