import ForgejoKit
import SwiftUI

struct CommentSheet: View {
    let users: [User]
    var onUploadImage: ((Data, String, String) async throws -> String)?
    var onSubmit: (String) async throws -> Void

    @State private var text = ""
    @State private var selectedTab: EditPreviewTab = .edit
    @State private var isSubmitting = false
    @State private var errorMessage: String?
    @State private var showError = false
    @Environment(\.dismiss) private var dismiss

    var body: some View {
        NavigationStack {
            Group {
                if users.isEmpty {
                    MarkdownEditorField(
                        text: $text,
                        selectedTab: $selectedTab,
                        showToolbar: true,
                        onUploadImage: onUploadImage,
                    )
                } else {
                    MentionableEditorField(
                        text: $text,
                        selectedTab: $selectedTab,
                        users: users,
                        showToolbar: true,
                        onUploadImage: onUploadImage,
                    )
                }
            }
            .padding()
            .navigationTitle("New Comment")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("Cancel") { dismiss() }
                }
                ToolbarItem(placement: .confirmationAction) {
                    if isSubmitting {
                        ProgressView()
                            .controlSize(.small)
                    } else {
                        Button("Submit") {
                            Task { await submit() }
                        }
                        .disabled(text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || isSubmitting)
                    }
                }
            }
            .errorAlert(message: $errorMessage, isPresented: $showError)
        }
    }

    private func submit() async {
        isSubmitting = true
        do {
            try await onSubmit(text.trimmingCharacters(in: .whitespacesAndNewlines))
            dismiss()
        } catch {
            errorMessage = error.localizedDescription
            showError = true
        }
        isSubmitting = false
    }
}

#if DEBUG
    #Preview {
        CommentSheet(users: [.preview, .previewBot]) { _ in }
    }
#endif
