package com.example.quiz.utils;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelStoreOwner;

import com.example.quiz.R;
import com.example.quiz.data.model.dtos.auth.LoginPayload;
import com.example.quiz.data.model.dtos.auth.LoginResponse;
import com.example.quiz.data.remote.TokenManager;
import com.example.quiz.viewModel.LoginViewModel;
import com.example.quiz.viewModel.LogsViewModel;

import javax.inject.Inject;

public class AuthNavigator {
    private final Context context;

    private FragmentManager fragmentManager;

    private final SessionManager sessionManager;
    private LoginViewModel viewModel;
    private LogsViewModel logsViewModel;
    private LifecycleOwner lifecycleOwner;


    private Dialog dialog;

    SharedPrefsHelper prefsHelper;



    public AuthNavigator(Context context,
                         FragmentManager fragmentManager,
                         SessionManager sessionManager,
                         LoginViewModel viewModel,
                         LogsViewModel logsViewModel,
                         LifecycleOwner lifecycleOwner) {
        this.viewModel = viewModel;
        this.logsViewModel = logsViewModel;
        this.prefsHelper = SharedPrefsHelper.getInstance(context);
        this.fragmentManager = fragmentManager;
        this.context = context;
        dialog = new Dialog(context);
        this.sessionManager = sessionManager;
        this.lifecycleOwner = lifecycleOwner;
    }

    public void navigate(Fragment destinationFragment) {
        if(destinationFragment== null){
            return;
        }
        if (sessionManager.isExpired()) {
            if(!dialogIsShowing()){
                showPinDialog(() -> {
                    sessionManager.updateLastExpiredDate();
                    fragmentManager.beginTransaction()
                            .replace(R.id.nav_host_fragment_content_main, destinationFragment)
                            .addToBackStack(null)
                            .commit();
                });
            }
        } else {
            fragmentManager.beginTransaction()
                    .replace(R.id.nav_host_fragment_content_main, destinationFragment)
                    .addToBackStack(null)
                    .commit();
        }
    }

    public void showPinDialog(Runnable onSuccess) {

        View view = LayoutInflater.from(context).inflate(R.layout.pin_view, null);

        dialog.setContentView(view);
        dialog.setCancelable(true);

        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        view.findViewById(R.id.cancel).setOnClickListener(v -> dialog.dismiss());
        view.findViewById(R.id.pin_validate)
                .setOnClickListener(v -> {
                    TextView code = view.findViewById(R.id.code);
                    TextView pin = view.findViewById(R.id.pin);
                    if(code.getText().toString().isEmpty()){
                        pin.setError("Entrez le code!");
                        return;
                    }
                    if(pin.getText().toString().isEmpty()){
                        pin.setError("Entrez le pin!");
                        return;
                    }
                    if(pin.getText().toString().length() < 4){
                        pin.setError("Le pin doit contenir minimum quatre chiffres!");
                        return;
                    }
                    if(prefsHelper== null || prefsHelper.get("terminalId") == null){
                        MessageDialog.showError(context, "Terminal non trouvé");
                        return;
                    }
                    LoginPayload loginPayload = new LoginPayload(
                            code.getText().toString(),
                            pin.getText().toString(),
                            Long.valueOf(prefsHelper.get("terminalId"))
                    );
                    viewModel.login(loginPayload).observe(lifecycleOwner, new Observer<Result<LoginResponse>>() {
                        @Override
                        public void onChanged(Result<LoginResponse> loginResponseResult) {
                            switch (loginResponseResult.status){
                                case LOADING:
                                    view.findViewById(R.id.pin_validate).setEnabled(false);
                                    view.findViewById(R.id.pin_validate).setAlpha(0.5f);
                                    break;
                                case ERROR:
                                    MessageDialog.showError(context, loginResponseResult.message);
                                    view.findViewById(R.id.pin_validate).setEnabled(true);
                                    view.findViewById(R.id.pin_validate).setAlpha(1f);
                                    break;
                                case SUCCESS:
                                    loginSuccess(loginResponseResult.data);
                                    logsViewModel.insertLog(prefsHelper.get("id"), "LOGIN","Authentification sur l'appareil", System.currentTimeMillis());
                                    sessionManager.updateLastExpiredDate();
                                    dialog.dismiss();
                                    view.findViewById(R.id.pin_validate).setEnabled(true);
                                    view.findViewById(R.id.pin_validate).setAlpha(1f);
                                    onSuccess.run();
                                    break;
                            }
                        }
                    });
                });
        dialog.show();
    }

    public boolean dialogIsShowing(){
        return dialog.isShowing();
    }

    public boolean isSessionExpired(){
        return sessionManager.isExpired();
    }


    public void updatedLastExpiredDate(){
        sessionManager.updateLastExpiredDate();
    }

    private void loginSuccess(LoginResponse loginResponse){
        String terminalId = prefsHelper.get("terminalId");
        if(terminalId == null){
            MessageDialog.showError(context, "Terminal non trouvé");
            return;
        }
        prefsHelper.save("id", String.valueOf(loginResponse.getUser().getId()));
        prefsHelper.save("firstName", loginResponse.getUser().getPrenom());
        prefsHelper.save("lastName", loginResponse.getUser().getNom());
        prefsHelper.save("profile", loginResponse.getUser().getFonction());
        prefsHelper.save("code", loginResponse.getUser().getCode());
        String isSupAgent = loginResponse.getUser().isSubAgent() ? "true" : "false";
        prefsHelper.save("isSupAgent", isSupAgent);
    }

    public void logOut (){
        prefsHelper.save("id", null);
        prefsHelper.save("firstName", null);
        prefsHelper.save("lastName", null);
        prefsHelper.save("profile", null);
        prefsHelper.save("code", null);
        prefsHelper.save("isSupAgent", null);
        sessionManager.setToExpire();
    }

}
