import ForgejoKit
import SwiftUI

struct ReviewSummaryView: View {
    let review: PullRequestReview
    let comments: [ReviewComment]

    private var stateIcon: String {
        switch ReviewState(rawValue: review.state) {
        case .approved: "checkmark.circle.fill"
        case .requestChanges: "xmark.circle.fill"
        default: "message.circle.fill"
        }
    }

    private var stateColor: Color {
        switch ReviewState(rawValue: review.state) {
        case .approved: .green
        case .requestChanges: .red
        default: .blue
        }
    }

    private var stateLabel: String {
        ReviewState(rawValue: review.state)?.label ?? review.state.lowercased()
    }

    var body: some View {
        VStack(alignment: .leading, spacing: 8) {
            HStack(spacing: 6) {
                Image(systemName: stateIcon)
                    .foregroundStyle(stateColor)
                    .font(.subheadline)
                Text(review.user?.login ?? "Unknown")
                    .font(.subheadline)
                    .fontWeight(.medium)
                Text(stateLabel)
                    .font(.subheadline)
                    .foregroundStyle(.secondary)
                Spacer()
                if let date = review.submittedAt {
                    Text(formatRelativeDate(date))
                        .font(.caption)
                        .foregroundStyle(.secondary)
                }
            }

            if let body = review.body, !body.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
                MarkdownPreview(text: body)
            }

            if !comments.isEmpty {
                DisclosureGroup("Inline comments (\(comments.count))") {
                    ForEach(comments) { comment in
                        VStack(alignment: .leading, spacing: 4) {
                            HStack(spacing: 4) {
                                Text(comment.path)
                                    .font(.caption)
                                    .fontWeight(.medium)
                                    .foregroundStyle(.blue)
                                if let line = comment.position ?? comment.originalPosition {
                                    Text("Pos \(line)")
                                        .font(.caption2)
                                        .foregroundStyle(.secondary)
                                }
                            }
                            MarkdownPreview(text: comment.body)
                        }
                        .padding(.vertical, 2)
                    }
                }
            }
        }
        .padding(.vertical, 4)
    }
}

#if DEBUG
    #Preview {
        List {
            ReviewSummaryView(
                review: .preview,
                comments: [.preview],
            )
        }
    }
#endif
