import SwiftUI

struct NewConversationSheet: View {
    var appState: AppState
    var onCreated: (String) async -> Void

    @State private var email = ""
    @State private var groupName = ""
    @State private var isGroup = false
    @State private var memberEmails: [String] = [""]
    @State private var isLoading = false
    @State private var errorMessage: String?
    @Environment(\.dismiss) private var dismiss

    var body: some View {
        NavigationStack {
            Form {
                Section {
                    Toggle("Create Group", isOn: $isGroup)

                    if isGroup {
                        TextField("Group Name", text: $groupName)
                    }
                }

                Section(isGroup ? "Members" : "Recipient") {
                    if isGroup {
                        ForEach(memberEmails.indices, id: \.self) { index in
                            TextField("Email", text: $memberEmails[index])
                                .textContentType(.emailAddress)
                                .keyboardType(.emailAddress)
                                .autocapitalization(.none)
                        }
                        Button("Add Member") {
                            memberEmails.append("")
                        }
                    } else {
                        TextField("Email", text: $email)
                            .textContentType(.emailAddress)
                            .keyboardType(.emailAddress)
                            .autocapitalization(.none)
                    }
                }

                if let error = errorMessage {
                    Section {
                        Text(error)
                            .foregroundStyle(.red)
                    }
                }
            }
            .navigationTitle("New Conversation")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("Cancel") { dismiss() }
                }
                ToolbarItem(placement: .confirmationAction) {
                    Button("Create") {
                        Task { await create() }
                    }
                    .disabled(isLoading)
                }
            }
        }
    }

    private func create() async {
        isLoading = true
        errorMessage = nil

        let emails: [String]
        if isGroup {
            emails = memberEmails.map { $0.trimmed }.filter { !$0.isEmpty }
            guard !emails.isEmpty else {
                errorMessage = "Add at least one member"
                isLoading = false
                return
            }
        } else {
            guard !email.trimmed.isEmpty else {
                errorMessage = "Enter an email address"
                isLoading = false
                return
            }
            emails = [email.trimmed]
        }

        let name = isGroup && !groupName.trimmed.isEmpty ? groupName.trimmed : nil
        let (convId, message) = await appState.chatClient.createConversation(emails: emails, name: name)

        isLoading = false

        if let convId = convId {
            await onCreated(convId)
        } else {
            errorMessage = message
        }
    }
}
