//
//  KMCloseVerificationWC.swift
//  PDF Reader Pro
//
//  Created by wanjun on 2024/11/5.
//  手动撤销验证码WindowController
//

import Cocoa
import Combine

class KMCloseVerificationWC: NSWindowController {
    
    @IBOutlet weak var titleLabel: NSTextField!
    @IBOutlet weak var subTitleLabel1: NSTextField!
    @IBOutlet weak var subTitleLabel2: NSTextField!
    @IBOutlet weak var verifficationBox: NSBox!
    @IBOutlet weak var verifficationBox2: NSBox!
    @IBOutlet weak var verifficationTextField: NSTextField!
    @IBOutlet weak var sendBox: KMBox!
    @IBOutlet weak var sendLabel: NSTextField!
    @IBOutlet weak var verifficationErrorLabel: NSTextField!
    @IBOutlet weak var nextButton: NSButton!

    private var userInfoModel = KMUserInfoVCModel()
    private var signUpModel = KMSignUpViewModel()
    private var cancellables = Set<AnyCancellable>()

    static let shared: KMCloseVerificationWC = {
        let windowC = KMCloseVerificationWC(windowNibName: "KMCloseVerificationWC")
        return windowC
    }()

    override func windowDidLoad() {
        super.windowDidLoad()

        // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
          
        bindViewModel()
        languageLocalized()
        initializeUI()
        signUpModel.email = KMMemberInfo.shared.userEmail
        
        signUpModel.countDown(type: .logout, callback: nil)
        
        nextButton.isEnabled = false
        
        window?.delegate = self
        
        NotificationCenter.default.addObserver(self, selector: #selector(changeEffectiveAppearance), name: NSNotification.Name(rawValue: "kEffectiveAppearance"), object: nil)
    }
    
    @objc func changeEffectiveAppearance() {
        self.initializeUI()
    }
    
    
    // MARK: Private Method
    
    private func languageLocalized() -> Void {
        self.window?.title = NSLocalizedString("Remove Account", tableName: "MemberCenterLocalizable", comment: "")

        titleLabel.stringValue = NSLocalizedString("Verify your identity", tableName: "MemberCenterLocalizable", comment: "")
        subTitleLabel1.stringValue = NSLocalizedString("We have sent you a code via email to", tableName: "MemberCenterLocalizable", comment: "")
        subTitleLabel2.stringValue = KMMemberInfo.shared.userEmail
        nextButton.title = NSLocalizedString("Next", tableName: "MemberCenterLocalizable", comment: "")
        verifficationErrorLabel.stringValue = String(format: "%@", NSLocalizedString("Verification code error.", tableName: "MemberCenterLocalizable", comment: ""))
        verifficationTextField.placeholderString = NSLocalizedString("Please enter code", tableName: "MemberCenterLocalizable", comment: "")
    }
    
    private func initializeUI() -> Void {
        self.window?.contentView?.wantsLayer = true
        let isDarkModel = KMAdvertisementConfig.isDarkModel()
        if  isDarkModel {
            self.window?.contentView?.layer?.backgroundColor = NSColor(hex: "0E1114").cgColor;
        } else {
            self.window?.contentView?.layer?.backgroundColor = NSColor(hex: "FFFFFF").cgColor;
        }

        verifficationBox.fillColor = NSColor(named: "texefiedfillcolor") ?? NSColor.white

        verifficationErrorLabel.isHidden = !signUpModel.passwordError()

        titleLabel.textColor = NSColor(named: "000000_0.85")
        titleLabel.font = NSFont.SFProTextSemiboldFont(13)
        subTitleLabel1.textColor = NSColor(named: "000000_0.85")
        subTitleLabel1.font = NSFont.SFProTextRegularFont(12)
        subTitleLabel2.textColor = NSColor(named: "000000_0.85")
        subTitleLabel2.font = NSFont.SFProTextRegularFont(12)
        nextButton.setTitleColor(color: NSColor(named: "FFFFFF") ?? NSColor.white, font: NSFont.SFProTextRegularFont(13))
        verifficationTextField.delegate = self
        verifficationBox2.borderColor = NSColor(named: "DADBDE") ?? NSColor.gray
        verifficationBox.borderColor = NSColor(named: "FA1E5D") ?? NSColor.gray
        sendBox.fillColor = NSColor(named: "273C62") ?? NSColor.blue
        sendBox.borderColor = NSColor(named: "273C62") ?? NSColor.blue
        sendLabel.textColor = NSColor(named: "FFFFFF") ?? NSColor.white
        sendLabel.font = NSFont.SFProTextRegularFont(13)
        verifficationErrorLabel.textColor = NSColor(named: "FA1E5D")
        verifficationErrorLabel.font = NSFont.SFProTextRegularFont(9)
        
        textfieldInputState()
        sendBoxRefresh()
        
        sendBox.moveCallback =  { [weak self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
            guard let self = self else { return }
            if self.signUpModel.sendBoxSelect { return }
            if mouseEntered {
                self.sendBox.fillColor = NSColor(named: "000000_0.1") ?? NSColor.blue
            } else {
                self.sendBox.fillColor = NSColor(named: "273C62") ?? NSColor.blue
            }
        }
        sendBox.downCallback = { [weak self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
            guard let self = self else { return }
            if self.signUpModel.email.count <= 0 { return }
            if self.signUpModel.sendBoxSelect { return }
            if downEntered {
                self.sendBox.fillColor = NSColor(named: "273C62_0.4") ?? NSColor.blue
                self.signUpModel.countDown(type: .logout, callback: nil)
            }
        }

    }
    
    private func textfieldInputState() -> Void {
        if signUpModel.passwordError() {
            if signUpModel.signUpState == .verificationCode {
                verifficationBox2.borderWidth = 0
                verifficationBox.borderWidth = 1
            }
        } else {
            if signUpModel.signUpState == .verificationCode {
                verifficationBox2.borderWidth = 1
                verifficationBox.borderWidth = 0
            }
        }
        verifficationErrorLabel.isHidden = !signUpModel.passwordError()
    }
    
    private func sendBoxRefresh() -> Void {
        sendLabel.stringValue = signUpModel.sendContent
        if signUpModel.sendContent == NSLocalizedString("Send", tableName: "MemberCenterLocalizable", comment: "") {
            sendBox.fillColor = NSColor(named: "273C62") ?? NSColor.blue
        } else {
            if signUpModel.sendContent == NSLocalizedString("Resend", tableName: "MemberCenterLocalizable", comment: "") {
                sendBox.fillColor = NSColor(named: "273C62") ?? NSColor.blue
            } else {
                sendBox.fillColor = NSColor(named: "DADBDE") ?? NSColor.gray
                sendLabel.stringValue = String(format: "%@s", signUpModel.sendContent)
            }
        }
    }

    // MARK: Bind Method
    
    func bindViewModel() -> Void {
        signUpModel.$passwordErrorMessage
            .receive(on: RunLoop.main)
            .sink { [weak self] newValue in
                self?.verifficationErrorLabel.stringValue = newValue
                self?.verifficationErrorLabel.isHidden = false
                self?.verifficationBox.borderColor = NSColor(named: "FA1E5D") ?? NSColor.red
            }
            .store(in: &cancellables)
        signUpModel.$sendContent
            .receive(on: RunLoop.main)
            .sink { [weak self] newValue in
                self?.sendBoxRefresh()
            }
            .store(in: &cancellables)
    }
    
    // MARK: Button Action
    
    @IBAction func yesButtonAction(_ sender: NSButton) {
        window?.showWaitingView()
        userInfoModel.closeAccountApplyWC(code: signUpModel.verificationCode) { [weak self] result, resultDict in
            DispatchQueue.main.async {
                if(result == true) {
                    KMCloseApplyWC.shared.showWindow(nil)
                    self?.window?.close()
                } else {
                    KMMemberCenterManager.showAlert(code: .init(rawValue: resultDict?.code ?? 0), message: resultDict?.msg, callback: nil)
                }
                self?.window?.hideWaitingView()
            }
        }
    }
}

extension KMCloseVerificationWC: NSTextFieldDelegate {
    func controlTextDidEndEditing(_ obj: Notification) {
        let textField = obj.object as? NSTextField
        if textField == verifficationTextField {
            signUpModel.verificationCode = textField!.stringValue
        }
    }
    
    func controlTextDidChange(_ obj: Notification) {
        let textField = obj.object as? NSTextField
        if textField == verifficationTextField {
            signUpModel.verificationCode = textField!.stringValue
            
            signUpModel.passwordErrorMessage = ""
            verifficationBox.borderColor = NSColor(named: "DADBDE") ?? NSColor.gray
            if(textField?.stringValue.isEmpty == true) {
                nextButton.isEnabled = false
            } else {
                nextButton.isEnabled = true
            }

        }
    }
}

extension KMCloseVerificationWC: NSWindowDelegate {
    func windowWillClose(_ notification: Notification) {
        if let data = self.window?.isEqual(to: notification.object), data {
            verifficationTextField.stringValue = ""
        }
    }
}