import SwiftUI

struct PinnedMessagesView: View {
    let messages: [Message]
    var onScrollTo: ((String) -> Void)?

    @Environment(\.dismiss) private var dismiss

    var body: some View {
        NavigationStack {
            Group {
                if messages.isEmpty {
                    Text("No pinned messages")
                        .foregroundStyle(.secondary)
                } else {
                    List(messages) { message in
                        Button {
                            dismiss()
                            onScrollTo?(message.id)
                        } label: {
                            VStack(alignment: .leading, spacing: 4) {
                                HStack {
                                    Image(systemName: "pin.fill")
                                        .font(.caption)
                                        .foregroundStyle(.orange)
                                    Text(message.senderUsername)
                                        .font(.caption.bold())
                                    Spacer()
                                    Text(formatTime(message.createdAt))
                                        .font(.caption2)
                                        .foregroundStyle(.secondary)
                                }
                                Text(message.text ?? "")
                                    .font(.body)
                                    .lineLimit(3)
                            }
                            .padding(.vertical, 4)
                        }
                        .buttonStyle(.plain)
                    }
                }
            }
            .navigationTitle("Pinned Messages")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("Done") { dismiss() }
                }
            }
        }
    }

    private func formatTime(_ date: Date) -> String {
        let formatter = DateFormatter()
        if Calendar.current.isDateInToday(date) {
            formatter.dateFormat = "HH:mm"
        } else {
            formatter.dateFormat = "MMM d, HH:mm"
        }
        return formatter.string(from: date)
    }
}
