import SwiftUI
import SwiftData

struct ContentView: View {
    @AppStorage("callWindowOnboardingDone") private var onboardingDone = false
    @AppStorage("callSuggestionDate") private var suggestionDateStr = ""

    @EnvironmentObject private var callWindowManager: CallWindowManager
    @EnvironmentObject private var appLockManager: AppLockManager
    @Environment(\.scenePhase) private var scenePhase
    @Environment(\.modelContext) private var modelContext
    @Environment(\.nahbarTheme) private var theme
    @Query private var persons: [Person]

    @State private var showingOnboarding = false
    @State private var suggestedPerson: Person? = nil
    @State private var showingSuggestion = false

    var body: some View {
        TabView {
            TodayView()
                .tabItem { Label("Heute", systemImage: "sun.max") }
                .toolbarBackground(theme.backgroundPrimary.opacity(0.88), for: .tabBar)
                .toolbarBackground(.visible, for: .tabBar)
                .toolbarColorScheme(theme.id.isDark ? .dark : .light, for: .tabBar)

            PeopleListView()
                .tabItem { Label("Menschen", systemImage: "person.2") }
                .toolbarBackground(theme.backgroundPrimary.opacity(0.88), for: .tabBar)
                .toolbarBackground(.visible, for: .tabBar)
                .toolbarColorScheme(theme.id.isDark ? .dark : .light, for: .tabBar)

            SettingsView()
                .tabItem { Label("Einstellungen", systemImage: "gearshape") }
                .toolbarBackground(theme.backgroundPrimary.opacity(0.88), for: .tabBar)
                .toolbarBackground(.visible, for: .tabBar)
                .toolbarColorScheme(theme.id.isDark ? .dark : .light, for: .tabBar)
        }
        .sheet(isPresented: $showingOnboarding) {
            CallWindowSetupView(
                manager: callWindowManager,
                isOnboarding: true,
                onDone: {
                    showingOnboarding = false
                    onboardingDone = true
                }
            )
            .presentationDetents([.large])
        }
        .sheet(isPresented: $showingSuggestion) {
            if let person = suggestedPerson {
                CallSuggestionView(person: person) {
                    person.lastSuggestedForCall = Date()
                    suggestionDateStr = ISO8601DateFormatter().string(from: Date())
                    let entry = LogEntry(type: .call, title: "Anruf mit \(person.firstName)", person: person)
                    modelContext.insert(entry)
                    person.logEntries?.append(entry)
                }
            }
        }
        .onAppear {
            syncPeopleCache()
            importPendingMoments()
            if !onboardingDone {
                showingOnboarding = true
            } else {
                checkCallWindow()
            }
        }
        .onChange(of: scenePhase) { _, phase in
            if phase == .active {
                syncPeopleCache()
                importPendingMoments()
                checkCallWindow()
            }
        }
        .onChange(of: persons) { _, _ in
            syncPeopleCache()
        }
    }

    private func checkCallWindow() {
        guard callWindowManager.isEnabled,
              callWindowManager.isCurrentlyInWindow,
              !suggestionShownToday,
              !showingSuggestion,
              !appLockManager.isLocked else { return }

        if let person = callWindowManager.selectPerson(from: persons) {
            suggestedPerson = person
            showingSuggestion = true
        }
    }

    /// Schreibt die aktuelle Personenliste in den App-Group-Cache für die Share Extension.
    private func syncPeopleCache() {
        AppGroup.savePeopleList(persons)
    }

    /// Importiert Momente, die über die Share Extension eingereiht wurden.
    private func importPendingMoments() {
        let pending = AppGroup.pendingMoments
        guard !pending.isEmpty else { return }
        for entry in pending {
            guard let name = entry["personName"],
                  let text = entry["text"],
                  let typeRaw = entry["type"] else { continue }
            let type_ = MomentType(rawValue: typeRaw) ?? .conversation
            let source_ = entry["source"].flatMap { MomentSource(rawValue: $0) }
            if let person = persons.first(where: { $0.name == name }) {
                let moment = Moment(text: text, type: type_, source: source_, person: person)
                modelContext.insert(moment)
                person.moments?.append(moment)
            }
        }
        if !pending.isEmpty {
            try? modelContext.save()
            AppGroup.clearPendingMoments()
        }
    }

    private var suggestionShownToday: Bool {
        guard !suggestionDateStr.isEmpty,
              let date = ISO8601DateFormatter().date(from: suggestionDateStr) else { return false }
        return Calendar.current.isDateInToday(date)
    }
}

#Preview {
    ContentView()
        .modelContainer(for: [Person.self, Moment.self], inMemory: true)
        .environmentObject(CallWindowManager.shared)
        .environmentObject(AppLockManager.shared)
}
