import SwiftUI
import SwiftData
import SFSafeSymbols

private let df: DateFormatter = {
    let df = DateFormatter()
    df.dateStyle = .short
    df.timeStyle = .short
    df.doesRelativeDateFormatting = true
    return df
}()

struct HistoryItemDetail: View {
    
    @Environment(\.modelContext)
    private var modelContext

    let item: HistoryItem

    @Environment(\.dismiss) private var dismiss
    
    private var entryTime: String {
        df.string(from: item.startDate)
    }

    var body: some View {
        List {
            SettingsListTextItem(
                title: "Status",
                value: item.response.description)
            SettingsListTextItem(
                title: "Date",
                value: entryTime)
            SettingsListTextItem(
                title: "Connection",
                value: item.route.displayName)
            SettingsListTextItem(
                    title: "Round Trip Time",
                    value: "\(Int(item.roundTripTime * 1000)) ms")
            SettingsListTextItem(
                title: "Client challenge",
                value: "\(item.message.clientChallenge)")
            SettingsListTextItem(
                title: "Server challenge",
                value: "\(item.message.serverChallenge)")
            Button {
                delete(item: item)
            } label: {
                HStack {
                    Spacer()
                    Label("Delete", systemSymbol: .trash)
                    Spacer()
                }
            }
            .listRowBackground(
                RoundedRectangle(cornerSize: CGSize(width: 8, height: 8))
                    .fill(.red)
            )
            .foregroundColor(.white)
        }.navigationTitle("Details")
    }

    private func delete(item: HistoryItem) {
        modelContext.delete(item)
        dismiss()
    }
}

#Preview {
    do {
        let config = ModelConfiguration(isStoredInMemoryOnly: true)
        let container = try ModelContainer(for: HistoryItem.self, configurations: config)
        
        let item = HistoryItem.mock
        container.mainContext.insert(item)
        try container.mainContext.save()
        return HistoryItemDetail(item: .mock)
            .modelContainer(container)
    } catch {
        fatalError("Failed to create model container.")
    }
}
