//
//  AppDelegate.swift
//  Reflect (iOS)
//
//  Created by Trey Tartt on 1/10/22.
//

import Foundation
import UserNotifications
import UIKit
import SwiftUI

class AppDelegate: NSObject, UIApplicationDelegate {
    static var pendingDeepLinkURL: URL?

    private let savedOnboardingData = UserDefaultsStore.getOnboarding()
    @AppStorage(UserDefaultsStore.Keys.theme.rawValue, store: GroupUserDefaults.groupDefaults) private var theme: Theme = .system

    @MainActor
    func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        if let url = launchOptions?[.url] as? URL {
            AppDelegate.pendingDeepLinkURL = url
        }
        DataController.shared.removeNoForDates()
        DataController.shared.fillInMissingDates()
        UNUserNotificationCenter.current().delegate = self

        UIPageControl.appearance().currentPageIndicatorTintColor = UIColor(theme.currentTheme.labelColor)
        UIPageControl.appearance().pageIndicatorTintColor = UIColor.systemGray

        let appearance = UITabBarAppearance()
        appearance.configureWithOpaqueBackground()
        UITabBar.appearance().standardAppearance = appearance
        UITabBar.appearance().scrollEdgeAppearance = appearance

        return true
    }

}

extension AppDelegate: @preconcurrency UNUserNotificationCenterDelegate {
    func requestAuthorization() {  }

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.badge, .banner, .sound])
    }

    @MainActor
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        if let action = LocalNotification.ActionType(rawValue: response.actionIdentifier) {
            let date = ShowBasedOnVoteLogics.getCurrentVotingDate(onboardingData: savedOnboardingData)
            let mood: Mood
            switch action {
            case .horrible:
                mood = .horrible
            case .bad:
                mood = .bad
            case .average:
                mood = .average
            case .good:
                mood = .good
            case .great:
                mood = .great
            }

            // Use centralized mood logger
            MoodLogger.shared.logMood(mood, for: date, entryType: .notification)

            UNUserNotificationCenter.current().setBadgeCount(0)
        }
        completionHandler()
    }
}
