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

import SwiftUI
import CoreData
import WidgetKit

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

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

}

struct StopwatchEditView: View {
    
    @Environment(\.managedObjectContext) private var viewContext
    @Environment(\.dismiss) private var dismiss
    
    var stopwatch: Stopwatch? = nil

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

    @State var playSound: Bool = false
    @State var sound: Sound = .trainhorn
    @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()
                    }
                }
            StopwatchFormView(nameBinding: self.$nameString,
                              imageBinding: self.$image,
                              soundBinding: self.$sound, playSoundBinding: self.$playSound,
                              textFieldIsFocused: $textFieldIsFocused)
                .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 stopwatch")
        }
        
    }
    
    fileprivate func _onAppear() {
        
        self._isAdding = (self.stopwatch == nil)
        
        if let stopwatch {
            
            if let name = stopwatch.activity?.name, !name.isEmpty {
                self.nameString = name
            }
            
            if let sound = Sound(rawValue: Int(stopwatch.sound)) {
                self.sound = sound
            }
            
            if let image = stopwatch.image, let coolpic = CoolPic(rawValue: image) {
                self.image = coolpic
            }
        }
        
    }
    
    fileprivate func _cancel() {
        viewContext.rollback()
        self.isPresented = false
    }
    
    fileprivate func _save() {
        
        let sw: Stopwatch
        if let stopwatch {
            sw = stopwatch
        } else {
            sw = Stopwatch(context: viewContext)
        }
        
//        if self._isAdding {
//            let max = self.countdowns.map { $0.order }.max() ?? 0
//            cd.order = max + 1
//        }
        
        sw.image = self.image.rawValue
        
        if self.playSound {
            sw.sound = Int16(self.sound.rawValue)
        } else {
//            sw.sound = nil
        }
        
        if !self.nameString.isEmpty {
            
            if let activity = sw.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 {
                        sw.activity = CoreDataRequests.getOrCreateActivity(name: self.nameString)
                    }
                }
            } else {
                sw.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 stopwatch else {
            return
        }
        
        viewContext.delete(stopwatch)
        self._saveContext()

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

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

struct NewStopwatchView_Previews: PreviewProvider {
    static var previews: some View {
        NewStopwatchView(isPresented: .constant(true))
            .environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
    }
}
