//
//  ProfileFieldVerificationView.swift
//  Tusker
//
//  Created by Shadowfacts on 5/6/23.
//  Copyright © 2023 Shadowfacts. All rights reserved.
//

import SwiftUI

@MainActor
struct ProfileFieldVerificationView: View {
    let acct: String
    let verifiedAt: Date
    let linkText: String
    let navigationDelegate: TuskerNavigationDelegate
    
    var body: some View {
        VStack(alignment: .leading, spacing: 8) {
            firstLine
            secondLine
        }
        .padding()
        .navigationTitle(Text("Verified Link"))
        .navigationBarTitleDisplayMode(.inline)
        .toolbar {
            ToolbarItem(placement: .cancellationAction) {
                Button("Done") {
                    navigationDelegate.dismiss(animated: true)
                }
            }
        }
        .environment(\.openURL, OpenURLAction(handler: { url in
            // dismiss the sheet/popover first
            navigationDelegate.dismiss(animated: true) {
                navigationDelegate.selected(url: url)
            }
            return .handled
        }))
    }
    
    private var firstLine: Text {
        var attrStr: AttributedString = "This link has been verified by your instance, "
        var instance = AttributedString(navigationDelegate.apiController!.instanceURL.host!)
        instance.font = .body.bold()
        attrStr += instance
        attrStr += "."
        return Text(attrStr)
    }
    
    private var secondLine: Text {
        var attrStr: AttributedString = "The page at "
        var linkStr: AttributedString
        if linkText.count > 43 {
            linkStr = AttributedString(linkText.prefix(40) + "…")
        } else {
            linkStr = AttributedString(linkText)
        }
        linkStr.link = URL(string: linkText)
        attrStr += linkStr
        attrStr += " was confirmed to link back to "
        var acctStr = AttributedString("@\(acct)")
        acctStr.font = .body.bold()
        attrStr += acctStr
        attrStr += AttributedString(" as of \(verifiedAt.formatted(date: .abbreviated, time: .shortened)).")
        return Text(attrStr)
    }
}
