package com.app.simplitend.welcome.welcomepatient.fragments.register;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.Navigation;

import com.onesignal.OneSignal;
import com.app.simplitend.R;
import com.app.simplitend.apputils.AppUtil;
import com.app.simplitend.apputils.PatientDataCache;
import com.app.simplitend.databinding.CreatePinFragmentBinding;
import com.app.simplitend.welcome.welcomepatient.mvvm.WelcomeContracts;
import com.app.simplitend.welcome.welcomepatient.mvvm.WelcomeViewModel;
import com.app.simplitend.welcome.welcomepatient.mvvm.models.PatientData;

public class CreatePinFragment extends Fragment implements WelcomeContracts.RegisterPatientContract {

    private static final String TAG = "CreatePinFragment";

    // view binding
    protected CreatePinFragmentBinding binding;

    // view model (common for this activity)
    private WelcomeViewModel welcomeViewModel;

    private ProgressDialog progressDialog;

    public CreatePinFragment() {
        // required empty const.
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = CreatePinFragmentBinding.inflate(inflater, container, false);

        welcomeViewModel = new ViewModelProvider(requireActivity()).get(WelcomeViewModel.class);

        initViews();

        clickEvents();

        return binding.getRoot();
    }

    private void initViews() {
        loadPinsSavedState();

        progressDialog = new ProgressDialog(requireContext());

        binding.pin.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.toString().length() == 4){
                    binding.confirmPin.requestFocus();
                }
            }
        });

        binding.confirmPin.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.toString().length() == 4){
                    AppUtil.closeKeyboard(requireActivity());
                }
            }
        });
    }

    private void loadPinsSavedState() {
        PatientData patientData = welcomeViewModel.getPatientData();

        binding.pin.setText(patientData.pin_code);
        binding.confirmPin.setText(patientData.c_pin_code);

    }

    private void clickEvents() {

        binding.backBtn.setOnClickListener(v -> {
            if (getActivity() != null){
                getActivity().onBackPressed();
            }
        });

        binding.setPin.setOnClickListener(v ->
                {
                    if (allOkay() && binding.pin.getText() != null && binding.confirmPin.getText() != null) {

                        AppUtil.closeKeyboard(requireActivity());

                        PatientData patientData = welcomeViewModel.getPatientData();

                        patientData.pin_code = binding.pin.getText().toString();
                        patientData.c_pin_code = binding.confirmPin.getText().toString();

                        // setting ONE_SIGNAL Subscription id if available
                        patientData.one_signal_player_id = OneSignal.getUser().getPushSubscription().getId();

                        progressDialog.setTitle("Please wait");
                        progressDialog.setMessage("while we sign you up");
                        progressDialog.setCancelable(false);

                        progressDialog.show();

                        welcomeViewModel.registerPatient(this);
                    }
                }
        );



    }

    private boolean allOkay() {
        boolean allOkay = true;

        if (binding.pin.getText() == null || binding.pin.getText().toString().length() != 4) {
            allOkay = false;
            Toast.makeText(requireContext(), "Enter a 4 digit security pin.", Toast.LENGTH_SHORT).show();
        } else if (binding.confirmPin.getText() == null ||
                !binding.confirmPin.getText().toString().equals(binding.pin.getText().toString())) {
            allOkay = false;
            if (binding.confirmPin.getText().toString().trim().isEmpty()){
                Toast.makeText(requireContext(), "Please enter confirm pin", Toast.LENGTH_SHORT).show();
            }else{
                Toast.makeText(requireContext(), "Confirm pin doesn't match.", Toast.LENGTH_SHORT).show();
            }
        }

        return allOkay;
    }

    @Override
    public void onResponse(PatientData patientResult, String token) {
        PatientDataCache.setPatientData(patientResult);

        progressDialog.setMessage("Almost there...");

        AppUtil.savePatientData(token, patientResult.patientId, requireContext(), true);

        progressDialog.dismiss();

        Navigation.findNavController(binding.getRoot()).navigate(R.id.action_createPinFragment_to_thankYouFragment);
    }

    @Override
    public void onFailure(Throwable t, @NonNull String message, int error_code) {
        Log.d(TAG, "onFailure: " + t);

        progressDialog.dismiss();

        AppUtil.showAlert(requireContext(),
                "Something went wrong",
                message, "OK", (dialog, which) -> {
                    dialog.dismiss();
                }, null, null);
    }
}
