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

import static com.app.simplitend.welcome.welcomecg.fragments.CgConnectFragment.CAREGIVER_EMAIL;
import static com.app.simplitend.welcome.welcomepatient.fragments.register.ReActivateFragment.CG_STATUS_KEY;
import static com.app.simplitend.welcome.welcomepatient.fragments.register.ReActivateFragment.CG_XID_KEY;
import static com.app.simplitend.welcome.welcomepatient.fragments.register.ReActivateFragment.IS_CAREGIVER_KEY;
import static com.app.simplitend.welcome.welcomepatient.fragments.register.ReActivateFragment.TOKEN_KEY;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Patterns;
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.NavOptions;
import androidx.navigation.Navigation;

import com.onesignal.OneSignal;
import com.app.simplitend.R;
import com.app.simplitend.apputils.AppUtil;
import com.app.simplitend.apputils.CaregiverDataCache;
import com.app.simplitend.caregiverdashboard.activities.CaregiverDashActivity;
import com.app.simplitend.caregiverdashboard.activities.deactivateacc.AccountPresenter;
import com.app.simplitend.databinding.CgSignInFragmentBinding;
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;

public class CgSignInFragment extends Fragment implements WelcomeContracts.CgLoginCallback {

    // view binding
    protected CgSignInFragmentBinding binding;

    private CgWelcomeViewModel viewModel;

    private ProgressDialog progressDialog;

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

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

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

        initViews();

        clickEvents();

        return binding.getRoot();
    }

    private void initViews() {
        progressDialog = new ProgressDialog(requireContext());
    }

    private void clickEvents() {
        binding.signInBtn.setOnClickListener(v -> {
            AppUtil.closeKeyboard(requireActivity());

            binding.email.setError(null);

            if (allOkay()){

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

                Map<String, String> body = new HashMap<>();
                body.put("email", binding.email.getText().toString());

                String password;
                if (binding.password.getText() == null) {
                    password = "";
                }
                else{
                    password = binding.password.getText().toString();
                }

                body.put("password", password);

                body.put("one_signal_player_id", OneSignal.getUser().getPushSubscription().getId());

                viewModel.loginCaregiver(body, this);
            }
        });

        binding.registerBtn.setOnClickListener(v -> {
            Navigation.findNavController(v).navigate(R.id.action_cgSignInFragment_to_cgHowToSetUpFragment);
        });

        binding.forgotPassword.setOnClickListener(v -> {
            Navigation.findNavController(v)
                    .navigate(R.id.action_cgSignInFragment_to_cgForgotPasswordFragment);
        });
    }

    private boolean allOkay() {
        boolean allOkay = true;
        
        if (binding.email.getText().toString().trim().isEmpty()){
            allOkay = false;
            binding.email.setError("Please enter email.");
        }else if (!Patterns.EMAIL_ADDRESS.matcher(binding.email.getText().toString()).matches()){
            allOkay = false;
            binding.email.setError("Invalid email");
        }
        
        if (binding.password.getText() != null && binding.password.getText().toString().trim().isEmpty()){
            allOkay = false;
            Toast.makeText(requireContext(), "Please enter password.", Toast.LENGTH_SHORT).show();
        }
        
        return allOkay;
    }

    private void gotoDashboard() {
        int cg_app_security = AppUtil.getWantSecurityFlag(requireContext());

        Intent intent;
        if (cg_app_security == AppUtil.CG_NO_SECURITY_NEEDED){
            // caregiver user has chosen to not use security
            intent = new Intent(requireActivity(), CaregiverDashActivity.class);

        }else{
            // caregiver user has asked to for security
            AppUtil.setCgRegistrationComplete(requireContext(), true);
            intent = new Intent(requireActivity(), CgAuthActivity.class);
        }

        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        requireActivity().finish();
    }

    private void gotoCgConnect(String email) {
        NavOptions navOptions = new NavOptions.Builder()
                .setPopUpTo(R.id.welcomeFragment, true)
                        .build();

        Bundle bundle = new Bundle();
        bundle.putString(CAREGIVER_EMAIL, email);

        // goto cg connect screen
        Navigation.findNavController(binding.getRoot())
                .navigate(R.id.action_cgSignInFragment_to_cgConnectFragment, bundle, navOptions);
    }

    private void gotoReActivateScreen(String cg_status, String token, int cg_xid){
        NavOptions navOptions = new NavOptions.Builder()
                .setPopUpTo(R.id.welcomeFragment, true)
                .build();

        Bundle bundle = new Bundle();

        bundle.putString(CG_STATUS_KEY, cg_status);
        bundle.putBoolean(IS_CAREGIVER_KEY, true);
        bundle.putInt(CG_XID_KEY, cg_xid);
        bundle.putString(TOKEN_KEY, token);

        Navigation.findNavController(binding.getRoot())
                .navigate(R.id.action_cgSignInFragment_to_reActivateFragment, bundle, navOptions);
    }

    @Override
    public void onLoginSuccess(CareGiverData careGiverData, String token) {
        // caching user data
        CaregiverDataCache.setCareGiverData(careGiverData);
        AppUtil.saveCgData(token, careGiverData.patientId, requireContext());
        progressDialog.dismiss();

        if (!careGiverData.caregiver_status.equals(AccountPresenter.ACC_ACTIVE_STR)){
            // account is not active

            gotoReActivateScreen(careGiverData.caregiver_status, AppUtil.getCgToken(requireContext()),
                    careGiverData.caregiver_xid);

            return;
        }

        Toast.makeText(requireContext(), "Log in success.", Toast.LENGTH_SHORT).show();

        if (careGiverData.isPatientAndCareGiverConnected == 1){
            gotoDashboard();
        }else{
            gotoCgConnect(careGiverData.email);
        }

    }

    @Override
    public void onLogInFailed(Throwable t, String message) {
        progressDialog.dismiss();
        Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show();
    }
}
