//
//  SecretSetViewController.swift
//  PhoneManager
//
//  Created by edy on 2025/3/31.
//

import UIKit
import LocalAuthentication

class SecretSetViewController: BaseViewController, UITextFieldDelegate {

    enum SecretType {
    case create  // 新建
    case verify  // 验证
    case del     // 删除
    case change  // 修改
    }
    
    var Callback:((_ suc:Bool)->Void) = { suc in }
    
    var secretType:SecretType = .create {
        didSet{
            if secretType == .create {
                setTitle.text =  "Create New PIN"
            }else{
                setTitle.text =  "Please Enter PIN"
            }
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.titleView.backBtn.setImage(UIImage(named: "ic_close_charging"), for: .normal)
        self.titleView.model.isBackBtnShow = true
        titleView.model.title = "Secret Library"
        titleView.titleLabel.textColor = .black
        titleView.titleLabel.textAlignment = .left
        setUI()
        collect.register(SecretSetPsCell.self, forCellWithReuseIdentifier: SecretSetPsCellID)
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
            if self.secretType != .verify || (SettingConfiguration.share.config.faceId ?? false ) == false {
                self.ps.becomeFirstResponder()
            }else{
                self.faceID()
            }
        }
    }
    
    func faceID() -> Void {
        if PMFaceIDManger.request() {
            PMFaceIDManger.authenticateWithFaceID(reason: "Unlock privacy space") {[weak self] success, error in
                if success {
                    self?.Callback(true)
                }else{
                    if let laError = error as? LAError {
                        let content = LAContext()
                        if laError.code == .biometryLockout ||
                            laError.code == .biometryNotEnrolled ||
                            laError.code == .biometryNotAvailable {
                            content.handleLAError(error ?? NSError())
                        }else{
                            self?.ps.becomeFirstResponder()
                        }
                    }else{
                        self?.ps.becomeFirstResponder()
                    }
                }
            }
        }
    }
    
    
    private func PMClose() -> Void {
        if self.navigationController?.children.count ?? 0 <= 0 {
            self.dismiss(animated: true)
        }else{
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    override func close(animation: Bool = true) {
        if secretType == .verify {
            self.PMClose()
            return
        }
        Callback(false)
        super.close(animation: animation)
    }
    
    private var createViesget = ""
    
    private var Secret = "" {
        didSet {
            collect.reloadData()
            if Secret.count == 4 {
                if secretType == .verify || secretType == .del || secretType == .change {
                    let Ps:String = SettingConfiguration.share.config.secret ?? ""
                    //UserDefaults.standard.object(forKey: SecretViewController.psKey) as? String ?? ""
                    if Ps != Secret {
                        Secret = ""
                        self.ps.text = ""
                        if secretType == .verify && (SettingConfiguration.share.config.faceId ?? false) {
                            self.contentView.isHidden = false
                            self.ps.resignFirstResponder()
                        }
                        descpLabel.text = "The entered PIN code is incorrect, please re-enter"
                        return
                    }else{
                        if secretType == .del {
//                            UserDefaults.standard.set("", forKey: SecretViewController.psKey)
                            SettingConfiguration.share.config.secret = ""
                            SettingConfiguration.share.config.faceId = false
                            let alert = UIAlertController(title: nil, message: "The PIN has been deleted", preferredStyle: .alert)
                            self.present(alert, animated: true)
                            DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                                alert.dismiss(animated: true) {
                                    self.Callback(true)
                                    self.PMClose()
                                }
                            }
                        }else if secretType == .change {
                            Secret = ""
                            self.ps.text = ""
                            self.secretType = .create
                            return
                        }
                    }
                }else{
                    if createViesget.count > 2 {
                        if createViesget != Secret {
                            descpLabel.text = "The PIN entered twice is different, please re-enter"
                            Secret = ""
                            self.ps.text = ""
                        }else{
//                            UserDefaults.standard.set(Secret, forKey: SecretViewController.psKey)
                            SettingConfiguration.share.config.secret = Secret
                            UserDefaults.standard.set("1", forKey: "SecretFirstShow")
                            let alert = UIAlertController(title: nil, message: "Your space is locked", preferredStyle: .alert)
                            self.present(alert, animated: true)
                            DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                                alert.dismiss(animated: true) {
                                    self.Callback(true)
                                    self.PMClose()
                                    _ = PMFaceIDManger.request()
                                }
                            }
                        }
                    }else{
                        createViesget = Secret
                        Secret = ""
                        self.ps.text = ""
                        setTitle.text =  "Confirm PIN code"
                    }
                    return
                }
                let alert = UIAlertController(title: nil, message: "Unlocked", preferredStyle: .alert)
                self.present(alert, animated: true)
                DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                    alert.dismiss(animated: true){
                        self.Callback(true)
                        self.PMClose()
                    }
                }
               
            }
        }
    }
    
    private func setUI() -> Void {
        view.addSubview(setInfo)
        view.addSubview(setTitle)
        view.addSubview(collect)
        view.addSubview(descpLabel)
        setInfo.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(titleView.snp.bottom).offset(62)
        }
        setTitle.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(setInfo.snp.bottom).offset(16)
        }
        descpLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(setTitle.snp.bottom).offset(5)
        }
        collect.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.width.equalTo(20*4.0 + 3 * 20.0 )
            make.top.equalTo(setTitle.snp.bottom).offset(32);
            make.height.equalTo(20)
        }
        contentView.isHidden = true
    }
    
    private lazy var collect: UICollectionView = {
        let flowLayout = UICollectionViewFlowLayout()
        let col = UICollectionView(frame: CGRectZero, collectionViewLayout: flowLayout)
        col.delegate = self;
        col.dataSource = self;
        return col
    }()
    
    private lazy var ps: UITextField = {
        let tf = UITextField()
        tf.alpha = 0
        tf.delegate = self;
        tf.keyboardType = .numberPad
        view.addSubview(tf)
        return tf
    }()
    
    private lazy var setInfo:UIImageView = {
        let info = UIImageView(image: UIImage(named: "img_secret_pop"))
        info.contentMode = .scaleToFill
        return info
    }()

    private lazy var setTitle: UILabel = {
        let st = UILabel()
        st.text = "Create New PIN"
        st.font = UIFont.boldSystemFont(ofSize: 20)
        st.textColor = .black
        st.textAlignment = .center
        return st
    }()
    
    private lazy var descpLabel: UILabel = {
        let st = UILabel()
        st.text = ""
        st.font = UIFont.systemFont(ofSize: 14)
        st.textColor = .red
        st.textAlignment = .center
        return st
    }()
    
    private lazy var contentView: SecretAlertFaceID = {
        let vc =  SecretAlertFaceID.xib()
        view.addSubview(vc)
        vc.center = CGPointMake(view.width/2.0, view.height/2.0 + 30)
        vc.callback = {[weak self] in
            self?.faceID()
        }
        return vc
    }()

}
 
extension SecretSetViewController:UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 4
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell:SecretSetPsCell = collectionView.dequeueReusableCell(withReuseIdentifier: SecretSetPsCellID, for: indexPath) as! SecretSetPsCell
        cell.isSelect = Secret.count > indexPath.row;
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 20
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSizeMake(20, 20)
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        var st:NSString = textField.text as? NSString ?? ""
        st = st.replacingCharacters(in: range, with: string) as NSString
        if st.length >= 4 {
            Secret = st.substring(to: 4)
            textField.text = ""
            return false
        }
        Secret = st as String;
        return true
    }
    
}
