//
//  DiscordAuthController.swift

//
//  Created by Leon on 2025/8/4.
//

import UIKit
import WebKit

class DiscordAuthController: H5BaseViewController {
    // MARK: - Properties

    weak var viewModel: AccountAuthViewModel?

    // MARK: - Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationView.title = "Sign In"
        
        requestDiscordOAuth()
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        UIWindow.applicationKey?.hideAllToasts()
    }

    // MARK: - Public Methods

    func requestDiscordOAuth() {
        let clientId = AppConst.discordOAuthAppId
        let redirectUri = AppConst.discordCallbackUrl
        //let urlString = "https://discord.com/api/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectUri)/link/auth&response_type=code&scope=identify"
        // Test use. // use %20email
        let urlString = "https://discord.com/api/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectUri)/api/auth/discord/callback&response_type=code&scope=identify%20email"
        
        targetUrl = URL(string: urlString)
    }
    
    // MARK: - Override
    
    override func tapNaviBackBtn(){
        close()
    }

    // MARK: - WKNavigationDelegate

    override func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        guard let urlString = navigationAction.request.url?.absoluteString.removingPercentEncoding else {
            decisionHandler(.allow)
            return
        }

        dlog("Discord urlString: \(urlString)")
        
        if urlString.contains("link/auth?code=") {
            // Handle OAuth code
            let components = urlString.components(separatedBy: "link/auth?code=")
            if components.count == 2, let code = components.last {
                codeToToken(code)
                decisionHandler(.cancel)
                return
            }
        } else if urlString.contains("callback?code=") {
            let components = urlString.components(separatedBy: "callback?code=")
            if components.count == 2, let code = components.last {
                codeToToken(code)
                decisionHandler(.cancel)
                return
            }
        }
        else if urlString.contains("?error=access_denied") {
            // Handle cancellation
            decisionHandler(.cancel)
            navigationController?.popViewController(animated: true)
            return
        }

        // Allow other navigations
        decisionHandler(.allow)
    }

    // MARK: - Private Methods

    private func codeToToken(_ code: String) {
        guard !code.isEmpty else { return }

        if let authProcessAction = viewModel?.authProcessAction {
            UIWindow.applicationKey?.hideAllToasts()
            authProcessAction(code, "DISCORD")
            navigationController?.popViewController(animated: true)
        }
    }

    func leaveAndPostNoti() {
        UIWindow.applicationKey?.hideAllToasts()

        NotificationCenter.post(name: .userLoginSuccess)
        NotificationCenter.post(name: .userInfoUpdated)

        dismiss(animated: true, completion: nil)
    }
}
