import SwiftUI
import Bedrock

struct RootView: View {
    @Bindable var store: RitualStore
    @Bindable var settingsStore: SettingsStore
    @Bindable var categoryStore: CategoryStore
    @Environment(\.scenePhase) private var scenePhase
    @State private var selectedTab: RootTab
    @State private var analyticsPrewarmTask: Task<Void, Never>?
    
    /// The available tabs in the app.
    enum RootTab: Hashable {
        case today
        case rituals
        case insights
        case history
        case settings
    }
    
    /// Creates a RootView with an optional initial tab.
    /// - Parameters:
    ///   - store: The ritual store
    ///   - settingsStore: The settings store
    ///   - categoryStore: The category store
    ///   - initialTab: The tab to show on first appearance (defaults to .today)
    init(
        store: RitualStore,
        settingsStore: SettingsStore,
        categoryStore: CategoryStore,
        initialTab: RootTab = .today
    ) {
        self.store = store
        self.settingsStore = settingsStore
        self.categoryStore = categoryStore
        self._selectedTab = State(initialValue: initialTab)
    }

    var body: some View {
        TabView(selection: $selectedTab) {
            Tab(String(localized: "Today"), systemImage: "sun.max.fill", value: RootTab.today) {
                NavigationStack {
                    TodayView(store: store, categoryStore: categoryStore)
                }
            }

            Tab(String(localized: "Rituals"), systemImage: "sparkles", value: RootTab.rituals) {
                NavigationStack {
                    RitualsView(store: store, categoryStore: categoryStore)
                }
            }

            Tab(String(localized: "Insights"), systemImage: "chart.bar.fill", value: RootTab.insights) {
                NavigationStack {
                    InsightsView(store: store)
                }
            }

            Tab(String(localized: "History"), systemImage: "calendar", value: RootTab.history) {
                NavigationStack {
                    HistoryView(store: store)
                }
            }

            Tab(String(localized: "Settings"), systemImage: "gearshape.fill", value: RootTab.settings) {
                NavigationStack {
                    SettingsView(store: settingsStore, ritualStore: store, categoryStore: categoryStore)
                }
            }
        }
        .tint(AppAccent.primary)
        .background(AppSurface.primary.ignoresSafeArea())
        .onChange(of: scenePhase) { _, newPhase in
            if newPhase == .active {
                refreshCurrentTab()
            }
        }
        .onChange(of: selectedTab) { _, _ in
            refreshCurrentTab()
        }
    }

    private func refreshCurrentTab() {
        Task {
            // Let tab selection UI update before refreshing data.
            await Task.yield()
            store.refresh()
            analyticsPrewarmTask?.cancel()
            if selectedTab != .insights {
                analyticsPrewarmTask = Task { @MainActor in
                    try? await Task.sleep(for: .milliseconds(350))
                    guard !Task.isCancelled else { return }
                    store.refreshAnalyticsIfNeeded()
                    store.refreshInsightCardsIfNeeded()
                }
            }
            if selectedTab == .settings {
                settingsStore.refresh()
                await store.reminderScheduler.refreshStatus()
            }
        }
    }
}

#Preview {
    RootView(store: RitualStore.preview, settingsStore: SettingsStore.preview, categoryStore: CategoryStore.preview)
}
