import SwiftUI

struct ForwardPickerView: View {
    let message: Message
    let appState: AppState

    @Environment(\.dismiss) private var dismiss
    @State private var conversations: [Conversation] = []
    @State private var isLoading = true
    @State private var isSending = false

    var body: some View {
        NavigationStack {
            Group {
                if isLoading {
                    ProgressView("Loading conversations...")
                } else if conversations.isEmpty {
                    Text("No conversations available")
                        .foregroundStyle(.secondary)
                } else {
                    List(conversations) { conv in
                        Button {
                            forwardTo(conv)
                        } label: {
                            HStack {
                                CircularAvatarView(
                                    name: conv.displayName(currentUserId: appState.currentUser?.id ?? ""),
                                    size: 36,
                                    isGroup: conv.isGroup
                                )
                                Text(conv.displayName(currentUserId: appState.currentUser?.id ?? ""))
                                Spacer()
                            }
                        }
                        .disabled(isSending)
                    }
                }
            }
            .navigationTitle("Forward to...")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("Cancel") { dismiss() }
                }
            }
        }
        .task {
            conversations = await appState.chatClient.listConversations()
            isLoading = false
        }
    }

    private func forwardTo(_ conv: Conversation) {
        isSending = true
        Task {
            let forwardPayload: [String: Any] = [
                "forwarded_from": [
                    "sender": message.senderUsername,
                    "conversation_id": message.conversationId,
                    "message_id": message.id,
                ] as [String: Any]
            ]
            let (success, _, _) = await appState.chatClient.sendMessage(
                convId: conv.id,
                text: message.text ?? "",
                members: conv.members,
                extraPayload: forwardPayload
            )
            await MainActor.run {
                isSending = false
                if success {
                    dismiss()
                }
            }
        }
    }
}
