// react-native-tink-sdk
// TinkComponent
// Created by: Imran MENTESE on 03/01/2024
// Copyright (c) 2023

import TinkLink
import TinkMoneyManagerUI

public class TinkComponent: UIView {

    var clientId: String?
    var clientAccessToken: String?
    var userAccessToken: String?
    var userId: String?
    var idHint: String?
    var redirectUri: String?
    var insightDelegate: InsightDelegate?
    
    init(clientId: String?, clientAccessToken: String?, userId: String?, idHint: String?, redirectUri: String?) {
        self.insightDelegate = InsightDelegate(clientId: clientId, clientAccessToken: clientAccessToken, userId: userId, idHint: idHint, redirectUri: redirectUri)
        super.init(frame: .zero)
    }

    // MARK: Constructors
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    internal func initSubview(frame: CGRect) {
        self.frame = frame

        guard let clientAccessToken = self.clientAccessToken, let clientId = self.clientId, let userAccessToken = self.userAccessToken else {
            print("ERROR Tink: accessToken or clientId is empty!!")
            return
        }

        let configuration = TinkMoneyManagerConfiguration(clientID: clientId)
        Tink.configure(with: configuration)
        Tink.shared.userSession = .accessToken(userAccessToken)

        let colorProvider = ColorProvider()
        colorProvider.background = UIColor(red: 251/255, green: 251/255, blue: 252/255, alpha: 1.0)
        colorProvider.secondaryBackground = .white
        colorProvider.groupedBackground = UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 1.0)
        colorProvider.accent = UIColor(red: 66/255, green: 119/255, blue: 131/255, alpha: 1.0)
        colorProvider.expenses = UIColor(red: 66/255, green: 119/255, blue: 131/255, alpha: 1.0)
        colorProvider.income = .systemGreen
        colorProvider.transfers = .systemGray
        colorProvider.button = UIColor(red: 92/255, green: 45/255, blue: 145/255, alpha: 1.0)
        colorProvider.label = .black
        colorProvider.separator = UIColor(red: 238/255, green: 238/255, blue: 238/255, alpha: 1.0)
        let insightColors = ColorProvider()
        insightColors.buttonLabel = .white
        

        let fontProvider = FontProvider()
        fontProvider.lightFont = .custom("Proximus-Light")
        fontProvider.regularFont = .custom("Proximus-Regular")
        fontProvider.semiBoldFont = .custom("Proximus-Bold")
        fontProvider.boldFont = .custom("Proximus-ExtraBold")

        Appearance.provider = AppearanceProvider(colors: colorProvider, fonts: fontProvider)
        Appearance.provider.actionableInsightColors = insightColors

        self.insightDelegate = InsightDelegate(
            clientId: self.clientId,
            clientAccessToken: clientAccessToken,
            userId: self.userId,
            idHint: self.idHint,
            redirectUri: self.redirectUri
        )
        guard let insightDelegate = self.insightDelegate else {
            return
        }
        let financeOverviewViewController = FinanceOverviewViewController(
            features: [
                .actionableInsights(delegate: insightDelegate),
                .statistics([.expenses, .income, .leftToSpend]),
                .accounts(AccountsViewController.Predicate.all, AccountsViewController.Grouping.kind),
                .latestTransactions, .budgets, .recommendedBudgets
            ]
        )

        // FinanceOverviewViewController header
        financeOverviewViewController.title = NSLocalizedString("Overview.Title", tableName: "TinkLocalizable", comment: "")
        let backButtonItem = UIBarButtonItem(image: UIImage(named: "back_button"), style: .plain, target: self, action: #selector(backButtonAction))
        financeOverviewViewController.navigationItem.leftBarButtonItems = [backButtonItem]

        // FinanceOverviewViewController config
        financeOverviewViewController.configuration.editAccountFields = [.name, .kind, .isIncluded, .isShared]
        financeOverviewViewController.configuration.editingPendingTransactions = .disabled
        financeOverviewViewController.configuration.transactionItemAction = .showDetails

        let navigationController = UINavigationController(rootViewController: financeOverviewViewController)
        // FinanceOverviewViewController header colors
        financeOverviewViewController.navigationController?.navigationBar.tintColor = UIColor.white
        financeOverviewViewController.navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.white]

        let appearance = UINavigationBarAppearance()
        appearance.configureWithOpaqueBackground()
        appearance.backgroundColor = UIColor(red: 26/255, green: 143/255, blue: 137/255, alpha: 1.0)
        appearance.titleTextAttributes = [.foregroundColor: UIColor.white]
        financeOverviewViewController.navigationController?.navigationBar.standardAppearance = appearance
        financeOverviewViewController.navigationController?.navigationBar.scrollEdgeAppearance = financeOverviewViewController.navigationController?.navigationBar.standardAppearance

        DispatchQueue.main.async {
            if let parentViewController = self.findViewController() {
                parentViewController.addChild(navigationController)
                self.addSubview(navigationController.view)
            }
        }
    }

    private func findViewController() -> UIViewController? {
        var responder: UIResponder? = self

        while let nextResponder = responder?.next {
            if let viewController = nextResponder as? UIViewController {
                return viewController
            }
            responder = nextResponder
        }

        return nil
    }

     @objc func backButtonAction() {
       TinkEventEmitter.emitter.sendEvent(withName: NativeEvents.userPressedBack.name, body: "")
     }
}
