import SwiftUI
import SharedModels
import SwiftData

/// Reusable tappable tense pill that shows a tense info sheet when tapped.
/// Use this anywhere a tense name is displayed as a badge/pill.
struct TensePill: View {
    let tenseInfo: TenseInfo
    @State private var showingInfo = false

    var body: some View {
        Button {
            showingInfo = true
        } label: {
            HStack(spacing: 4) {
                Text(tenseInfo.english)
                    .font(.caption.weight(.semibold))
                Image(systemName: "info.circle")
                    .font(.caption2)
            }
            .padding(.horizontal, 12)
            .padding(.vertical, 5)
            .background(.tint.opacity(0.15), in: .capsule)
            .foregroundStyle(.tint)
        }
        .sheet(isPresented: $showingInfo) {
            TensePillSheet(tenseInfo: tenseInfo)
                .presentationDetents([.medium])
        }
    }
}

/// Also support creating from a tense ID string
extension TensePill {
    init?(tenseId: String) {
        guard let info = TenseInfo.find(tenseId) else { return nil }
        self.init(tenseInfo: info)
    }
}

// MARK: - Sheet

private struct TensePillSheet: View {
    let tenseInfo: TenseInfo
    @Environment(\.dismiss) private var dismiss
    @Query private var guides: [TenseGuide]

    private var guide: TenseGuide? {
        guides.first { $0.tenseId == tenseInfo.id }
    }

    private var description: String {
        guard let guide else { return "" }
        let body = guide.body

        let lines = body.components(separatedBy: "\n")
        var introLines: [String] = []
        var usageHeaders: [String] = []

        for line in lines {
            let trimmed = line.trimmingCharacters(in: .whitespaces)
            if trimmed.isEmpty { continue }

            let usagePattern = /^\*{1,2}(\d+)\s+(.+?)\*{0,2}$/
            if let match = trimmed.firstMatch(of: usagePattern) {
                let title = String(match.2).replacingOccurrences(of: "*", with: "")
                usageHeaders.append(title)
                continue
            }

            if trimmed.hasPrefix("*Usages") || trimmed.hasPrefix("**Usages") { continue }

            if usageHeaders.isEmpty {
                let clean = trimmed.replacingOccurrences(of: "**", with: "").replacingOccurrences(of: "*", with: "")
                if !clean.hasPrefix("-") && !clean.hasPrefix("¿") && !clean.hasPrefix("¡") {
                    introLines.append(clean)
                }
            }
        }

        var parts: [String] = []
        let intro = introLines.joined(separator: " ")
        if !intro.isEmpty { parts.append(intro) }

        if !usageHeaders.isEmpty {
            let summary = usageHeaders.enumerated().map { i, h in "\(i + 1). \(h)" }.joined(separator: "\n")
            parts.append("Used for:\n" + summary)
        }

        return parts.isEmpty ? guide.title.replacingOccurrences(of: "*", with: "") : parts.joined(separator: "\n\n")
    }

    var body: some View {
        NavigationStack {
            ScrollView {
                VStack(alignment: .leading, spacing: 16) {
                    Text(tenseInfo.spanish)
                        .font(.title2.weight(.bold))

                    Text(tenseInfo.english)
                        .font(.title3)
                        .foregroundStyle(.secondary)

                    Label(tenseInfo.mood, systemImage: "tag")
                        .font(.subheadline.weight(.medium))
                        .padding(.horizontal, 10)
                        .padding(.vertical, 4)
                        .background(.fill.tertiary, in: Capsule())

                    Divider()

                    if !description.isEmpty {
                        Text(description)
                            .font(.body)
                            .lineSpacing(4)
                    }
                }
                .padding()
                .frame(maxWidth: .infinity, alignment: .leading)
            }
            .navigationTitle("About this tense")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .confirmationAction) {
                    Button("Done") { dismiss() }
                }
            }
        }
    }
}

#Preview {
    TensePill(tenseInfo: TenseInfo.all[0])
        .modelContainer(for: TenseGuide.self, inMemory: true)
}
