//
//  KMMemberCenterWindowController.swift
//  PDF Reader Pro
//
//  Created by 王帅 on 2024/11/12.
//

import Cocoa

class KMMemberCenterWindowController: NSWindowController {
    
    @IBOutlet weak var productBox: NSBox!
    @IBOutlet weak var productView: NSView!
    @IBOutlet weak var productLabel: NSTextField!
    @IBOutlet weak var typeLabel: NSTextField!

    @IBOutlet weak var device1View: NSView!
    @IBOutlet weak var device1Label: NSTextField!
    @IBOutlet weak var device1Button: NSButton!
    
    @IBOutlet weak var device2View: NSView!
    @IBOutlet weak var device2Label: NSTextField!
    @IBOutlet weak var device2Button: NSButton!

    @IBOutlet weak var device3View: NSView!
    @IBOutlet weak var device3Label: NSTextField!
    @IBOutlet weak var device3Button: NSButton!
    
    @IBOutlet weak var device4View: NSView!
    @IBOutlet weak var device4Label: NSTextField!
    @IBOutlet weak var device4Button: NSButton!
    
    @IBOutlet var bottomoffset:NSLayoutConstraint!
    
    @IBOutlet weak var tipLabel: NSTextField!

    @IBOutlet weak var cancelButton: NSButton!
    @IBOutlet weak var loginButton: NSButton!
    
    var signUpViewModel:KMSignUpViewModel?
    
    static let shared: KMMemberCenterWindowController = {
        let windowC = KMMemberCenterWindowController(windowNibName: "KMMemberCenterWindowController")
        return windowC
    }()
    
    public var memberCenterdeviceResult: KMMemberCenterResult = KMMemberCenterResult(loginResult: KMMemberLoginResult(refreshToken: "", accessToken: "", tokenType: "", expiresIn: "")) {
        didSet {
            refreshData()
        }
    }

