//
//  ViewController.swift
//  BreastFeedingDemo
//
//  Created by Jay Zhang on 2022/6/2.
//

import AVFoundation
import Flutter
import UIKit

class ViewController: UIViewController {
    @IBOutlet var titleL: UILabel!
    @IBOutlet var stepL1: UILabel!
    @IBOutlet var stepL2: UILabel!
    @IBOutlet var stepL3: UILabel!
    @IBOutlet var startBtn: UIButton!
    @IBOutlet var panelV: UIStackView!
    @IBOutlet var popupView: UIView!
    @IBOutlet var switchBtn: UIButton!
    @IBOutlet var permisionPopupV: UIView!
    @IBOutlet var permissionTitle: UILabel!
    @IBOutlet var permissionText: UILabel!
    @IBOutlet var permissionOKBtn: UIButton!
    @IBOutlet var permissionPanel: UIView!
    var methodChannel: FlutterMethodChannel?
    lazy var vm: ViewModel = .init()
    var isFirstLoad: Bool = true

    fileprivate func updateUI() {
        titleL.text = vm.landingPageTitle
        stepL1.text = vm.landingPageStep1
        stepL2.text = vm.landingPageStep2
        stepL3.text = vm.landingPageStep3

        permissionText.text = vm.cameraText1
        permissionTitle.text = vm.cameraText
        permissionOKBtn.setTitle(vm.cameraButtonText, for: .normal)
        startBtn.setTitle(vm.landingPageStart, for: .normal)
        panelV.layer.cornerRadius = 8
        permissionPanel.layer.cornerRadius = 8
        permissionPanel.clipsToBounds = true
        panelV.clipsToBounds = true
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        overrideUserInterfaceStyle = .light
        UIApplication.shared.isIdleTimerDisabled = true
        navigationController?.setNavigationBarHidden(true, animated: false)
        updateUI()
        popupView.isHidden = true

        if let flutterEngine = (UIApplication.shared.delegate as? AppDelegate)?.flutterEngine {
            methodChannel = FlutterMethodChannel(name: "com.wmdigit.breastcoachai.native",
                                                 binaryMessenger: flutterEngine.binaryMessenger)
            methodChannel?.setMethodCallHandler { [weak self]
                (call: FlutterMethodCall, result: @escaping FlutterResult) in
                    if let strongSelf = self {
                        switch call.method {
                        case "init":
                            result(strongSelf.vm.flutterArguments)
                        case "teachingEnd":
                            strongSelf.methodChannel?.invokeMethod("dispose", arguments: nil)
                            // ["totalDuration": 3, "reasonText": Concern about my personal privacy, "status": incomplete, "incompleteReasonCode": 2]
                            let argument: [String: Any] = try! JSONSerialization.jsonObject(with: (call.arguments as! String).data(using: .utf8)!) as! [String: Any]
//                            let totalDuration: Int = argument["totalDuration"] as! Int
//                            let reasonText: String = argument["reasonText"] as! String
//                            let incompleteReasonCode: Int = argument["incompleteReasonCode"] as! Int
                            let status: String = argument["status"] as! String
                            if status == "incomplete" {
//                                strongSelf.showError(reasonText)
                            } else if status == "complete" {
                                strongSelf.toCompleteVC()
                                return
                            }
                            strongSelf.navigationController?.popViewController(animated: true)
                        default:
                            // Unrecognized method name
                            print("Unrecognized method name: \(call.method)")
                        }
                    }
            }
        }
    }

    func checkCameraPermission() -> Bool? {
        let cameraAuthorizationStatus = AVCaptureDevice.authorizationStatus(for: .video)

        switch cameraAuthorizationStatus {
        case .notDetermined:
            return nil
        case .authorized:
            return true
        default:
            permisionPopupV.isHidden = false
            return false
        }
    }

    func showError(_ text: String?) {
        let alertVC = UIAlertController(title: text, message: nil, preferredStyle: .alert)
        alertVC.addAction(UIAlertAction(title: "OK", style: .cancel))
        navigationController?.pushViewController(alertVC, animated: true)
    }

    func toCompleteVC() {
        let sb = UIStoryboard(name: "Main", bundle: nil)
        let vc = sb.instantiateViewController(withIdentifier: "CompleteVC") as! CompleteVC
        vc.vm = vm
        navigationController?.pushViewController(vc, animated: true)
    }

    @IBAction func toSetting(_: Any) {
        if let appSettingsURL = URL(string: UIApplication.openSettingsURLString) {
            UIApplication.shared.open(appSettingsURL)
        }
    }

    @IBAction func tapStart(_: Any) {
        if checkCameraPermission() == false {
            return
        }

        if !isFirstLoad {
            methodChannel?.invokeMethod("reload", arguments: nil)
        }
        isFirstLoad = false
        if let flutterEngine = (UIApplication.shared.delegate as? AppDelegate)?.flutterEngine {
            let scanVC = FlutterViewController(engine: flutterEngine, nibName: nil, bundle: nil)
            scanVC.modalPresentationStyle = .overFullScreen
            navigationController?.pushViewController(scanVC, animated: true)
        }
    }

    /// 选择语言
    @IBAction func showPanel(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
        popupView.isHidden = !sender.isSelected
        //
        (panelV.viewWithTag(1000) as! UIButton).isSelected = false
        (panelV.viewWithTag(1001) as! UIButton).isSelected = false
        (panelV.viewWithTag(1002) as! UIButton).isSelected = false

        switch vm.language {
        case .english:
            (panelV.viewWithTag(1000) as! UIButton).isSelected = true
        case .français:
            (panelV.viewWithTag(1001) as! UIButton).isSelected = true
        case .español:
            (panelV.viewWithTag(1002) as! UIButton).isSelected = true
        }
    }

    @IBAction func dismissPermissimPanel(_: Any) {
        permisionPopupV.isHidden = true
    }

    @IBAction func selectLanguage(_ sender: UIButton) {
        switch sender.tag {
        case 1000:
            vm.language = .english
        case 1001:
            vm.language = .français
        case 1002:
            vm.language = .español
        default:
            break
        }

        switchBtn.isSelected = false
        popupView.isHidden = true

        updateUI()
    }
}