//
//  SuccessScreenViewController.swift
//  Bill24OnlinePaymentSdk
//
//  Created by MacbookPro on 6/11/23.
//

import Foundation
import UIKit

class SuccessScreenViewController: UIViewController{
    @IBOutlet weak var dotLineViewThird: DottedLineView!
    @IBOutlet weak var dotLineViewSecond: DottedLineView!
    @IBOutlet weak var dotLineViewFirst: DottedLineView!
    
    @IBOutlet weak var receiptView: UIView!
    @IBOutlet var successView: UIView!
    @IBOutlet weak var successCardView: UIView!
    @IBOutlet weak var successTitle: UILabel!
    @IBOutlet weak var bankRefLabel: UILabel!
    @IBOutlet weak var transactionIdLabel: UILabel!
    @IBOutlet weak var merchantLabel: UILabel!
    @IBOutlet weak var transactionDateLabel: UILabel!
    @IBOutlet weak var totalLabel: UILabel!
    @IBOutlet weak var downloadView: UIView!
    @IBOutlet weak var shareView: UIView!
    @IBOutlet weak var shareTextLabel: UILabel!
    @IBOutlet weak var downloadTextLabel: UILabel!
    @IBOutlet weak var doneButton: UIButton!
    @IBOutlet weak var feeLabel: UILabel!
    @IBOutlet weak var originalAmountLabel: UILabel!
    
    @IBOutlet weak var downloadIcon: UIImageView!
    @IBOutlet weak var shareIcon: UIImageView!
    
    @IBOutlet weak var totalAmount: UILabel!
    @IBOutlet weak var merchantName: UILabel!
    @IBOutlet weak var bankRef: UILabel!
    @IBOutlet weak var transactionNo: UILabel!
    @IBOutlet weak var transactionDate: UILabel!
    @IBOutlet weak var currency: UILabel!
    @IBOutlet weak var fee: UILabel!
    @IBOutlet weak var originalAmount: UILabel!
    @IBOutlet weak var currencyOriginalAmount: UILabel!
    var transactionSuccess: Transaction?
    weak var presentingVC: UIViewController?
    
