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

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.app.simplitend.R;
import com.app.simplitend.apputils.AppUtil;
import com.app.simplitend.apputils.EditTextErrorRemover;
import com.app.simplitend.databinding.ChangePinFragmentBinding;
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;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import okhttp3.MediaType;
import okhttp3.RequestBody;

public class ChangePinFragment extends Fragment implements WelcomeContracts.UpdatePinCallback {

    private static final String TAG = "ChangePinFragment";

    // view binding
    protected ChangePinFragmentBinding binding;

    private WelcomeViewModel viewModel;

    private ProgressDialog progressDialog;

    private String email_id;

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

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

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

        initViews();

        clickEvents();

        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        Bundle bundle = getArguments();

        if (bundle == null || bundle.getString(ForgotPinFragment.EMAIL_KEY) == null){
            Toast.makeText(requireContext(), "Something went wrong", Toast.LENGTH_SHORT).show();
            Navigation.findNavController(binding.getRoot()).popBackStack();
            return;
        }

        email_id = bundle.getString(ForgotPinFragment.EMAIL_KEY);

    }

    private void initViews() {
        progressDialog = new ProgressDialog(requireContext());
        
        new EditTextErrorRemover(
                binding.pin,
                binding.confirmPin
        );

        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 clickEvents() {

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

        binding.resetPin.setOnClickListener(v -> {
            if (allOkay()){

                progressDialog.setTitle("Please wait");
                progressDialog.setMessage("while we reset your pin.");
                progressDialog.setCancelable(false);
                progressDialog.show();

                try {
                    Map<String, RequestBody> body = new HashMap<>();

                    RequestBody pin_body = RequestBody.create(Objects.requireNonNull(binding.pin.getText()).toString().trim(), MediaType.parse("text/plain"));
                    body.put("pin", pin_body);

                    RequestBody c_pin_body = RequestBody.create(Objects.requireNonNull(binding.confirmPin.getText()).toString().trim(), MediaType.parse("text/plain"));
                    body.put("cpin", c_pin_body);

                    RequestBody email_body = RequestBody.create(Objects.requireNonNull(email_id), MediaType.parse("text/plain"));
                    body.put("email", email_body);

                    viewModel.updatePin(body, this);
                }catch (NullPointerException e){
                    Log.e(TAG, "clickEvents: ", e);
                    Toast.makeText(requireContext(), "Something went wrong", Toast.LENGTH_SHORT).show();
                }

            }
        });

    }

    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;
            Toast.makeText(requireContext(), "Confirm pin doesn't match.", Toast.LENGTH_SHORT).show();
        }

        return allOkay;
    }

    @Override
    public void onPinUpdated(PatientData patientData) {
        progressDialog.dismiss();

        Toast.makeText(requireContext(), "PIN changed successfully", Toast.LENGTH_SHORT).show();

        Navigation.findNavController(binding.getRoot())
                .popBackStack(R.id.signInFragment, false, true);
    }

    @Override
    public void onPinUpdateFailed(Throwable t, String message) {
        progressDialog.dismiss();

        AppUtil.showAlert(requireContext(),
                getString(R.string.something_went_wrong),
                message,
                getString(R.string.ok),
                ((dialog, which) -> {
                    dialog.dismiss();
                }), null, null);
    }
}
