package com.example.quiz;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;

import com.example.quiz.data.model.dtos.auth.LoginPayload;
import com.example.quiz.data.model.dtos.auth.LoginResponse;
import com.example.quiz.utils.Result;
import com.example.quiz.utils.SessionManager;
import com.example.quiz.utils.SharedPrefsHelper;
import com.example.quiz.viewModel.LoginViewModel;
import com.google.android.material.snackbar.Snackbar;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Handler;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.example.quiz.databinding.ActivityPageQuizBinding;

import dagger.hilt.android.AndroidEntryPoint;

@AndroidEntryPoint
public class PageQuiz extends AppCompatActivity {

    LoginViewModel viewModel;
    private SessionManager sessionManager;

    private AlertDialog dialog;
    private Handler handler = new Handler();
    private Runnable checkRunnable;

    private AppBarConfiguration appBarConfiguration;
    private ActivityPageQuizBinding binding;

    private SharedPrefsHelper prefsHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityPageQuizBinding.inflate(getLayoutInflater());
        _showPinDialog();
        setContentView(binding.getRoot());
        sessionManager = new SessionManager();
        prefsHelper = SharedPrefsHelper.getInstance(getApplicationContext());
        viewModel = new ViewModelProvider(this).get(LoginViewModel.class);
        setSupportActionBar(binding.toolbar);
        binding.toolbar.setBackgroundColor(Color.parseColor("#501C5A29"));
        binding.fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAnchorView(R.id.fab)
                        .setAction("Action", null).show();
            }
        });
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {

        if (dialog != null && dialog.isShowing()) {
            return super.dispatchTouchEvent(ev);
        }


        if(sessionManager.isExpired()){
            _showPinDialog();
            return true;
        }
        sessionManager.updateLastExpiredDate();
        return super.dispatchTouchEvent(ev);
    }

    void _showPinDialog(){
        LayoutInflater inflater = getLayoutInflater();
        View view = inflater.inflate(R.layout.pin_view, null);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(view);
        builder.setCancelable(false);

        dialog = builder.create();
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

// Bouton OK
        view.findViewById(R.id.pin_validate).setOnClickListener(v -> {
            TextView pin = view.findViewById(R.id.pin);
            if(pin.getText().toString().isEmpty()){
                pin.setError("Entrez le pin!");
                return;
            }
            if(pin.getText().toString().length() != 5){
                pin.setError("Le pin doit contenir 5 chiffres!");
                return;
            }
            LoginPayload loginPayload = new LoginPayload(
                    pin.getText().toString()
            );
            viewModel.login(loginPayload).observe(this, new Observer<Result<LoginResponse>>() {
                @Override
                public void onChanged(Result<LoginResponse> loginResponseResult) {
                    switch (loginResponseResult.status){
                        case LOADING:
                            Toast.makeText(getApplicationContext(), "Loading",Toast.LENGTH_SHORT).show();
                            break;
                        case ERROR:
                            pin.setError("Pin incorrect");
                            break;
                        case SUCCESS:
                            loginSuccess(loginResponseResult.data);
                            sessionManager.updateLastExpiredDate();
                            dialog.dismiss();
                            break;
                    }
                }
            });
        });

        dialog.show();
    }


    private void loginSuccess(LoginResponse loginResponse){
        prefsHelper.save("id", String.valueOf(loginResponse.getId()));
        prefsHelper.save("firstName", loginResponse.getPrenom());
        prefsHelper.save("lastName", loginResponse.getNom());
        prefsHelper.save("profile", loginResponse.getProfile());
        prefsHelper.save("limit", String.valueOf(loginResponse.getLimiteSuperieure()));
        prefsHelper.save("code", loginResponse.getCode());
    }

    @Override
    protected void onResume() {
        super.onResume();
        handler = new Handler();
        checkRunnable = new Runnable() {
            @Override
            public void run() {
                if (sessionManager.isExpired()) {
                    if(dialog != null && !dialog.isShowing()){
                        _showPinDialog();
                    }
                } else {
                    handler.postDelayed(this, 10); // check every second
                }
            }
        };
        handler.postDelayed(checkRunnable, 10);
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_page_quiz);
        return NavigationUI.navigateUp(navController, appBarConfiguration)
                || super.onSupportNavigateUp();
    }
}