import UIKit
import Alamofire

class AddWalletView: UIViewController {
    // MARK: - Properties
    private var loadingView: LoadingView?
    private var customerSyncCode = ""
    private let options = ["KHR","USD"]
    var language:String = "km"

    // MARK: - UI Components
    private let containerView: UIView = {
        let view = UIView()
        view.backgroundColor = DefaultAppearance.shared.screenBgColor
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()
    

    private lazy var walletNameField: UITextField = {
        let field = UITextField()
        field.translatesAutoresizingMaskIntoConstraints = false
        field.placeholder = B24PaymentSdkHelper.localized(AddWalletLocalizedKeys.placeholder_wallet_name.rawValue)
        field.backgroundColor = DefaultAppearance.shared.cardColor
        field.textColor = DefaultAppearance.shared.primaryLabelColor
        field.layer.cornerRadius = 8
        field.layer.borderWidth = 1
        field.layer.borderColor = UIColor.systemGray5.cgColor
        // Set placeholder text color
        let placeholderText = B24PaymentSdkHelper.localized(AddWalletLocalizedKeys.placeholder_wallet_name.rawValue)
        let placeholderColor = DefaultAppearance.shared.primaryLabelColor.withAlphaComponent(0.3)
        let placeholderFont = FontManager.shared.regularFont(forLanguage: language ,fontFromconfig: DefaultAppearance.shared.fontEnglish, size: FixFontSize.contentText)
        field.attributedPlaceholder = NSAttributedString(
            string: placeholderText,
            attributes: [
                .foregroundColor: placeholderColor,
                .font: placeholderFont]
        )
        return field
       
    }()

    private let currencyField: UITextField = {
        let field = UITextField()
        field.translatesAutoresizingMaskIntoConstraints = false
        field.placeholder = "Currency"
        field.backgroundColor = DefaultAppearance.shared.cardColor
        field.layer.cornerRadius = 8
        field.layer.borderWidth = 1
        field.layer.borderColor = UIColor.systemGray5.cgColor
        field.tintColor = .clear
        field.textColor = DefaultAppearance.shared.primaryLabelColor
        return field
    }()

    private lazy var saveButton: UIButton = {
        let button = UIButton(type: .system)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.setTitle(B24PaymentSdkHelper.localized(AddWalletLocalizedKeys.save_button.rawValue), for: .normal)
        button.titleLabel?.font = FontManager.shared.mediumFont(forLanguage: language, fontFromconfig: DefaultAppearance.shared.fontEnglish,size: FixFontSize.buttonText)
        button.backgroundColor = DefaultAppearance.shared.primaryColor
        button.setTitleColor(DefaultAppearance.shared.onPrimaryColor, for: .normal)
        button.layer.cornerRadius = 8
        return button
    }()

    private let dropdownImageView: UIImageView = {
        let imageView = UIImageView(image: UIImage(systemName: "chevron.down"))
        imageView.tintColor = DefaultAppearance.shared.primaryLabelColor
        imageView.contentMode = .scaleAspectFit
        return imageView
    }()

    private let pickerView = UIPickerView()

    private lazy var customDoneView: UIView = {
        let view = UIView()
        view.backgroundColor = DefaultAppearance.shared.screenBgColor
        view.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 60)

        let doneButton = UIButton(type: .system)
        doneButton.frame = CGRect(x: 0, y: 0, width: 120, height: 40)
        doneButton.center = CGPoint(x: view.bounds.width / 2, y: view.bounds.height / 2)
        doneButton.backgroundColor = DefaultAppearance.shared.primaryColor
        doneButton.setTitle(B24PaymentSdkHelper.localized(AddWalletLocalizedKeys.done.rawValue), for: .normal)
        doneButton.setTitleColor(DefaultAppearance.shared.onPrimaryColor, for: .normal)
        //doneButton.titleLabel?.font = .systemFont(ofSize: 16, weight: .semibold)
        doneButton.titleLabel?.font = FontManager.shared.regularFont(forLanguage: language,fontFromconfig: DefaultAppearance.shared.fontEnglish, size: FixFontSize.buttonText)
        doneButton.layer.cornerRadius = 20
        doneButton.layer.shadowColor = UIColor.black.cgColor
        doneButton.layer.shadowOffset = CGSize(width: 0, height: 2)
        doneButton.layer.shadowRadius = 4
        doneButton.layer.shadowOpacity = 0.1
        doneButton.addTarget(self, action: #selector(doneTapped), for: .touchUpInside)

        view.addSubview(doneButton)

        let separatorLine = UIView()
        separatorLine.backgroundColor = .systemGray5
        separatorLine.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: 0.5)
        view.addSubview(separatorLine)

        return view
    }()
    
    

