import SwiftUI
import SharedModels

struct IrregularHighlightText: View {
    let form: String
    let spans: [IrregularSpan]
    var font: Font = .title
    var showLabels: Bool = true

    private var attributedForm: AttributedString {
        var result = AttributedString(form)

        for span in spans {
            let startIndex = form.index(form.startIndex, offsetBy: span.start, limitedBy: form.endIndex) ?? form.startIndex
            let endIndex = form.index(form.startIndex, offsetBy: span.end, limitedBy: form.endIndex) ?? form.endIndex

            guard let attrStart = AttributedString.Index(startIndex, within: result),
                  let attrEnd = AttributedString.Index(endIndex, within: result) else {
                continue
            }

            result[attrStart..<attrEnd].foregroundColor = colorForSpan(span)
        }

        return result
    }

    private var uniqueCategories: [IrregularSpan.SpanCategory] {
        var seen = Set<String>()
        return spans.compactMap { span in
            let cat = span.category
            if seen.insert(cat.rawValue).inserted {
                return cat
            }
            return nil
        }
    }

    var body: some View {
        VStack(spacing: 8) {
            Text(attributedForm)
                .font(font)

            if showLabels && !spans.isEmpty {
                HStack(spacing: 12) {
                    ForEach(uniqueCategories, id: \.rawValue) { category in
                        Label(category.rawValue, systemImage: symbolForCategory(category))
                            .font(.caption)
                            .foregroundStyle(colorForCategory(category))
                    }
                }
            }
        }
    }

    private func colorForSpan(_ span: IrregularSpan) -> Color {
        colorForCategory(span.category)
    }

    private func colorForCategory(_ category: IrregularSpan.SpanCategory) -> Color {
        switch category {
        case .spelling: .orange
        case .stemChange: .blue
        case .uniqueIrregular: .red
        }
    }

    private func symbolForCategory(_ category: IrregularSpan.SpanCategory) -> String {
        switch category {
        case .spelling: "textformat.abc"
        case .stemChange: "leaf"
        case .uniqueIrregular: "star"
        }
    }
}

#Preview {
    VStack(spacing: 30) {
        IrregularHighlightText(
            form: "tengo",
            spans: []
        )

        IrregularHighlightText(
            form: "tengo",
            spans: [
                IrregularSpan(verbId: 1, tenseId: "ind_presente", personIndex: 0, spanType: 300, pattern: 301, start: 0, end: 4)
            ]
        )
    }
    .padding()
}
