//
//  TinkInsightDelegate.swift
//  react-native-tink-sdk
//
//  Created by id856574 on 30/05/2024.
//
import TinkMoneyManagerUI
import TinkLink

class InsightDelegate: ActionableInsightsViewControllerDelegate {
    
    var clientId: String?
    var clientAccessToken: String?
    var userId: String?
    var idHint: String?
    var redirectUri: String?
    
    init(clientId: String?, clientAccessToken: String?, userId: String?, idHint: String?, redirectUri: String?) {
        self.clientId = clientId
        self.clientAccessToken = clientAccessToken
        self.userId = userId
        self.idHint = idHint
        self.redirectUri = redirectUri
    }
    
    public func actionableInsightsViewController(_ viewController: TinkMoneyManagerUI.ActionableInsightsViewController, showLeftToSpendForMonth month: TinkMoneyManagerUI.Month) {
    }
    
    public func actionableInsightsViewController(_ viewController: TinkMoneyManagerUI.ActionableInsightsViewController, initiateTransferFromAccount sourceIdentity: TinkMoneyManagerUI.TransferIdentity?, to destinationIdentity: TinkMoneyManagerUI.TransferIdentity?, amount: Double?, currencyCode: String?, completionHandler: @escaping (Result<Void, any Error>) -> Void) {
    }
    
    func actionableInsightsViewController(_ viewController: ActionableInsightsViewController, refreshCredentialsWithID credentialsID: TinkMoneyManagerUI.Credentials.ID, completionHandler: @escaping (Result<Void, any Error>) -> Void) {
        
        guard let clientAccessToken = self.clientAccessToken, let userId = self.userId, let idHint = self.idHint, let clientId = self.clientId, let redirectUri = self.redirectUri else {
            print("Error Tink: one of accessToken, userId, clientId, redirectUri or idHint is not defined")
            return
        }
        
        postAuthorizationGrant(clientAccessToken: clientAccessToken, userId: userId, idHint: idHint) { result in
            switch(result) {
            case .success(let apiResponse):
                DispatchQueue.main.async {
                    let configuration = Configuration(clientID: clientId, redirectURI: redirectUri, baseDomain: .eu)
                    
                    let viewController = Tink.Transactions.updateConsent(
                        configuration: configuration,
                        authorizationCode: AuthorizationCode(apiResponse.code),
                        credentialsID: Credentials.ID(credentialsID.value)) { res in
                            switch res {
                            case .success(let credentialsID):
                                DispatchQueue.main.asyncAfter(deadline: .now()+3, execute: {
                                    UIApplication.shared.windows.first?.rootViewController?.dismiss(animated: true)
                                })
                            case .failure(let error):
                                DispatchQueue.main.asyncAfter(deadline: .now(), execute: {
                                    UIApplication.shared.windows.first?.rootViewController?.dismiss(animated: true)
                                })
                            }
                        }
                    
                    UIApplication.shared.windows.first?.rootViewController?.present(viewController, animated: true)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
}