    @IBOutlet weak var toolbarLine: UIView!
    // MARK: - Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        
        toolbarLine.isHidden = true
        
        getSharePef()
        
        B24PaymentSdkHelper.getCurrentLanguage(language: language)

        applyToolBar()

        setupView()
        setupConstraints()
        setupPickerView()
        setupTextFields()
        //applySeparateLine()

    }
    
//    override func viewWillAppear(_ animated: Bool) {
//        super.viewWillAppear(animated)
//
//        // Animate the appearance of the separator line
//        UIView.animate(withDuration: 0.3, delay: 0, options: [.curveEaseInOut], animations: {
//            self.applySeparateLine()
//        }, completion: nil)
//    }

    private func getSharePef(){
        if let languageCode = SharedPreferenceManager.getString(forKey: SharePrefKey.lanuageCode.rawValue){
            language = languageCode
        }else{
            language = "km"
        }
        
        if let userSynCode = SharedPreferenceManager.getString(forKey: SharePrefKey.customerSyncode.rawValue){
            customerSyncCode = userSynCode
        }else{
            customerSyncCode = ""
        }
    }

    private func applySeparateLine() {
        guard let navigationBar = self.navigationController?.navigationBar else { return }

        let separatorLine = UIView()
        separatorLine.backgroundColor = DefaultAppearance.shared.primaryLabelColor
            .withAlphaComponent(0.5)
        separatorLine.tag = 100
        separatorLine.translatesAutoresizingMaskIntoConstraints = false
        separatorLine.alpha = 0.5// Set opacity to 50%

        // Add the separator line without animation
        navigationBar.addSubview(separatorLine)
        NSLayoutConstraint.activate([
            separatorLine.leadingAnchor.constraint(equalTo: navigationBar.leadingAnchor),
            separatorLine.trailingAnchor.constraint(equalTo: navigationBar.trailingAnchor),
            separatorLine.bottomAnchor.constraint(equalTo: navigationBar.bottomAnchor, constant: 10.5),
            separatorLine.heightAnchor.constraint(equalToConstant: 1)
        ])

    }



    // Add this method to remove the line when leaving the screen
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)

        // Remove the separator line
        navigationController?.navigationBar.subviews.forEach { view in
            if view.tag == 100 {
                view.removeFromSuperview()
            }
        }
    }

    private func applyToolBar(){
        // Configure navigation bar appearance for consistency
        if #available(iOS 13.0, *) {
            let appearance = UINavigationBarAppearance()
            appearance.configureWithOpaqueBackground()
            appearance.backgroundColor = DefaultAppearance.shared.screenBgColor
            appearance.shadowColor = DefaultAppearance.shared.primaryLabelColor.withAlphaComponent(0.3)
            
            navigationController?.navigationBar.standardAppearance = appearance
            navigationController?.navigationBar.scrollEdgeAppearance = appearance
            navigationController?.navigationBar.compactAppearance = appearance
        } else {
            navigationController?.navigationBar.barTintColor = DefaultAppearance.shared.screenBgColor
            navigationController?.navigationBar.isTranslucent = false
        }
        
        let customButton = UIButton(type: .system)
        // Image
        let imageView = UIImageView(image: UIImage(systemName: "chevron.backward"))
        imageView.tintColor = DefaultAppearance.shared.primaryLabelColor
        imageView.contentMode = .scaleAspectFit
        imageView.translatesAutoresizingMaskIntoConstraints = false
        customButton.addSubview(imageView)
        
        let titleLabel = UILabel()
        
        titleLabel.text = B24PaymentSdkHelper.localized(AddWalletLocalizedKeys.title.rawValue)
        
        titleLabel.textColor = DefaultAppearance.shared.primaryLabelColor
        titleLabel.font = FontManager.shared.mediumFont(forLanguage: language,fontFromconfig: DefaultAppearance.shared.fontEnglish, size: FixFontSize.toolbarTitle)
        titleLabel.translatesAutoresizingMaskIntoConstraints = false
        customButton.addSubview(titleLabel)

        // Add constraints to position the image and title properly
        NSLayoutConstraint.activate([
            imageView.leadingAnchor.constraint(equalTo: customButton.leadingAnchor,constant: -10),
            imageView.centerYAnchor.constraint(equalTo: customButton.centerYAnchor),
            imageView.widthAnchor.constraint(equalToConstant: 24), // Set desired width
            imageView.heightAnchor.constraint(equalToConstant: 24),
            
            titleLabel.leadingAnchor.constraint(equalTo: imageView.trailingAnchor, constant: 8),
            titleLabel.centerYAnchor.constraint(equalTo: customButton.centerYAnchor),
            titleLabel.trailingAnchor.constraint(equalTo: customButton.trailingAnchor)
        ])

        // Add action to the button
        customButton.addTarget(self, action: #selector(backButtonTapped), for: .touchUpInside)

        // Create a UIBarButtonItem with the custom button
        let backButton = UIBarButtonItem(customView: customButton)
        navigationItem.leftBarButtonItem = backButton
    }
    
    // Back button action
    @objc func backButtonTapped() {
        navigationController?.popViewController(animated: true)
    }

    // MARK: - Setup Methods
    private func setupView() {
        view.backgroundColor = DefaultAppearance.shared.screenBgColor

        view.addSubview(containerView)
        containerView.addSubview(walletNameField)
        containerView.addSubview(currencyField)
        containerView.addSubview(saveButton)

        walletNameField.becomeFirstResponder()
        walletNameField.font = FontManager.shared.regularFont(forLanguage: language,fontFromconfig: DefaultAppearance.shared.fontEnglish ,size: FixFontSize.contentText)
        
        saveButton.addTarget(self, action: #selector(buttonSave), for: .touchUpInside)
    }

    private func setupConstraints() {
        NSLayoutConstraint.activate([
            // Container View
            containerView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 25), // Increased top padding
            containerView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            containerView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            containerView.bottomAnchor.constraint(equalTo: view.bottomAnchor),

            // Wallet Name Field
            walletNameField.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 20),
            walletNameField.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 16),
            walletNameField.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -16),
            walletNameField.heightAnchor.constraint(equalToConstant: 50),

            // Currency Field
            currencyField.topAnchor.constraint(equalTo: walletNameField.bottomAnchor, constant: 16),
            currencyField.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 16),
            currencyField.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -16),
            currencyField.heightAnchor.constraint(equalToConstant: 50),

            // Save Button
            saveButton.topAnchor.constraint(equalTo: currencyField.bottomAnchor, constant: 24),
            saveButton.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 16),
            saveButton.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -16),
            saveButton.heightAnchor.constraint(equalToConstant: 50)
        ])
    }

    private func setupTextFields() {
        addPadding(to: walletNameField)
        setupCurrencyField()
    }

    private func setupCurrencyField() {
        addPadding(to: currencyField)

        dropdownImageView.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
        let containerView = UIView(frame: CGRect(x: 0, y: 0, width: 40, height: 20))
        containerView.addSubview(dropdownImageView)
        dropdownImageView.center = containerView.center

        currencyField.rightView = containerView
        currencyField.rightViewMode = .always

        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(currencyFieldTapped))
        currencyField.addGestureRecognizer(tapGesture)
        currencyField.isUserInteractionEnabled = true
        
    }

    private func setupPickerView() {
        pickerView.delegate = self
        pickerView.dataSource = self
        //pickerView.backgroundColor = DefaultAppearance.shared.screenBgColor
        currencyField.inputView = pickerView
        currencyField.inputAccessoryView = customDoneView
        currencyField.text = options[0]
        currencyField.font = FontManager.shared.regularFont(forLanguage: language,fontFromconfig: DefaultAppearance.shared.fontEnglish, size: FixFontSize.contentText)
    }

    // MARK: - Helper Methods
    private func addPadding(to textField: UITextField) {
        let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: 15, height: textField.frame.height))
        textField.leftView = paddingView
        textField.leftViewMode = .always
    }

    // MARK: - Actions
    @objc private func currencyFieldTapped() {
        currencyField.becomeFirstResponder()
        rotateDropdownArrow(up: true)

        UIView.animate(withDuration: 0.3) {
            self.pickerView.alpha = 1.0
        }
    }

    @objc private func doneTapped() {
        let generator = UIImpactFeedbackGenerator(style: .medium)
        generator.impactOccurred()

        UIView.animate(withDuration: 0.1, animations: {
            self.customDoneView.transform = CGAffineTransform(scaleX: 0.95, y: 0.95)
        }) { _ in
            UIView.animate(withDuration: 0.1) {
                self.customDoneView.transform = .identity
            }
        }

        UIView.animate(withDuration: 0.3, animations: {
            self.pickerView.alpha = 0.0
        }) { _ in
            self.currencyField.resignFirstResponder()
            self.rotateDropdownArrow(up: false)
        }
    }

    private func rotateDropdownArrow(up: Bool) {
        UIView.animate(withDuration: 0.3) {
            self.dropdownImageView.transform = up ? CGAffineTransform(rotationAngle: .pi) : .identity
        }
    }
    
    private var errorLabel: UILabel?
    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: walletNameField.bottomAnchor, constant: 0),