    override func windowDidLoad() {
        super.windowDidLoad()
        
        self.window?.title = NSLocalizedString("Device Management", tableName: "MemberCenterLocalizable", comment: "")
        productLabel.stringValue = NSLocalizedString("Device name", tableName: "MemberCenterLocalizable", comment: "")
        typeLabel.stringValue = NSLocalizedString("Action", tableName: "MemberCenterLocalizable", comment: "")

        device1Button.title = NSLocalizedString("Unbind", tableName: "MemberCenterLocalizable", comment: "")
        device2Button.title = NSLocalizedString("Unbind", tableName: "MemberCenterLocalizable", comment: "")
        device3Button.title = NSLocalizedString("Unbind", tableName: "MemberCenterLocalizable", comment: "")
        device4Button.title = NSLocalizedString("Unbind", tableName: "MemberCenterLocalizable", comment: "")
        
        cancelButton.title = NSLocalizedString("Do not log in to the current device", tableName: "MemberCenterLocalizable", comment: "")
        loginButton.title = NSLocalizedString("Log in to the current device", tableName: "MemberCenterLocalizable", comment: "")

        productView.wantsLayer = true
        device1View.wantsLayer = true
        device2View.wantsLayer = true
        device3View.wantsLayer = true
        device4View.wantsLayer = true

        initializeUI()
        
        NotificationCenter.default.addObserver(self, selector: #selector(changeEffectiveAppearance), name: NSNotification.Name(rawValue: "kEffectiveAppearance"), object: nil)
    }
    
    @objc func changeEffectiveAppearance() {
            self.initializeUI()
    }
    
    private func initializeUI() -> Void {
        self.window?.contentView?.wantsLayer = true
        let isDarkModel = KMAdvertisementConfig.isDarkModel()
        var proColor = NSColor(hex: "323232")
        var prosubColor = NSColor(hex: "272727")

        if  isDarkModel {
            self.window?.contentView?.layer?.backgroundColor = NSColor(hex: "282828").cgColor
            proColor = NSColor(hex: "323232")
            prosubColor = NSColor(hex: "272727")
        } else {
            self.window?.contentView?.layer?.backgroundColor = NSColor(hex: "f6f6f6").cgColor;
            proColor = NSColor(hex: "E4E4E4")
            prosubColor = NSColor(hex: "F0F0F0")
        }
        
        productView.layer?.backgroundColor = proColor.cgColor
        device1View.layer?.backgroundColor = prosubColor.cgColor
        device2View.layer?.backgroundColor = prosubColor.cgColor
        device3View.layer?.backgroundColor = prosubColor.cgColor
        device4View.layer?.backgroundColor = prosubColor.cgColor

        productBox.borderColor = NSColor(named: "DADBDE") ?? .gray

        productLabel.textColor = NSColor(named: "42464D")
        typeLabel.textColor = NSColor(named: "42464D")
        device1Label.textColor = NSColor(named: "42464D")
        device2Label.textColor = NSColor(named: "42464D")
        device3Label.textColor = NSColor(named: "42464D")
        device4Label.textColor = NSColor(named: "42464D")
        tipLabel.textColor = NSColor(named: "4982E6")

        cancelButton.setTitleColor(color: NSColor(named: "000000") ?? NSColor.white, font: NSFont.SFProTextRegularFont(13))

        device1Button.setTitleColor(color: NSColor(named: "4982E6") ?? NSColor.blue, font: NSFont.SFProTextRegularFont(13))
        device2Button.setTitleColor(color: NSColor(named: "4982E6") ?? NSColor.blue, font: NSFont.SFProTextRegularFont(13))
        device3Button.setTitleColor(color: NSColor(named: "4982E6") ?? NSColor.blue, font: NSFont.SFProTextRegularFont(13))
        device4Button.setTitleColor(color: NSColor(named: "4982E6") ?? NSColor.blue, font: NSFont.SFProTextRegularFont(13))
    }
    
    private func refreshData() {
        let deviceList_Result:[KMMemberDeviceList] = memberCenterdeviceResult.deviceList_Result ?? []
        bottomoffset.constant = CGFloat(Int(deviceList_Result.count) * 32)
        
        if(deviceList_Result.count == 4) {
            
        } else if (deviceList_Result.count == 3) {
            device4View.isHidden = true
            device3View.isHidden = false
            device2View.isHidden = false
            device1View.isHidden = false
        } else if (deviceList_Result.count == 2) {
            device4View.isHidden = true
            device3View.isHidden = true
            device2View.isHidden = false
            device1View.isHidden = false
        } else if (deviceList_Result.count == 1) {
            device4View.isHidden = true
            device3View.isHidden = true
            device2View.isHidden = true
            device1View.isHidden = false
        } else if (deviceList_Result.count == 0) {
            device4View.isHidden = true
            device3View.isHidden = true
            device2View.isHidden = true
            device1View.isHidden = true
        }
        
        for i in 0 ..< deviceList_Result.count {
            let device = deviceList_Result[i]
            let name = String(format: "%@%@(%@)","PDF Reader Pro for ",device.device_model ?? "PDF Reader Pro User",device.deviceName ?? " Device Name")
            if i == 0 {
                device1Label.stringValue = name
            } else if i == 1 {
                device2Label.stringValue = name
            }  else if i == 2 {
                device3Label.stringValue = name
            } else if i == 3 {
                device4Label.stringValue = name
            }
        }
        let maxDeviceNum = memberCenterdeviceResult.maxDeviceNum ?? 1
        if (maxDeviceNum <= 1) {
            tipLabel.stringValue = String(format: NSLocalizedString("Can keep %d device online at the same time", tableName: "MemberCenterLocalizable", comment: ""), maxDeviceNum)
        } else {
            tipLabel.stringValue = String(format: NSLocalizedString("Can keep %d devices online at the same time", tableName: "MemberCenterLocalizable", comment: ""), maxDeviceNum)
        }
        
        if deviceList_Result.count == maxDeviceNum {
            loginButton.isEnabled = false
        } else {
            loginButton.isEnabled = true
        }
    }
    
    // MARK: Button Actions
    @IBAction func buttonItemClicked_UntieDevice(_ sender: NSButton) {
        let tag = sender.tag
        var deviceList_Result:[KMMemberDeviceList] = memberCenterdeviceResult.deviceList_Result ?? []
        if(deviceList_Result.count > tag) {
            let device = deviceList_Result[tag]
            if(device.id?.isEmpty == true) {
                return
            }
            
            if KMMemberCenterManager.manager.isConnectionAvailable() == false {
                let alert = NSAlert()
                alert.alertStyle = .critical
                alert.messageText = NSLocalizedString("Error Information", comment: "")
                alert.informativeText = NSLocalizedString("Please make sure your internet connection is available.", comment: "")
                alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
                alert.runModal()
                return
            }
            
            showWaitingView(to: window?.contentView ?? NSView())
            KMMemberCenterManager.manager.logoutDevice(deviceId: device.id!, complete: {[weak self] success, result in
                self?.hideWaitingView(from: self?.window?.contentView ?? NSView())
                
                guard let result = result else { return }
                let resultDict = result as KMMemberCenterResult
                let msg = resultDict.msg
                if success {
                    deviceList_Result.remove(at: Int(tag))
                    self?.memberCenterdeviceResult.deviceList_Result = deviceList_Result
                    self?.refreshData()
                } else {
                    KMMemberCenterManager.showAlert(code: .init(rawValue: result.code), message: result.msg, callback: nil)
                }
            })
        }
    }
    
    @IBAction func buttonItemClicked_Cancel(_ sender: NSButton) {
        window?.close()
    }
    
    @IBAction func buttonItemClicked_Login(_ sender: NSButton) {
        window?.showWaitingView()
        signUpViewModel?.signUpAction { [weak self] result, _ in
            self?.window?.hideWaitingView()
            self?.window?.close()
        }
    }
    
}