    var targetNavigationController: UINavigationController?

    
    public override func viewDidLoad() {
        super.viewDidLoad()
        print("*** Success Screen ****")
        setUpStyleAndConstraint()
        setUpData()
        setUpFont()
        setUpThemes()
        
        downloadView.isUserInteractionEnabled = true
        downloadView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(downloadImage)))

        shareView.isUserInteractionEnabled = true
        shareView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(shareImage)))
        
        
        // Copied text and show snackbar
        transactionNo.isUserInteractionEnabled = true
        transactionNo.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(copyTransactionNo)))
        
        bankRef.isUserInteractionEnabled = true
        bankRef.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(copyBankRef)))
    }
    
    @objc func copyTransactionNo(){
        UIPasteboard.general.string = transactionNo.text
        let message = B24PaymentSdkHelper.localized(SuccessLocalizedKeys.copy.rawValue) + " " +  (transactionNo.text ?? "")
        B24PaymentSdkHelper.successSnackbar(view: self.view, message: message, forBottomSheet: false)
    }
    
    @objc func copyBankRef(){
        UIPasteboard.general.string = bankRef.text
        let message = B24PaymentSdkHelper.localized(SuccessLocalizedKeys.copy.rawValue) + " " + (bankRef.text ?? "")
        B24PaymentSdkHelper.successSnackbar(view: self.view, message: message, forBottomSheet: false)
    }
    
    
    
    func dismissBoth() {
           presentingVC?.dismiss(animated: true, completion: nil)
       }
    
    @objc func shareImage(){
        let image = receiptView.saveAsImage() // Assuming saveAsImage() returns a UIImage
        
        let billerNameDisplay = (transactionSuccess?.data?.biller.billerName) ?? (transactionSuccess?.data?.biller.billerNameKh)
        let amountDisplay = (transactionSuccess?.data?.transInfo.totalAmountDisplay) ?? ""
        let currencyDisplay = (transactionSuccess?.data?.transInfo.currency) ?? ""
        let imageName = "\(billerNameDisplay ?? "")-\(amountDisplay) \(currencyDisplay).png"
        // Get the URL for the documents directory
        if let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
            // Append the custom image name to the documents directory URL
            let fileURL = documentsDirectory.appendingPathComponent(imageName)
            
            // Save the image to the specified URL
            if let data = image.pngData() {
                do {
                    try data.write(to: fileURL)
                    let items: [Any] = [image, imageName]
                    // Now you can share the image using UIActivityViewController
                    let activityViewController = UIActivityViewController(activityItems: items, applicationActivities: nil)
                    
                    // For iPads, you need to specify a source view and arrow direction for the popover
                    activityViewController.popoverPresentationController?.sourceView = self.view
                    activityViewController.popoverPresentationController?.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
                    // Present the activity view controller
                    self.present(activityViewController, animated: true, completion: nil)
                } catch {
                    print("Error saving image: \(error)")
                }
            }
        }
    }
    
    @objc func downloadImage(){
        let image = receiptView.saveAsImage()
        saveImageToPhotoLibrary(image: image)
    }
    
    private func saveImageToPhotoLibrary(image: UIImage) {
        UIImageWriteToSavedPhotosAlbum(image, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
    }
    
    @objc func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeRawPointer) {
        if error != nil{
            B24PaymentSdkHelper.errorSnackbar(
                view: self.view,
                message: B24PaymentSdkHelper.localized(SnackBarLocalizedKeys.error.rawValue),
                forBottomSheet: false
            )
        } else {
            B24PaymentSdkHelper.successSnackbar(
                view: self.view,
                message: B24PaymentSdkHelper.localized(SnackBarLocalizedKeys.saveReceipt.rawValue),
                forBottomSheet: false
            )
        }
    }
    
    private func setUpThemes(){
        self.view.backgroundColor = UIColor(hex: Themes.Property.secondaryBackgroundColor)
        successCardView.backgroundColor = UIColor(hex: Themes.Property.primaryBackgroundColor)
        receiptView.backgroundColor = UIColor(hex: Themes.Property.primaryBackgroundColor)
        successTitle.textColor = UIColor(hex: Themes.Property.primaryTextColor)
        dotLineViewFirst.tintColor = UIColor(hex: Themes.Property.indicatorColor)
        dotLineViewSecond.tintColor = UIColor(hex: Themes.Property.indicatorColor)
        dotLineViewThird.tintColor = UIColor(hex: Themes.Property.indicatorColor)
        
        transactionIdLabel.textColor = UIColor(hex: Themes.Property.primaryTextColor)
        bankRefLabel.textColor = UIColor(hex: Themes.Property.primaryTextColor)
        merchantLabel.textColor = UIColor(hex: Themes.Property.primaryTextColor)
        transactionDateLabel.textColor = UIColor(hex: Themes.Property.primaryTextColor)
        totalLabel.textColor = UIColor(hex: Themes.Property.primaryTextColor)
        downloadTextLabel.textColor = UIColor(hex: Themes.Property.primaryTextColor)
        shareTextLabel.textColor = UIColor(hex: Themes.Property.primaryTextColor)
        originalAmountLabel.textColor = UIColor(hex: Themes.Property.primaryTextColor)
        currencyOriginalAmount.textColor = UIColor(hex: Themes.Property.primaryTextColor)
        feeLabel.textColor = UIColor(hex: Themes.Property.primaryTextColor)
        
        transactionNo.textColor = UIColor(hex: Themes.Property.primaryTextColor)
        bankRef.textColor = UIColor(hex: Themes.Property.primaryTextColor)
        merchantName.textColor = UIColor(hex: Themes.Property.primaryTextColor)
        transactionDate.textColor = UIColor(hex: Themes.Property.primaryTextColor)
        totalAmount.textColor = UIColor(hex: Themes.Property.primaryTextColor)
        currency.textColor = UIColor(hex: Themes.Property.primaryTextColor)
        originalAmount.textColor = UIColor(hex: Themes.Property.primaryTextColor)
        fee.textColor = UIColor(hex: Themes.Property.primaryTextColor)
        
        doneButton.backgroundColor = UIColor(hex: Themes.Property.buttonBackgroundColor)
        doneButton.titleLabel?.textColor = UIColor(hex: Themes.Property.buttonTextColor)
        
        downloadView.backgroundColor = UIColor(hex: Themes.Property.actionButtonBackgroundColor)
        downloadTextLabel.textColor = UIColor(hex: Themes.Property.primaryTextColor)
        downloadIcon.tintColor = UIColor(hex: Themes.Property.actionButtonTextColor)
        
        shareView.backgroundColor = UIColor(hex: Themes.Property.actionButtonBackgroundColor)
        shareTextLabel.textColor = UIColor(hex: Themes.Property.primaryTextColor)
        shareIcon.tintColor = UIColor(hex: Themes.Property.actionButtonTextColor)

    }
   
    private func setUpStyleAndConstraint(){
        successCardView.layer.cornerRadius = 30
        receiptView.layer.cornerRadius = 30
//        receiptView.roundCorners(corners: [.topLeft, .topRight], radius: 30.0)
        if (SDKVariableSetting.isDarkMode == false){
            let shadowColor =  UIColor(red: 0, green: 0, blue: 0)
            successCardView.layer.shadowColor = shadowColor.cgColor
            successCardView.layer.shadowOffset = CGSize(width: 0, height: 0)
            successCardView.layer.shadowOpacity = 0.10
            successCardView.layer.shadowRadius = 12
            successCardView.layer.masksToBounds = false
        }
       
        downloadView.layer.cornerRadius = 10
        shareView.layer.cornerRadius = 10
        doneButton.layer.cornerRadius = 10
    }
    
    private func setUpData(){
        let transactionData = (transactionSuccess?.data)
        
        successTitle.text =  B24PaymentSdkHelper.localized(SuccessLocalizedKeys.title.rawValue)
        transactionIdLabel.text = B24PaymentSdkHelper.localized(SuccessLocalizedKeys.transactionNo.rawValue)
        bankRefLabel.text = B24PaymentSdkHelper.localized(SuccessLocalizedKeys.bankRef.rawValue)
        merchantLabel.text = B24PaymentSdkHelper.localized(SuccessLocalizedKeys.merchantName.rawValue)
        transactionDateLabel.text = B24PaymentSdkHelper.localized(SuccessLocalizedKeys.transactionDate.rawValue)
        totalLabel.text = B24PaymentSdkHelper.localized(SuccessLocalizedKeys.totalLabel.rawValue)
        downloadTextLabel.text = B24PaymentSdkHelper.localized(LocalizedKeys.download.rawValue)
        shareTextLabel.text = B24PaymentSdkHelper.localized(LocalizedKeys.share.rawValue)
        doneButton.setTitle(B24PaymentSdkHelper.localized(SuccessLocalizedKeys.button.rawValue), for: .normal)
        feeLabel.text = B24PaymentSdkHelper.localized(SuccessLocalizedKeys.feeLabel.rawValue)
        originalAmountLabel.text = B24PaymentSdkHelper.localized(SuccessLocalizedKeys.originalAmountLabel.rawValue)
        
        transactionNo.text = (transactionData?.transInfo.tranNo)
        bankRef.text = (transactionData?.transInfo.bankRefID)
        
        // Display BillerName
        if(SDKVariableSetting.currentLanguage.lowercased() == "en"){
            merchantName.text = (transactionData?.biller.billerName ?? transactionData?.biller.billerNameKh)
        }else{
            merchantName.text =  (transactionData?.biller.billerNameKh ?? transactionData?.biller.billerName)
        }
        
        transactionDate.text = (transactionData?.transInfo.tranDate)
        totalAmount.text = (transactionData?.transInfo.totalAmountDisplay)
        originalAmount.text = (transactionData?.transInfo.tranAmountDisplay)
        currencyOriginalAmount.text = (transactionData?.transInfo.currency)
        fee.text = (transactionData?.transInfo.feeAmountDisplay)
        currency.text = (transactionData?.transInfo.currency)
    }
    
    private func setUpFont(){
        successTitle.font =  FontManager.shared.boldFont(forLanguage: SDKVariableSetting.currentLanguage, size: 18.0)
        transactionIdLabel.font =  FontManager.shared.regularFont(forLanguage: SDKVariableSetting.currentLanguage, size: 15.0)
        bankRefLabel.font =  FontManager.shared.regularFont(forLanguage: SDKVariableSetting.currentLanguage, size: 15.0)
        merchantLabel.font =  FontManager.shared.regularFont(forLanguage: SDKVariableSetting.currentLanguage, size: 15.0)
        transactionDateLabel.font =  FontManager.shared.regularFont(forLanguage: SDKVariableSetting.currentLanguage, size: 15.0)
        downloadTextLabel.font =  FontManager.shared.regularFont(forLanguage: SDKVariableSetting.currentLanguage, size: 13.0)
        shareTextLabel.font =  FontManager.shared.regularFont(forLanguage: SDKVariableSetting.currentLanguage, size: 13.0)
        feeLabel.font =  FontManager.shared.regularFont(forLanguage: SDKVariableSetting.currentLanguage, size: 15.0)
        originalAmountLabel.font =  FontManager.shared.regularFont(forLanguage: SDKVariableSetting.currentLanguage, size: 15.0)
        currencyOriginalAmount.font = FontManager.shared.regularFont(forLanguage: SDKVariableSetting.currentLanguage, size: 15.0)
        totalLabel.font =  FontManager.shared.boldFont(forLanguage: SDKVariableSetting.currentLanguage, size: 17.0)
        totalAmount.font =  B24PaymentSdkHelper.setFont(named: "Roboto-Bold", ofSize: 17.0)
        currency.font =  B24PaymentSdkHelper.setFont(named: "Roboto-Bold", ofSize: 17.0)
        
        transactionNo.font = B24PaymentSdkHelper.setFont(named: "Roboto-Medium", ofSize: 15.0)
        bankRef.font = B24PaymentSdkHelper.setFont(named: "Roboto-Medium", ofSize: 15.0)
        merchantName.font = FontManager.shared.boldFont(forLanguage: SDKVariableSetting.currentLanguage, size: 15.0)
        transactionDate.font = B24PaymentSdkHelper.setFont(named: "Roboto-Medium", ofSize: 15.0)
        doneButton.titleLabel?.font = FontManager.shared.regularFont(forLanguage: SDKVariableSetting.currentLanguage, size: 14.0)
        fee.font = B24PaymentSdkHelper.setFont(named: "Roboto-Medium", ofSize: 15.0)
        originalAmount.font = B24PaymentSdkHelper.setFont(named: "Roboto-Medium", ofSize: 15.0)
        currencyOriginalAmount.font = B24PaymentSdkHelper.setFont(named: "Roboto-Medium", ofSize: 15.0)
    }
    
    
    @IBAction func onClickDoneButton(_ sender: Any) {
        
        self.dismiss(animated: true){ [self] in
            B24PaymentSdkHelper.openDeeplink(deepLinkUrl: (self.transactionSuccess?.data?.transInfo.redirectURL) ?? "", view: self.view, forBottomSheet: false)
            self.dismissBoth()
        }
        
       
    }
    
    
}
