import SwiftData
import SwiftUI

struct DMListView: View {
    @Environment(ConnectionManager.self) private var manager
    @Binding var selectedConversation: String?
    @Query(
        filter: #Predicate<SavedMessage> { $0.buffer == "direct-messages" && !$0.isSystem },
        sort: \.timestamp,
        order: .reverse
    ) private var dmMessages: [SavedMessage]

    private var conversations: [(id: String, name: String, lastMessage: SavedMessage)] {
        var latest: [String: (name: String?, message: SavedMessage)] = [:]
        for message in dmMessages {
            guard let partnerId = message.characterId else { continue }
            if let existing = latest[partnerId] {
                // Prefer the partner's display name over the ID
                if existing.name == nil, !message.senderIsRecipient {
                    latest[partnerId] = (message.senderName, existing.message)
                }
            } else {
                let name: String? = message.senderIsRecipient ? nil : message.senderName
                latest[partnerId] = (name, message)
            }
        }
        return latest
            .map { (id: $0.key, name: $0.value.name ?? $0.key, lastMessage: $0.value.message) }
            .sorted { $0.lastMessage.timestamp > $1.lastMessage.timestamp }
    }

    var body: some View {
        if conversations.isEmpty {
            ContentUnavailableView(
                "No Conversations",
                systemImage: "envelope",
                description: Text("Direct messages will appear here.")
            )
        } else {
            List(conversations, id: \.id, selection: $selectedConversation) { convo in
                NavigationLink(value: convo.id) {
                    VStack(alignment: .leading, spacing: 4) {
                        HStack {
                            Text(convo.name)
                                .font(.headline)
                            Spacer()
                            Text(convo.lastMessage.timestamp, style: .time)
                                .font(.caption)
                                .foregroundStyle(.secondary)
                        }
                        Text(convo.lastMessage.content)
                            .font(.subheadline)
                            .foregroundStyle(.secondary)
                            .lineLimit(1)
                    }
                    .padding(.vertical, 4)
                }
            }
            .listStyle(.plain)
        }
    }
}
