package com.app.simplitend.caregiverdashboard.activities;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.app.simplitend.R;
import com.app.simplitend.apputils.AppUtil;
import com.app.simplitend.apputils.CaregiverDataCache;
import com.app.simplitend.caregiverdashboard.mvvm.CaregiverMainViewModel;
import com.app.simplitend.caregiverdashboard.mvvm.CgHomeContracts;
import com.app.simplitend.databinding.CgChangePasswordFragmentBinding;
import com.app.simplitend.welcome.welcomecg.mvvm.CareGiverData;

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

import okhttp3.MediaType;
import okhttp3.RequestBody;

public class CgChangePwdActivity extends AppCompatActivity implements CgHomeContracts.UpdateCgPasswordCallback {

    private CgChangePasswordFragmentBinding binding;

    private CaregiverMainViewModel viewModel;
    private ProgressDialog progressDialog;

    private CareGiverData careGiverData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = CgChangePasswordFragmentBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        viewModel = new ViewModelProvider(this).get(CaregiverMainViewModel.class);
        progressDialog = new ProgressDialog(this);

        // viewing old pwd view
        binding.oldPwdTitle.setVisibility(View.VISIBLE);
        binding.oldPwdView.setVisibility(View.VISIBLE);
        binding.subTitle.setText(R.string.when_updating_a_password_it_s_essential_to_create_a_strong_unique_password);
        
        initViews();
        
        clickEvents();

        CaregiverDataCache.getCaregiverData(this, (careGiverData1 -> {
            this.careGiverData = careGiverData1;
        }), true);

    }

    @Override
    protected void attachBaseContext(Context newBase) {
        final Configuration configuration = new Configuration(newBase.getResources().getConfiguration());
        configuration.fontScale = Math.min(configuration.fontScale, 1.1f);
        applyOverrideConfiguration(configuration);
        super.attachBaseContext(newBase);
    }

    private void initViews() {
        
    }

    private void clickEvents() {
        binding.resetPin.setOnClickListener(v -> {
            if (careGiverData == null){
                Toast.makeText(this, "Couldn't load data", Toast.LENGTH_SHORT).show();
                return;
            }

            if (allOkay()){
                AppUtil.closeKeyboard(this);

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

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

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

                    RequestBody old_password_body = RequestBody.create(Objects.requireNonNull(binding.oldPassword.getText()).toString(), MediaType.parse("text/plain"));
                    body.put("old_password", old_password_body);

                    viewModel.updateCgPassword(careGiverData.caregiver_xid,
                            body, "Bearer " + AppUtil.getCgToken(this),
                            this);

                }catch (Exception e){
                    Toast.makeText(this, "Please try again later.", Toast.LENGTH_SHORT).show();
                }

            }
        });

        binding.backBtn.setOnClickListener(view -> onBackPressed());
    }

    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(this, "Password must be at least 8 characters.", Toast.LENGTH_SHORT).show();
            } else if (password.contains(" ")) {
                allOkay = false;
                Toast.makeText(this, "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(this, "Password doesn't match the required criteria.", Toast.LENGTH_SHORT).show();
            } else if (binding.confirmPassword.getText().toString().isEmpty()){
                allOkay = false;
                Toast.makeText(this, "Please confirm your password.", Toast.LENGTH_SHORT).show();
            } else if (!binding.confirmPassword.getText().toString().equals(password)) {
                allOkay = false;
                Toast.makeText(this, "Confirm password doesn't match.", Toast.LENGTH_SHORT).show();
            }

            if (allOkay && binding.oldPassword.getText() != null){
                String old_password = binding.oldPassword.getText().toString();
                if (old_password.trim().isEmpty()){
                    allOkay = false;
                    Toast.makeText(this, "Old password cannot be empty.", Toast.LENGTH_SHORT).show();
                }else if (old_password.equals(password)){
                    allOkay = false;
                    Toast.makeText(this, "New password cannot be same as old password.", Toast.LENGTH_SHORT).show();
                }
            }
        }

        return allOkay;
    }

    @Override
    public void onPasswordUpdated(@NonNull CareGiverData patientData) {
        progressDialog.dismiss();
        Toast.makeText(this, "Password updated successfully.", Toast.LENGTH_SHORT).show();
        finish();
    }

    @Override
    public void onPasswordUpdateFailed(Throwable throwable, String message) {
        progressDialog.dismiss();
        AppUtil.showAlert(this,
                getString(R.string.something_went_wrong),
                message,
                getString(R.string.ok),
                ((dialogInterface, i) -> {}),
                null, null);
    }
}