import SwiftUI
import HealthDB
import HealthKit
import HealthKitExtensions

struct GenericSampleList<Sample, Content>: View where Content: View, Sample: HKSampleContainer {

    let sampleView: (Sample) -> Content

    let search: (Date, Date, Bool) throws -> [Sample]

    @State
    private var samples: [Sample] = []

    @State
    private var startDate = Date.now.addingTimeInterval(-86400)

    @State
    private var endDate = Date.now

    @State
    private var sortAscending = false

    var body: some View {
        List {
            Section("Search") {
                DatePicker("Start", selection: $startDate)
                    .datePickerStyle(.compact)
                DatePicker("End", selection: $endDate)
                    .datePickerStyle(.compact)
                Toggle("Sort ascending", isOn: $sortAscending)
                Button(action: load) {
                    HStack {
                        Spacer()
                        Text("Find samples")
                        Spacer()
                    }
                }
            }
            Section("Samples") {
                ForEach(samples, id: \.uuid) { sample in
                    sampleView(sample)
                }
            }
        }.onAppear {
            load()
        }
    }

    func load() {
        print("Finding samples from \(startDate.formatted()) to \(endDate.formatted()) for \(Sample.self)")
        Task {
            do {
                try await loadSamplesAsync()
            } catch {
                print("Failed to load samples: \(error)")
            }
        }
    }

    private func loadSamplesAsync() async throws {
        let samples = try search(startDate, endDate, sortAscending)
            .sorted(ascending: false) { $0.endDate }
        print("Finished loading \(samples.count) samples")
        DispatchQueue.main.async {
            self.samples = samples
        }
    }
}

#Preview {
    NavigationStack {
        GenericSampleList(sampleView: { sample in
            HStack {
                Text(sample.quantity.description)
                Spacer()
                Text(sample.endDate.formatted())
            }
        }, search: { (_, _, _) -> [ActiveEnergyBurned] in
    [] })
    }
}
