import ForgejoKit
import SwiftUI

struct CommentView: View {
    let comment: IssueComment
    let currentUsername: String?
    let onSave: ((String) async -> Bool)?

    @State private var isEditing = false
    @State private var editedBody: String = ""
    @State private var displayBody: String = ""

    private var isOwnComment: Bool {
        currentUsername != nil && comment.user.login == currentUsername
    }

    var body: some View {
        VStack(alignment: .leading, spacing: 8) {
            HStack(spacing: 6) {
                Text(comment.user.login)
                    .font(.subheadline)
                    .fontWeight(.medium)
                Text(formatRelativeDate(comment.createdAt))
                    .font(.caption)
                    .foregroundStyle(.secondary)

                Spacer()

                if isOwnComment {
                    Button {
                        editedBody = displayBody
                        isEditing = true
                    } label: {
                        Image(systemName: "pencil")
                            .font(.caption)
                            .foregroundStyle(.secondary)
                    }
                    .buttonStyle(.plain)
                    .accessibilityLabel("Edit comment")
                }
            }

            MarkdownPreview(text: displayBody)

            if let assets = comment.assets, !assets.isEmpty {
                AttachmentGallery(attachments: assets)
                    .padding(.top, 4)
            }
        }
        .padding(.vertical, 4)
        .onAppear {
            displayBody = comment.body
        }
        .onChange(of: comment.body) { _, newValue in
            displayBody = newValue
        }
        .sheet(isPresented: $isEditing) {
            CommentEditSheet(text: $editedBody) { saved in
                displayBody = saved
            } onSave: { body in
                await onSave?(body) ?? false
            }
        }
    }
}

private struct CommentEditSheet: View {
    @Binding var text: String
    let onDismissWithSave: (String) -> Void
    let onSave: (String) async -> Bool
    @State private var selectedTab: EditPreviewTab = .edit
    @State private var isSaving = false
    @Environment(\.dismiss) private var dismiss

    var body: some View {
        NavigationStack {
            MarkdownEditorField(
                text: $text,
                selectedTab: $selectedTab,
                showToolbar: true,
            )
            .frame(maxHeight: .infinity)
            .padding()
            .navigationTitle("Edit Comment")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("Cancel") { dismiss() }
                }
                ToolbarItem(placement: .confirmationAction) {
                    if isSaving {
                        ProgressView()
                            .controlSize(.small)
                    } else {
                        Button("Save") {
                            Task { await save() }
                        }
                        .disabled(text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
                    }
                }
            }
        }
    }

    private func save() async {
        isSaving = true
        let success = await onSave(text)
        if success {
            onDismissWithSave(text)
            dismiss()
        }
        isSaving = false
    }
}

#if DEBUG
    #Preview {
        List {
            CommentView(
                comment: .preview, currentUsername: "testuser",

                onSave: nil,
            )
        }
    }
#endif