//            errorLabel.leadingAnchor.constraint(equalTo: walletNameField.leadingAnchor),
//            errorLabel.trailingAnchor.constraint(equalTo: walletNameField.trailingAnchor)
//        ])
//
        if errorLabel == nil {
                errorLabel = UILabel()
                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: walletNameField.bottomAnchor, constant: 0),
                    errorLabel!.leadingAnchor.constraint(equalTo: walletNameField.leadingAnchor),
                    errorLabel!.trailingAnchor.constraint(equalTo: walletNameField.trailingAnchor)
                ])
            }
            
        errorLabel?.text = message  // Update existing label's text
        
    }
    
    private func removeErrorMessage(){
        errorLabel?.removeFromSuperview()
        errorLabel = nil
    }

    @objc private func buttonSave(_ sender: Any) {
//        guard let accountName = walletNameField.text, !accountName.isEmpty,
//              let currency = currencyField.text, !currency.isEmpty else {
//            showError(message: "Please fill in all fields")
//            return
//        }
        
        guard let accountName = walletNameField.text?.trimmingCharacters(in: .whitespacesAndNewlines), !accountName.isEmpty,
              let currency = currencyField.text, !currency.isEmpty else {
                walletNameField.layer.borderWidth = 1
                walletNameField.layer.masksToBounds = true
                walletNameField.layer.cornerRadius = 8.0
                walletNameField.layer.borderColor = UIColor.red.cgColor
            
                showErrorMessage(B24PaymentSdkHelper.localized(AddWalletLocalizedKeys.required.rawValue))
                   
                return
            }
        
        walletNameField.resignFirstResponder()
        walletNameField.layer.borderColor = UIColor.systemGray5.cgColor
        removeErrorMessage()
        

        let payload = WalletPayload(
            account_name: accountName,
            customer_sync_code: customerSyncCode,
            currency: currency
        )

        do {
            let jsonData = try JSONEncoder().encode(payload)
            guard let jsonString = String(data: jsonData, encoding: .utf8) else {
                showError(message: "Failed to create payload")
                return
            }

            let encryptedText = try EncryptionHelper.encryptHMACAES(
                plainText: jsonString,
                secretKey: SDKVariableSetting.walletSecretKey
            )

            sendEncryptedWalletData(encryptedText)

        } catch {
            showError(message: "Encryption failed: \(error.localizedDescription)")
        }
    }

    // MARK: - Networking
    private func sendEncryptedWalletData(_ encryptedData: String) {
        let url = APIManager.merchantApiUrl().appendingPathComponent("instantpaymentsdk/create/wallet")
        let parameters: [String: Any] = ["encrypted": encryptedData]

        loadingView = LoadingView.show(in: self)

        AF.request(
            url,
            method: .post,
            parameters: parameters,
            encoding: JSONEncoding.default,
            headers: APIManager.initWalletHeader()
        ).responseData { [weak self] response in
            guard let self = self else { return }

            self.loadingView?.dismiss {
                switch response.result {
                case .success(let data):
                    do {
                        let decoder = JSONDecoder()
                        let apiResponse = try decoder.decode(ApiResponse<WalletResponseData>.self, from: data)

                        if apiResponse.code == StatusCode.succcess.rawValue {
                            DispatchQueue.main.async {

                                self.handleSuccessfulWalletCreation()
                            }
                        } else {
                            DispatchQueue.main.async {
                               // self.showError(message: apiResponse.message)
                                //let message = B24PaymentSdkHelper.localized(AddWalletLocalizedKeys.can_not_create_wallet.rawValue)
                                let message = self.language == "km" ? apiResponse.messageKh:apiResponse.message
                                B24PaymentSdkHelper.errorSnackbar(view: self.view,message: message )
                            }
                            
                        }
                    } catch {
                        print("Decoding error:", error)
                      
                            //self.showError(message: "Failed to process server response.")
                        B24PaymentSdkHelper.errorSnackbar(
                            view:self.view,
                                            message: B24PaymentSdkHelper.localized(AddWalletLocalizedKeys.can_not_create_wallet.rawValue),
                                                forBottomSheet: false)
                        
                    }
                case .failure(let error):
                    print("Network error:", error)
//                    DispatchQueue.main.async {
//                        self.showError(message: "Network error: \(error.localizedDescription)")
//                    }
                        B24PaymentSdkHelper.errorSnackbar(
                            view:self.view,
                            message: B24PaymentSdkHelper.localized(SnackBarLocalizedKeys.error.rawValue),
                            forBottomSheet: false)
                    }
                }
            }
        }

    private func handleSuccessfulWalletCreation() {
//        if let availablePaymentMethodVC = navigationController?.viewControllers.first(
//            where: { $0 is InstantPaymentMethodViewController }
//        ) {
//            navigationController?.popToViewController(availablePaymentMethodVC, animated: true)
//        } else {
//            print("Could not find the target view controller.")
//        }
       // navigationController?.popToRootViewController(animated: true)
        let storyboard = UIStoryboard(name: "InstantPaymentMethodView", bundle: B24PaymentSdkHelper.frameworkBundle())
        if let instantPaymentMethod = storyboard.instantiateViewController(withIdentifier: "InstantPMView") as? InstantPMView {
            navigationController?.pushViewController(instantPaymentMethod, animated: true)
        }
        

    }

    private func showError(message: String) {
        let alert = UIAlertController(
            title: "Error",
            message: message,
            preferredStyle: .alert
        )
        alert.addAction(UIAlertAction(title: "OK", style: .default))
        present(alert, animated: true)
    }
}

// MARK: - UIPickerView Delegate and Data Source
extension AddWalletView: UIPickerViewDelegate, UIPickerViewDataSource {
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return options.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return options[row]
    }
    // Customize the row view with a custom font
    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        let label: UILabel
        if let reusedLabel = view as? UILabel {
            label = reusedLabel // Reuse existing label if available
        } else {
                label = UILabel() // Create a new label
                label.textAlignment = .center
        }

        // Set the text and font
        label.text = options[row]
        label.font = FontManager.shared.regularFont(forLanguage: language, fontFromconfig: DefaultAppearance.shared.fontEnglish, size: FixFontSize.buttonText)

        return label
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        currencyField.text = options[row]
        
        if options[row] == "USD" {
            currencyField.textColor = UIColor(hex: "#b0b0b0")
        }else{
            currencyField.textColor = DefaultAppearance.shared.primaryLabelColor
        }

    }
}
