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

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.ArrowBack
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.PersonAdd
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 de.oaa.xxx.app.data.model.FriendshipDto
import de.oaa.xxx.app.data.model.User
import de.oaa.xxx.app.ui.viewmodel.SocialViewModel

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun FriendsScreen(
    viewModel: SocialViewModel,
    currentUserId: String,
    onNavigateBack: () -> Unit,
    onOpenMessages: (String) -> Unit
) {
    val friends by viewModel.friends.collectAsState()
    val pending by viewModel.pending.collectAsState()
    val searchResults by viewModel.searchResults.collectAsState()
    val isLoading by viewModel.isLoading.collectAsState()
    var selectedTab by remember { mutableIntStateOf(0) }
    var searchQuery by remember { mutableStateOf("") }
    var showSearch by remember { mutableStateOf(false) }

    LaunchedEffect(Unit) { viewModel.loadFriends() }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("Freunde") },
                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) viewModel.searchUsers(it)
                    },
                    label = { Text("Benutzer suchen...") },
                    modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),
                    trailingIcon = {
                        IconButton(onClick = { viewModel.searchUsers(searchQuery) }) {
                            Icon(Icons.Default.Search, contentDescription = "Suchen")
                        }
                    },
                    singleLine = true
                )

                LazyColumn(
                    modifier = Modifier.fillMaxWidth(),
                    contentPadding = PaddingValues(horizontal = 16.dp),
                    verticalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    items(searchResults) { user ->
                        SearchUserCard(user = user, onSendRequest = {
                            user.userId?.let { viewModel.sendFriendRequest(it) }
                        })
                    }
                }
            } else {
                TabRow(selectedTabIndex = selectedTab) {
                    Tab(selected = selectedTab == 0, onClick = { selectedTab = 0 }, text = { Text("Freunde (${friends.size})") })
                    Tab(selected = selectedTab == 1, onClick = { selectedTab = 1 }, text = { Text("Anfragen (${pending.size})") })
                }

                if (isLoading) {
                    Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                        CircularProgressIndicator()
                    }
                } else if (selectedTab == 0) {
                    LazyColumn(
                        contentPadding = PaddingValues(16.dp),
                        verticalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        items(friends) { friendship ->
                            FriendCard(
                                friendship = friendship,
                                currentUserId = currentUserId,
                                onMessage = { partnerId -> onOpenMessages(partnerId) },
                                onRemove = { viewModel.rejectRequest(friendship.friendshipId ?: "") }
                            )
                        }
                    }
                } else {
                    LazyColumn(
                        contentPadding = PaddingValues(16.dp),
                        verticalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        items(pending) { request ->
                            PendingRequestCard(
                                request = request,
                                currentUserId = currentUserId,
                                onAccept = { viewModel.acceptRequest(request.friendshipId ?: "") },
                                onReject = { viewModel.rejectRequest(request.friendshipId ?: "") }
                            )
                        }
                    }
                }
            }
        }
    }
}

@Composable
fun SearchUserCard(user: User, onSendRequest: () -> Unit) {
    Card(modifier = Modifier.fillMaxWidth(), colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface)) {
        Row(modifier = Modifier.padding(12.dp), verticalAlignment = Alignment.CenterVertically) {
            Text(user.name ?: "(Unbekannt)", modifier = Modifier.weight(1f), fontWeight = FontWeight.Medium)
            IconButton(onClick = onSendRequest) {
                Icon(Icons.Default.PersonAdd, contentDescription = "Anfrage senden", tint = MaterialTheme.colorScheme.primary)
            }
        }
    }
}

@Composable
fun FriendCard(friendship: FriendshipDto, currentUserId: String, onMessage: (String) -> Unit, onRemove: () -> Unit) {
    val partnerName = if (friendship.senderId == currentUserId) friendship.receiverName else friendship.senderName
    val partnerId = if (friendship.senderId == currentUserId) friendship.receiverId else friendship.senderId
    Card(modifier = Modifier.fillMaxWidth(), colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface)) {
        Row(modifier = Modifier.padding(12.dp), verticalAlignment = Alignment.CenterVertically) {
            Text(partnerName ?: "(Unbekannt)", modifier = Modifier.weight(1f), fontWeight = FontWeight.Medium)
            IconButton(onClick = { partnerId?.let(onMessage) }) {
                Icon(Icons.Default.Check, contentDescription = "Nachricht", tint = MaterialTheme.colorScheme.primary)
            }
        }
    }
}

@Composable
fun PendingRequestCard(request: FriendshipDto, currentUserId: String, onAccept: () -> Unit, onReject: () -> Unit) {
    val name = if (request.senderId == currentUserId) request.receiverName else request.senderName
    Card(modifier = Modifier.fillMaxWidth(), colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface)) {
        Row(modifier = Modifier.padding(12.dp), verticalAlignment = Alignment.CenterVertically) {
            Column(modifier = Modifier.weight(1f)) {
                Text(name ?: "(Unbekannt)", fontWeight = FontWeight.Medium)
                val direction = if (request.senderId == currentUserId) "Gesendet" else "Empfangen"
                Text(direction, fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f))
            }
            if (request.senderId != currentUserId) {
                IconButton(onClick = onAccept) {
                    Icon(Icons.Default.Check, contentDescription = "Annehmen", tint = MaterialTheme.colorScheme.primary)
                }
            }
            IconButton(onClick = onReject) {
                Icon(Icons.Default.Close, contentDescription = "Ablehnen", tint = MaterialTheme.colorScheme.error)
            }
        }
    }
}
