import SwiftUI

struct NoteRowView: View {
    let note: NoteEntity

    var body: some View {
        HStack(alignment: .center, spacing: 10) {
            CalendarBadge(date: note.createdAt)

            VStack(alignment: .leading, spacing: 4) {
                Text(displayTitle)
                    .font(.body.weight(.medium))
                    .lineLimit(2)

                HStack(spacing: 4) {
                    if note.hasAudio {
                        Image(systemName: "waveform")
                        Text(AudioPlayerView.timeString(note.audioDuration ?? 0))
                        Text("·")
                    }
                    Text(note.createdAt, format: .dateTime.hour().minute())
                    if let place = note.context.summary {
                        Text("·")
                        Text(place)
                            .lineLimit(1)
                    }
                }
                .font(.caption)
                .foregroundStyle(.secondary)

                transcriptionChip

                if !note.tags.isEmpty {
                    Text(note.tags.map { "#\($0)" }.joined(separator: " "))
                        .font(.caption)
                        .foregroundStyle(.tint)
                        .lineLimit(1)
                }
            }
        }
        .padding(.vertical, 2)
    }

    /// Audio notes with no transcript yet still need a legible title.
    private var displayTitle: String {
        if !note.title.isEmpty { return note.title }
        return note.hasAudio ? "Audio note" : "Untitled"
    }

    @ViewBuilder
    private var transcriptionChip: some View {
        switch note.audio?.transcriptionStatus {
        case .pending:
            capsule("Transcribing…", color: .secondary)
        case .failed:
            capsule("Transcription failed", color: .red)
        case .done, .none:
            EmptyView()
        }
    }

    private func capsule(_ text: String, color: Color) -> some View {
        Text(text)
            .font(.caption2)
            .foregroundStyle(color)
            .padding(.horizontal, 8)
            .padding(.vertical, 2)
            .background(color.opacity(0.12), in: Capsule())
    }
}
