package com.app.simplitend.welcome.welcomecg.fragments;

import static com.app.simplitend.welcome.welcomecg.fragments.CgCheckEmailFragment.FORGOT_EMAIL;

import android.app.ProgressDialog;
import android.os.Bundle;
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.databinding.CgChangePasswordFragmentBinding;
import com.app.simplitend.welcome.welcomecg.WelcomeContracts;
import com.app.simplitend.welcome.welcomecg.mvvm.CareGiverData;
import com.app.simplitend.welcome.welcomecg.mvvm.CgWelcomeViewModel;

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

import okhttp3.MediaType;
import okhttp3.RequestBody;

public class CgChangePwdFragment extends Fragment implements WelcomeContracts.ChangePasswordCallback {

    protected CgChangePasswordFragmentBinding binding;

    private ProgressDialog progressDialog;

    private CgWelcomeViewModel viewModel;

    private String eEmail;

    public CgChangePwdFragment() {
        // required
    }

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

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

        progressDialog = new ProgressDialog(requireContext());

        clickEvents();

        return binding.getRoot();
    }

    private void clickEvents() {
        binding.backBtn.setOnClickListener(view -> {
            requireActivity().onBackPressed();
        });

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

    private void changePassword() {
        if (eEmail == null ||
                binding.password.getText() == null ||
                binding.confirmPassword.getText() == null) {
            Toast.makeText(requireContext(), "Something goes wrong, Try again.", Toast.LENGTH_SHORT).show();
            return;
        }

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

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

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

        RequestBody password_body = RequestBody.create(binding.password.getText().toString(), MediaType.parse("text/plain"));
        body.put("password", password_body);

        RequestBody c_password_body = RequestBody.create(binding.confirmPassword.getText().toString(), MediaType.parse("text/plain"));
        body.put("c_password", c_password_body);

        viewModel.changeCgPassword(body, this);

    }

    private boolean allOkay() {
        boolean allOkay = true;

        if (binding.password.getText() != null && binding.confirmPassword.getText() != null) {
            String password = binding.password.getText().toString();

            if (password.length() < 8) {
                allOkay = false;
                Toast.makeText(requireContext(), "Password must be at least 8 characters.", Toast.LENGTH_SHORT).show();
            } else if (password.contains(" ")) {
                allOkay = false;
                Toast.makeText(requireContext(), "Password should not contains white spaces.", Toast.LENGTH_SHORT).show();
            } else if (!password.matches("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[^a-zA-Z0-9]).{8,}$")) {
                allOkay = false;
                Toast.makeText(requireContext(), "Password doesn't match the required criteria.", Toast.LENGTH_SHORT).show();
            } else if (binding.confirmPassword.getText().toString().isEmpty()){
                allOkay = false;
                Toast.makeText(requireContext(), "Please confirm your password.", Toast.LENGTH_SHORT).show();
            } else if (!binding.confirmPassword.getText().toString().equals(password)) {
                allOkay = false;
                Toast.makeText(requireContext(), "Confirm password doesn't match.", Toast.LENGTH_SHORT).show();
            }
        }

        return allOkay;
    }

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

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

        eEmail = bundle.getString(FORGOT_EMAIL);
    }

    @Override
    public void onPasswordChanged(CareGiverData careGiverData) {
        progressDialog.dismiss();

        Toast.makeText(requireContext(), "Password changed successfully.", Toast.LENGTH_SHORT).show();
        Navigation.findNavController(binding.getRoot())
                .popBackStack(R.id.cgSignInFragment, false);
    }

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

        Toast.makeText(requireContext(), "" + message, Toast.LENGTH_SHORT).show();
    }
}
