//
//  NewAlarmView.swift
//  LeCountdown
//
//  Created by Laurent Morvillier on 01/02/2023.
//

import SwiftUI
import CoreData
import WidgetKit

struct NewAlarmView: View {
    
    @Environment(\.managedObjectContext) private var viewContext
    
    @Binding var isPresented: Bool

    var body: some View {
        AlarmEditView(isPresented: $isPresented)
            .environment(\.managedObjectContext, viewContext)
            .navigationTitle("New alarm")
    }

}

struct AlarmEditView: View {
    
    @Environment(\.managedObjectContext) private var viewContext
    @Environment(\.dismiss) private var dismiss
    
    var alarm: Alarm? = nil

    @Binding var isPresented: Bool
    
    @State var time: Date = Date()
    
    @State var nameString: String = ""

    @State var soundRepeatCount: Int16 = 0
    @State var image: CoolPic = .pic1

    @State var deleteConfirmationShown: Bool = false
    @State var activityNameConfirmationShown: Bool = false
    @State fileprivate var _rename: Bool? = nil

    @State var errorShown: Bool = false
    @State var error: Error? = nil
    
    @FocusState private var textFieldIsFocused: Bool

//    @FetchRequest(sortDescriptors: [])
//    private var countdowns: FetchedResults<Countdown>
    
    @State var _isAdding: Bool = false
    
    @Environment(\.isPresented) var envIsPresented

    var body: some View {
        NavigationStack {
            Rectangle()
                .frame(width: 0.0, height: 0.0)
                .onChange(of: envIsPresented) { newValue in
                    if !newValue && !self._isAdding {
                        self._save()
                    }
                }
            
            Text("todo")
//            AlarmFormView(dateBinding: self.$time,
//                          imageBinding: self.$image,
//
//
//                          soundBinding: self.$sound,
//                          repeatCountBinding: self.$soundRepeatCount)
            .onAppear {
                self._onAppear()
            }
            .confirmationDialog("", isPresented: $deleteConfirmationShown, actions: {
                Button("Yes", role: .destructive) {
                    withAnimation {
                        self._delete()
                    }
                }.keyboardShortcut(.defaultAction)
                Button("No", role: .cancel) {}
            }, message: {
                Text("Do you really want to delete?")
            })
            .confirmationDialog("", isPresented: $activityNameConfirmationShown, actions: {
                Button("Rename") {
                    self._rename = true
                    self._save()
                }
                Button("New activity") {
                    self._rename = false
                    self._save()
                }
            }, message: {
                Text("Do you wish to rename or create a new activity")
            })

            .alert("", isPresented: $errorShown, actions: { }, message: {
                Text(error?.localizedDescription ?? "error")
            })
            .toolbar {
                if self._isAdding {
                    ToolbarItem(placement: .navigationBarLeading) {
                        Button("Cancel") {
                            self._cancel()
                        }
                    }
                    ToolbarItem(placement: .navigationBarTrailing) {
                        Button("Save") {
                            self._save()
                        }
                    }
                } else {
                    ToolbarItem(placement: .navigationBarTrailing) {
                        Button {
                            self.deleteConfirmationShown = true
                        } label: {
                            Image(systemName: "trash")
                        }
                    }
                }
                ToolbarItemGroup(placement: .keyboard) {
                    Button {
                        textFieldIsFocused = false
                    } label: {
                        Image(systemName: "checkmark")
                    }
                }
            }
            .navigationTitle("Edit alarm")
        }
        
    }
    
    fileprivate func _onAppear() {
        
        self._isAdding = (self.alarm == nil)
        
        if let alarm {
            
            if let fireDate = alarm.fireDate {
                self.time = fireDate
            }
            
            if let name = alarm.activity?.name, !name.isEmpty {
                self.nameString = name
            }
            
//            self.sounds = alarm.sounds
//            self.playlists = alarm.playlists
            
            if let image = alarm.image, let coolpic = CoolPic(rawValue: image) {
                self.image = coolpic
            }
        }
        
    }
    fileprivate func _cancel() {
        viewContext.rollback()
        self.isPresented = false
    }
    
    fileprivate func _save() {
        
        let a: Alarm
        if let alarm {
            a = alarm
        } else {
            a = Alarm(context: viewContext)
        }
        
//        if self._isAdding {
//            let max = self.countdowns.map { $0.order }.max() ?? 0
//            cd.order = max + 1
//        }
        
        a.fireDate = self.time
        a.image = self.image.rawValue
        
//        a.setSounds(self.sounds)
//        a.setPlaylists(self.playlists)
        
        a.repeatCount = self.soundRepeatCount
        
        if !self.nameString.isEmpty {
            
            if let activity = a.activity, let currentActivityName = activity.name, self.nameString != currentActivityName {
                
                switch self._rename {
                case .none:
                    self.activityNameConfirmationShown = true
                    return
                case .some(let rename):
                    if rename {
                        activity.name = self.nameString
                    } else {
                        a.activity = CoreDataRequests.getOrCreateActivity(name: self.nameString)
                    }
                }
            } else {
                a.activity = CoreDataRequests.getOrCreateActivity(name: self.nameString)
            }
            
        }
        
        self._saveContext()
        
        WidgetCenter.shared.reloadAllTimelines() // refreshes the visual of existing widgets
        
        self._popOrDismiss()
    }
    
    fileprivate func _popOrDismiss() {
        if self._isAdding {
            self.isPresented = false
        } else {
            dismiss()
        }
    }
    
    fileprivate func _delete() {
        
        guard let alarm else {
            return
        }
        
        viewContext.delete(alarm)
        self._saveContext()

        WidgetCenter.shared.reloadAllTimelines() // refreshes the visual of existing widgets

        self._popOrDismiss()
    }
    
    fileprivate func _saveContext() {
        do {
            try viewContext.save()
        } catch {
            Logger.error(error)
            self.errorShown = true
            self.error = error
        }
    }
}

struct NewAlarmView_Previews: PreviewProvider {
    static var previews: some View {
        NewAlarmView(isPresented: .constant(true))
    }
}
