import SwiftUI
import Bedrock

struct ScannedResultView: View {
    let code: String
    let onConfirm: () -> Void

    private var isVCard: Bool {
        code.contains("BEGIN:VCARD")
    }

    private var parsedName: String? {
        guard isVCard else { return nil }
        let lines = code.components(separatedBy: "\n")
        for line in lines {
            if line.hasPrefix("FN:") {
                return String(line.dropFirst(3))
            }
        }
        return nil
    }

    var body: some View {
        VStack(spacing: Design.Spacing.xLarge) {
            Image(systemName: isVCard ? "person.crop.circle.badge.checkmark" : "qrcode")
                .font(.system(size: Design.IconSize.xxxLarge))
                .foregroundStyle(Color.Accent.red)

            if isVCard {
                VStack(spacing: Design.Spacing.small) {
                    Text("Card Found!")
                        .typography(.title2)
                        .bold()
                        .foregroundStyle(Color.Text.primary)

                    if let name = parsedName {
                        Text(name)
                            .typography(.heading)
                            .foregroundStyle(Color.Text.secondary)
                    }
                }
            } else {
                Text("QR Code Scanned")
                    .typography(.title2)
                    .bold()
                    .foregroundStyle(Color.Text.primary)
            }

            if isVCard {
                Button(String.localized("Save Contact"), systemImage: "person.badge.plus") {
                    onConfirm()
                }
                .buttonStyle(.borderedProminent)
                .tint(Color.Accent.red)
                .controlSize(.large)
            } else {
                Text("This doesn't appear to be a business card QR code.")
                    .typography(.subheading)
                    .foregroundStyle(Color.Text.secondary)
                    .multilineTextAlignment(.center)
                    .padding(.horizontal, Design.Spacing.xLarge)
            }
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Color.AppBackground.base)
    }
}
