package de.oaa.xxx.app.ui.screens.gruppen

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import de.oaa.xxx.app.data.api.ApiClient
import de.oaa.xxx.app.data.model.GruppeDto
import de.oaa.xxx.app.data.model.GruppenbeitragDto
import de.oaa.xxx.app.ui.viewmodel.FeedViewModel
import kotlinx.coroutines.launch

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun GruppenScreen(
    currentUserId: String,
    onNavigateBack: () -> Unit
) {
    var gruppen by remember { mutableStateOf<List<GruppeDto>>(emptyList()) }
    var searchResults by remember { mutableStateOf<List<GruppeDto>>(emptyList()) }
    var selectedGruppe by remember { mutableStateOf<GruppeDto?>(null) }
    var searchQuery by remember { mutableStateOf("") }
    var showSearch by remember { mutableStateOf(false) }
    var isLoading by remember { mutableStateOf(false) }
    val scope = rememberCoroutineScope()

    LaunchedEffect(Unit) {
        isLoading = true
        try {
            val resp = ApiClient.gruppenApi.getMine()
            if (resp.isSuccessful) gruppen = resp.body() ?: emptyList()
        } catch (e: Exception) {
        } finally {
            isLoading = false
        }
    }

    if (selectedGruppe != null) {
        GruppeDetailScreen(
            gruppe = selectedGruppe!!,
            currentUserId = currentUserId,
            onNavigateBack = { selectedGruppe = null }
        )
        return
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("Gruppen") },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(Icons.Default.ArrowBack, contentDescription = "Zurück")
                    }
                },
                actions = {
                    IconButton(onClick = { showSearch = !showSearch }) {
                        Icon(Icons.Default.Search, contentDescription = "Suchen")
                    }
                }
            )
        }
    ) { padding ->
        Column(modifier = Modifier.fillMaxSize().padding(padding)) {
            if (showSearch) {
                OutlinedTextField(
                    value = searchQuery,
                    onValueChange = {
                        searchQuery = it
                        if (it.length >= 2) {
                            scope.launch {
                                val resp = ApiClient.gruppenApi.search(it)
                                if (resp.isSuccessful) searchResults = resp.body() ?: emptyList()
                            }
                        }
                    },
                    label = { Text("Gruppen suchen...") },
                    modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),
                    singleLine = true
                )
            }

            if (isLoading) {
                Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                    CircularProgressIndicator()
                }
            } else {
                val displayList = if (showSearch && searchQuery.isNotBlank()) searchResults else gruppen
                LazyColumn(
                    contentPadding = PaddingValues(16.dp),
                    verticalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    items(displayList) { gruppe ->
                        GruppeCard(gruppe = gruppe, onClick = { selectedGruppe = gruppe })
                    }
                }
            }
        }
    }
}

@Composable
fun GruppeCard(gruppe: GruppeDto, onClick: () -> Unit) {
    Card(
        onClick = onClick,
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface)
    ) {
        Column(modifier = Modifier.padding(16.dp)) {
            Row(verticalAlignment = Alignment.CenterVertically) {
                Text(gruppe.name ?: "(Unbekannt)", fontWeight = FontWeight.Bold, modifier = Modifier.weight(1f))
                if (gruppe.isPrivate) {
                    Text("Privat", fontSize = 11.sp, color = MaterialTheme.colorScheme.primary)
                }
            }
            gruppe.beschreibung?.takeIf { it.isNotBlank() }?.let {
                Text(it, fontSize = 13.sp, maxLines = 2, color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.7f))
            }
            gruppe.memberCount?.let {
                Text("$it Mitglieder", fontSize = 12.sp, color = MaterialTheme.colorScheme.primary)
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun GruppeDetailScreen(
    gruppe: GruppeDto,
    currentUserId: String,
    onNavigateBack: () -> Unit
) {
    var beitraege by remember { mutableStateOf<List<GruppenbeitragDto>>(emptyList()) }
    var newPostText by remember { mutableStateOf("") }
    var isLoading by remember { mutableStateOf(false) }
    val scope = rememberCoroutineScope()

    LaunchedEffect(gruppe.gruppeId) {
        gruppe.gruppeId?.let { id ->
            isLoading = true
            try {
                val resp = ApiClient.gruppenApi.getBeitraege(id)
                if (resp.isSuccessful) beitraege = resp.body() ?: emptyList()
            } catch (e: Exception) {
            } finally {
                isLoading = false
            }
        }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(gruppe.name ?: "Gruppe") },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(Icons.Default.ArrowBack, contentDescription = "Zurück")
                    }
                }
            )
        }
    ) { padding ->
        Column(modifier = Modifier.fillMaxSize().padding(padding)) {
            Row(
                modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp).fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                OutlinedTextField(
                    value = newPostText,
                    onValueChange = { newPostText = it },
                    modifier = Modifier.weight(1f),
                    placeholder = { Text("Neuer Beitrag...") },
                    singleLine = false,
                    maxLines = 3
                )
                Spacer(modifier = Modifier.width(8.dp))
                IconButton(onClick = {
                    if (newPostText.isNotBlank()) {
                        scope.launch {
                            gruppe.gruppeId?.let { id ->
                                val beitrag = GruppenbeitragDto(text = newPostText, beitragTyp = "TEXT")
                                val resp = ApiClient.gruppenApi.createBeitrag(id, beitrag)
                                if (resp.isSuccessful) {
                                    newPostText = ""
                                    val refresh = ApiClient.gruppenApi.getBeitraege(id)
                                    if (refresh.isSuccessful) beitraege = refresh.body() ?: emptyList()
                                }
                            }
                        }
                    }
                }) {
                    Icon(Icons.Default.Add, contentDescription = "Beitrag erstellen", tint = MaterialTheme.colorScheme.primary)
                }
            }

            LazyColumn(
                contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp),
                verticalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                items(beitraege) { beitrag ->
                    BeitragCard(beitrag = beitrag, currentUserId = currentUserId)
                }
            }
        }
    }
}

@Composable
fun BeitragCard(beitrag: GruppenbeitragDto, currentUserId: String) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface)
    ) {
        Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
            Text(beitrag.authorName ?: "(Unbekannt)", fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.primary)
            Text(beitrag.text ?: "", fontSize = 15.sp)
            Text(beitrag.createdAt ?: "", fontSize = 11.sp, color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.5f))
        }
    }
}
