//
//  EditDialog.swift
//  B24PaymentSdk
//
//  Created by visal ny on 25/12/24.
//

import UIKit

class EditDialog: UIViewController {
    
    @IBOutlet weak var dialogContainer: UIView!
    
    @IBOutlet weak var inputField: UITextField!
    @IBOutlet weak var buttonCancel: UIButton!
    @IBOutlet weak var buttonOk: UIButton!
    
    var okActionHandler: ((_ inputText: String) -> Void)?
    var cancelActionHandler: (() -> Void)?
    private var initialText: String = ""

    
    var language:String?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.black.withAlphaComponent(0.5)

        
        getSharePref()
        B24PaymentSdkHelper.getCurrentLanguage(language: language)
        
        setUpUI()

        inputField.text = initialText


    }
    
    
    func getSharePref(){
        if let languageCode = SharedPreferenceManager.getString(forKey: SharePrefKey.lanuageCode.rawValue){
            language = languageCode
        }else{
            language = "km"
        }
    }
    
    
    func setUpUI(){
        dialogContainer.backgroundColor = DefaultAppearance.shared.cardColor
        dialogContainer.layer.cornerRadius = 8
        inputField.layer.cornerRadius = 8.0
        inputField.backgroundColor = DefaultAppearance.shared.screenBgColor
        inputField.textColor = DefaultAppearance.shared.primaryLabelColor
        inputField.font = FontManager.shared.regularFont(forLanguage: language ?? "km", fontFromconfig: DefaultAppearance.shared.fontEnglish, size: FixFontSize.contentText)
        
        let placeholderText = B24PaymentSdkHelper.localized(AddWalletLocalizedKeys.placeholder_wallet_name.rawValue)
        let placeholderColor = DefaultAppearance.shared.primaryLabelColor.withAlphaComponent(0.3)

        inputField.attributedPlaceholder = NSAttributedString(
            string: placeholderText,
            attributes: [NSAttributedString.Key.foregroundColor: placeholderColor]
        )
        
        self.addPadding(to: inputField)
        
        
        let okTitle = NSAttributedString(
            string : B24PaymentSdkHelper.localized(DialogLocalizedKeys.ok.rawValue),
            attributes: [
                .font: FontManager.shared.regularFont(forLanguage: language ?? "km",fontFromconfig: DefaultAppearance.shared.fontEnglish, size: FixFontSize.contentText),
                .foregroundColor: DefaultAppearance.shared.onPrimaryColor,
                
            ]
        )
        buttonOk.setAttributedTitle(okTitle, for: .normal)
        
        
//        buttonOk.tintColor = DefaultAppearance.shared.primaryColor
//        buttonOk.setTitleColor(DefaultAppearance.shared.onPrimaryColor, for: .normal)
//        buttonOk.titleLabel?.font = FontManager.shared.mediumFont(forLanguage: language ?? "km", size: FixFontSize.contentText)
        
        
        
        let cancelTitle = NSAttributedString(
            string : B24PaymentSdkHelper.localized(DialogLocalizedKeys.cancel.rawValue),
            attributes: [
                .font: FontManager.shared.regularFont(forLanguage: language ?? "km", fontFromconfig: DefaultAppearance.shared.fontEnglish,size: FixFontSize.contentText),
                .foregroundColor: DefaultAppearance.shared.primaryLabelColor
            ]
        )
        buttonCancel.setAttributedTitle(cancelTitle, for: .normal)
        
        
//        buttonCancel.setTitleColor(DefaultAppearance.shared.primaryLabelColor, for: .normal)
//        buttonCancel.titleLabel?.font = FontManager.shared.regularFont(forLanguage: language ?? "km", size: FixFontSize.contentText)
        
    }
    
    
    private func showErrorMessage(_ message: String) {
        let errorLabel = UILabel()
        errorLabel.text = message
        errorLabel.textColor = .systemRed
        errorLabel.font = .systemFont(ofSize: 11)
        errorLabel.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(errorLabel)
        
        // Position error label below the text field
        NSLayoutConstraint.activate([
            errorLabel.topAnchor.constraint(equalTo: inputField.bottomAnchor, constant: 2),
            errorLabel.leadingAnchor.constraint(equalTo: inputField.leadingAnchor),
            errorLabel.trailingAnchor.constraint(equalTo: inputField.trailingAnchor)
        ])
        
    }
    
    
    func configure(
            okButtonTitle: String,
            cancelButtonTitle: String,
            okHandler: @escaping (_ inputText: String) -> Void,
            cancelHandler: @escaping () -> Void
    ) {
        
        DispatchQueue.main.async {
            if let okButton = self.buttonOk {
                okButton.setTitle(okButtonTitle, for: .normal)
            }
            if let cancelButton = self.buttonCancel {
                cancelButton.setTitle(cancelButtonTitle, for: .normal)
            }
       
            
            self.okActionHandler = okHandler
            self.cancelActionHandler = cancelHandler
        }
    }
    
    
    @IBAction func cancelAction(_ sender: Any) {
        dismiss(animated: true) {
          self.cancelActionHandler?()
        }
    }
    @IBAction func okAction(_ sender: Any) {
        guard let inputText = inputField.text?.trimmingCharacters(in: .whitespacesAndNewlines), !inputText.isEmpty else {
            inputField.layer.borderWidth = 1
            inputField.layer.masksToBounds = true
            inputField.layer.cornerRadius = 8.0
            inputField.layer.borderColor = UIColor.red.cgColor
            
            
            showErrorMessage(B24PaymentSdkHelper.localized(AddWalletLocalizedKeys.required.rawValue));
            
            return
        }
        dismiss(animated: true) {
            self.okActionHandler?(inputText)
        }
    }
    

    func setDefaultText(_ text: String) {
        self.initialText = text
    }

    func showEditDialog(from presentingViewController: UIViewController,
                       defaultText: String = "",
                       okHandler: @escaping (_ inputText: String) -> Void,
                       cancelHandler: @escaping () -> Void) {
        let storyboard = UIStoryboard(name: "InstantPaymentMethodView", bundle: B24PaymentSdkHelper.frameworkBundle())
        guard let alertView = storyboard.instantiateViewController(withIdentifier: "EditDialogView") as? EditDialog else {
            return
        }

        alertView.modalPresentationStyle = .overFullScreen
        alertView.modalTransitionStyle = .crossDissolve

        alertView.setDefaultText(defaultText)  // Set the default text

        alertView.configure(
            okButtonTitle: B24PaymentSdkHelper.localized(DialogLocalizedKeys.ok.rawValue),
            cancelButtonTitle: B24PaymentSdkHelper.localized(DialogLocalizedKeys.cancel.rawValue),
            okHandler: okHandler,
            cancelHandler: cancelHandler
        )

        presentingViewController.present(alertView, animated: true)
    }

   
    func addPadding(to textField: UITextField) {
        let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: textField.frame.height))
        textField.leftView = paddingView
        textField.leftViewMode = .always
    }
    
}
