//
//  CLLoginMainController.swift

//
//  Created by Leon on 2025/7/17.
//

import RswiftResources
import UIKit

class CLLoginMainController: CLViewController<CLLoginMainView> {
    var viewModel: AccountAuthViewModel = AccountAuthViewModel()
    
    lazy var appleLogin = SignInAppleLogin()

    override class var shouldPresentThisVc: Bool {
        return true
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupViews()
        setupData()
        setupEvent()
    }

    private func setupViews() {
        navigationView.bgView.backgroundColor = .clear
    }

    private func setupData() {
    }

    private func setupEvent() {
        container.button.addTarget(self, action: #selector(tapOperateButton), for: .touchUpInside)
        viewModel.authProcessAction = {[weak self] code, type in
            self?.thirdLogin(code: code, type: type)
        }
    }

    @objc private func tapOperateButton() {
        // Sheet
        let sheet = EGActionSheet()
        sheet.title = "Continue with"

        let icon1 = MWIconFont.image(fromIcon: .socialDiscord, size: .init(width: 24, height: 24), color: .white)
        let action1 = EGActionSheetAction(title: "Discord", iconLeading: icon1, autoDismiss: true) { [weak self] in
            self?.signInWithDiscord()
        }

        let icon2 = MWIconFont.image(fromIcon: .socialGoogle, size: .init(width: 24, height: 24), color: .white)
        let action2 = EGActionSheetAction(title: "Google", iconLeading: icon2, autoDismiss: true) { [weak self] in
            self?.signInWithGoogle()
        }

        let icon3 = MWIconFont.image(fromIcon: .socialApple, size: .init(width: 24, height: 24), color: .white)
        let action3 = EGActionSheetAction(title: "Apple", iconLeading: icon3, autoDismiss: true) { [weak self] in
            self?.signInWithApple()
        }
        sheet.addAction(action1)
        sheet.addAction(action2)
        sheet.addAction(action3)
        sheet.show()
    }

    // MARK: - Functions
    private func thirdLogin(code:String?, type: String?){
        viewModel.thirdLogin(code: code, type: type) {[weak self] state, token in
            if(state){
                self?.loadUserSelfInfo(userToken: token)
            }
        }
    }
    
    private func loadUserSelfInfo(userToken: String){
        UserProvider.request(.userInfoSelfGet, modelType: User.self) {[weak self] result in
            Hud.hideIndicator()
            switch result {
            case let .success(userContent):
                guard let user = userContent else { return }
                UserCore.shared.updateLocalUser(userNew: user)
                NotificationCenter.post(name: .userLoginSuccess)
                NotificationCenter.post(name: .userInfoUpdated)
                if user.cpUserInfo {
                    self?.goPersonalInformationFill(userToken)
                } else {
                    self?.close()
                }
            case .failure:
                break
            }
        }
    }
    
    // MARK: - Actions

    private func signInWithDiscord() {
        let vc = DiscordAuthController()
        vc.viewModel = viewModel
        navigationController?.pushViewController(vc, animated: true)
    }

    private func signInWithGoogle() {
//        testLogin()
        //goPersonalInformationFill("XXXXX")
        #if DEBUG
        testLogin()
        #endif
    }

    private func signInWithApple() {
        appleLogin.loginByApple()
        appleLogin.delegate = self
    }

    private func testLogin() {
        let token = "thirdToken_example"

        Hud.showIndicator()
        let params = ["thirdType": ThirdType.GOOGLE.rawValue, "thirdToken": token]
        LoginProvider.request(LoginAPI.loginByThird(params: params), modelType: ThirdLoginResponse.self) { [weak self] result in
            switch result {
            case let .success(content):
                dlog("mock user: \(String(describing: content)), user's token: \(String(describing: content?.token))")
                guard let userToken = content?.token else { return }
                UserCore.shared.updateToken(tokenNew: userToken)

                UserProvider.request(.userInfoSelfGet, modelType: User.self) { result in
                    Hud.hideIndicator()
                    switch result {
                    case let .success(userContent):
                        guard let user = userContent else { return }
                        UserCore.shared.updateLocalUser(userNew: user)
                        if user.cpUserInfo {
                            self?.goPersonalInformationFill(userToken)
                        } else {
                            self?.close()
                        }
                    case .failure:
                        return
                    }
                }
            case .failure:
                Hud.hideIndicator()
                break
            }
        }
    }

    // MARK: - Helper

    private func goPersonalInformationFill(_ userToken: String) {
        let vc = PersonalInformationFillController()
        vc.userToken = userToken
        navigationController?.pushViewController(vc, animated: true)
    }
}

extension CLLoginMainController: SignInAppleLoginDelegate{
    func signInAppleAuth(token: String, userId: String, name: String) {
        thirdLogin(code: token, type: "APPLE")
    }
}

