package com.dspread.pos.ui.cashier;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;

import androidx.lifecycle.viewmodel.CreationExtras;

import com.dspread.pos.common.base.BaseFragment;
import com.dspread.pos.TitleProviderListener;

import com.dspread.pos_android_app.R;
import com.dspread.pos_android_app.databinding.FragmentCashierBinding;

import com.dspread.pos_android_app.BR;

import android.view.KeyEvent;

import android.view.View;

import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import org.json.JSONObject;

public class CashierFragment extends BaseFragment<FragmentCashierBinding, CashierViewModel  >
        implements TitleProviderListener{
    private EditText etAmountInput;
    @Override
    public void initViewObservable() {

// Observe payment info LiveData
        viewModel.getPaymentInfo().observe(getViewLifecycleOwner(), paymentInfo -> {
            if (paymentInfo != null) {
                Log.d("CashierFragment", "Payment Info Updated: " + paymentInfo);
            }
        });

        // Observe payment status LiveData
        viewModel.getPaymentStatus().observe(getViewLifecycleOwner(), paymentStatus -> {
            Log.d("CashierFragment", "Payment Status Updated: " + paymentStatus);
        });

    }

    @Override
    public String getTitle() {
        return "Cashier";
    }

    @Override
    public int initContentView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return R.layout.fragment_cashier;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public void initData() {
        super.initData();

        // Setup amount input field
        setupAmountInput();
    }
    private void setupAmountInput() {
        // Find the EditText in layout
        etAmountInput = binding.getRoot().findViewById(R.id.etAmountInput);

        if (etAmountInput != null) {
            // Request focus
            etAmountInput.requestFocus();

            // Add text watcher to update amount in real-time
            etAmountInput.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {}

                @Override
                public void afterTextChanged(Editable s) {
                    String input = s.toString().trim();
                    if (!input.isEmpty()) {
                        try {
                            // Convert cents to dollars and update ViewModel
                            double dollars = Double.parseDouble(input) / 100.0;
                            viewModel.amount.set(String.format("%.2f", dollars));
                        } catch (NumberFormatException e) {
                            // Handle invalid input
                            viewModel.amount.set("0.00");
                        }
                    } else {
                        viewModel.amount.set("0.00");
                    }
                }
            });

            // Set up Enter key listener
            etAmountInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                    if (actionId == EditorInfo.IME_ACTION_DONE) {
                        handleEnterPressed();
                        return true;
                    }
                    return false;
                }
            });

            // Handle physical keyboard Enter key
            etAmountInput.setOnKeyListener(new View.OnKeyListener() {
                @Override
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
                        handleEnterPressed();
                        return true;
                    }
                    return false;
                }
            });
        }
    }

    private void handleEnterPressed() {
        if (etAmountInput != null) {
            String amount = etAmountInput.getText().toString().trim();
            String deviceIdM50 = "01534090202502210065";
            String deviceIdM20 = "01220110202305150514";


            if (!amount.isEmpty()) {
                try {
                    // Create JSON signal
                    JSONObject paymentData = new JSONObject();
                    paymentData.put("type", "redirect");
                    paymentData.put("amount", amount);
                    paymentData.put("currencySymbol", "$");
                    paymentData.put("id", deviceIdM50);
                    paymentData.put("status", "signal");

                    JSONObject paymentDataM20 = new JSONObject();
                    paymentDataM20.put("type", "redirect");
                    paymentDataM20.put("amount", amount);
                    paymentDataM20.put("currencySymbol", "$");
                    paymentDataM20.put("id", deviceIdM20);
                    paymentDataM20.put("status", "signal");

                    // Send via WebSocket
                    viewModel.sendMessage(paymentData.toString());
                    viewModel.sendMessage(paymentDataM20.toString());

                    // Reset input field
                    etAmountInput.setText("");

                } catch (Exception e) {
                    Log.e("CashierFragment", "Error creating JSON", e);
                }
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        // Request focus when fragment resumes
        if (etAmountInput != null) {
            etAmountInput.requestFocus();
        }
    }

    @NonNull
    @Override
    public CreationExtras getDefaultViewModelCreationExtras() {
        return super.getDefaultViewModelCreationExtras();
    }
}
