import SwiftUI
import SwiftData

struct ContentView: View {
    @Environment(\.modelContext) private var modelContext
    @AppStorage(AppSettings.typeDetailCacheBackfillVersionKey)
    private var typeDetailCacheBackfillVersion: Int = 0
    @State private var didAttemptTypeDetailCacheBackfill = false

    var body: some View {
        TabView {
            Tab("Dashboard", systemImage: "waveform.path.ecg") {
                DashboardView()
            }
            Tab("Snapshots", systemImage: "clock.arrow.circlepath") {
                SnapshotsView()
            }
            Tab("Data Types", systemImage: "doc.text.magnifyingglass") {
                DataTypesView()
            }
            Tab("Settings", systemImage: "gearshape") {
                SettingsView()
            }
        }
        .task {
            await rebuildTypeDetailCachesIfNeeded()
        }
    }

    @MainActor
    private func rebuildTypeDetailCachesIfNeeded() async {
        guard !didAttemptTypeDetailCacheBackfill,
              typeDetailCacheBackfillVersion < AppSettings.currentTypeDetailCacheBackfillVersion else {
            return
        }
        didAttemptTypeDetailCacheBackfill = true

        try? await Task.sleep(for: .seconds(2))

        do {
            let isComplete = try SnapshotLifecycleService.rebuildMissingDetailCaches(
                context: modelContext,
                maxTypeCounts: 1
            )
            if isComplete {
                typeDetailCacheBackfillVersion = AppSettings.currentTypeDetailCacheBackfillVersion
            }
        } catch {
            assertionFailure("Failed to rebuild type detail caches: \(error)")
        }
    }
}

#Preview {
    ContentView()
        .modelContainer(for: [HealthSnapshot.self, TypeCount.self, YearlyCount.self, HealthRecord.self, TypeDistributionBin.self, DeviceProfile.self], inMemory: true)
        .environment(AppSettings())
}
