import SwiftUI
import SwiftData

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

    @Query(sort: \HistoryItem.startDate, order: .reverse)
    var history: [HistoryItem] = []

    private var unlockCount: Int {
        history.count { $0.response == .unlocked }
    }

    private var percentage: Double {
        guard history.count > 0 else {
            return 0
        }
        return Double(unlockCount * 100) / Double(history.count)
    }

    var body: some View {
        NavigationView {
            List {
                HStack {
                    VStack(alignment: .leading) {
                        Text("\(history.count) requests")
                            .foregroundColor(.primary)
                            .font(.body)
                        Text(String(format: "%.1f %% success", percentage))
                            .foregroundColor(.secondary)
                            .font(.footnote)
                    }
                    Spacer()
                }
                .listRowBackground(Color.clear)

                ForEach(history) { item in
                    NavigationLink {
                        HistoryItemDetail(item: item)
                    } label: {
                        HistoryListRow(item: item)
                    }
                    .swipeActions(edge: .trailing) {
                        Button {
                            delete(item: item)
                        } label: {
                            Label("Delete", systemSymbol: .trash)
                        }.tint(.red)
                    }
                }
            }
            .navigationTitle("History")
        }
    }

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

#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 HistoryView()
            .modelContainer(container)
    } catch {
        fatalError("Failed to create model container.")
    }
}
