import UIKit
import Eureka
import AuthenticationServices

class SettingsController: FormViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        form +++ Section()
            <<< LabelRow() { row in
                row.title = NSLocalizedString("Version", comment: "")
                row.value = Bundle.main.fullVersion
            }

        form +++ Section(NSLocalizedString("Profile", comment: ""))
			<<< LabelRow("AutoCatAccount") { row in
				row.title = NSLocalizedString("AutoCat Account", comment: "")
				row.value = Settings.shared.user.email
			}
			<<< LabelRow("GoogleAccount") { row in
				row.title = NSLocalizedString("Google", comment: "")
                if let jwtString = Settings.shared.user.firebaseIdToken, let jwt = JWT<FirebasePayload>(string: jwtString) {
                    row.value = jwt.payload.email
                } else {
                    row.value = NSLocalizedString("Log In", comment: "")
                }
				row.cellUpdate { cell, _ in
					cell.accessoryType = .disclosureIndicator
				}
			}.onCellSelection { cell, row in
				if Settings.shared.user.firebaseIdToken != nil {
                    self.displayLogoutSheet(for: "GoogleAccount")
				} else {
					self.loginToGoogle()
				}
			}
            
        +++ Section(header: NSLocalizedString("Plate number recognition", comment: ""), footer: NSLocalizedString("Recognize plate numbers in alternative form. For example 'ЕВА 123 777' instead of 'Е123ВА 777'", comment: ""))
            <<< SwitchRow("AlternateRecognition") { row in
                row.title = NSLocalizedString("Alternative order", comment: "")
                row.value = Settings.shared.recognizeAlternativeOrder
            }.onChange { row in
                if let val = row.value {
                    Settings.shared.recognizeAlternativeOrder = val
                }
            }
            
        +++ Section(footer: NSLocalizedString("If enabled, app will try to recognize shortened plate numbers (without region) and add default region", comment: ""))
            <<< SwitchRow("ShortenedNumbers") { row in
                row.title = NSLocalizedString("Shortened numbers", comment: "")
                row.value = Settings.shared.recognizeShortenedNumbers
            }.onChange { row in
                if let val = row.value {
                    Settings.shared.recognizeShortenedNumbers = val
                }
            }
            <<< TextRow("") { row in
                row.title = NSLocalizedString("Default region", comment: "")
                row.placeholder = "161"
                row.value = Settings.shared.defaultRegion
                row.hidden = Condition.function(["ShortenedNumbers"], { form in
                    return !((form.rowBy(tag: "ShortenedNumbers") as? SwitchRow)?.value ?? false)
                })
            }.onChange { row in
                if let val = row.value {
                    Settings.shared.defaultRegion = val
                }
            }
            
        +++ Section(footer: NSLocalizedString("When enabled, you will hear short sound before starting audio recording. This will only work when audio record is started via Siri", comment: "")) { $0.tag = "BeepRecordSection" }
            <<< SwitchRow("BeepRecord") { row in
                row.title = NSLocalizedString("Beep before record", comment: "")
                row.value = Settings.shared.recordBeep
            }.onChange{ row in
                if let val = row.value {
                    Settings.shared.recordBeep = val
                }
            }
            
        +++ Section(NSLocalizedString("Debug", comment: ""))
            <<< SwitchRow() { row in
                row.title = NSLocalizedString("Show debug info", comment: "")
                row.value = Settings.shared.showDebugInfo
            }.onChange { row in
                if let val = row.value {
                    Settings.shared.showDebugInfo = val
                }
            }
            
		+++ Section("")
			<<< ButtonRow("SignOut") { $0.title = NSLocalizedString("Sign Out", comment: "") }.onCellSelection { cell, row in
				self.logout()
			}
        
        #if targetEnvironment(macCatalyst)
            if let beepSection = self.form.sectionBy(tag: "BeepRecordSection") {
                beepSection.hidden = true
                beepSection.evaluateHidden()
            }
        #endif
    }
    
    func logout() {
        Settings.shared.user.token = ""
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        self.view.window?.rootViewController = storyboard.instantiateViewController(identifier: "AuthController")
    }
	
    func displayLogoutSheet(for row: String) {
        guard let jwtString = Settings.shared.user.firebaseIdToken, let jwt = JWT<FirebasePayload>(string: jwtString) else { return }
        
        let msg = String.localizedStringWithFormat(NSLocalizedString("You are currently signed in with email %@. It will help to gather more data about vehicles.", comment: ""), jwt.payload.email)
        let sheet = UIAlertController(title: jwt.payload.name, message: msg, preferredStyle: .actionSheet)
		
		let cancel = UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .cancel) { _ in sheet.dismiss(animated: true, completion: nil) }
		let logout = UIAlertAction(title: NSLocalizedString("Sign Out", comment: ""), style: .destructive) { _ in
			Settings.shared.user.firebaseIdToken = nil
			Settings.shared.user.firebaseRefreshToken = nil
			if let row = self.form.rowBy(tag: row) as? LabelRow {
				row.value = NSLocalizedString("Log In", comment: "")
				row.reload()
			}
		}
		
		sheet.addAction(logout)
		sheet.addAction(cancel)
		self.present(sheet, animated: true, completion: nil)
	}
	
	func loginToGoogle() {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
		if let vc = storyboard.instantiateViewController(identifier: "GoogleSignInController") as? GoogleSignInController {
			vc.completion = {
				guard let googleRow = self.form.rowBy(tag: "GoogleAccount") as? LabelRow else { return }
				if let jwtString = Settings.shared.user.firebaseIdToken, let jwt = JWT<FirebasePayload>(string: jwtString) {
					googleRow.value = jwt.payload.email
				} else {
					googleRow.value = NSLocalizedString("Log In", comment: "")
				}
				googleRow.reload()
			}
			self.present(vc, animated: true)
		}
	}
    
    func loginToApple() {
        
    }
}
