package com.example.quiz;
import android.graphics.Color;
import android.os.Bundle;

import com.anggastudio.printama.Pref;
import com.anggastudio.printama.Printama;
import com.example.quiz.utils.AuthNavigator;
import com.example.quiz.utils.BluetoothUtils;
import com.example.quiz.utils.MessageDialog;
import com.example.quiz.utils.SessionManager;
import com.example.quiz.viewModel.LoginViewModel;
import com.example.quiz.viewModel.LogsViewModel;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Handler;
import android.os.Looper;

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 javax.inject.Inject;

import dagger.hilt.android.AndroidEntryPoint;

@AndroidEntryPoint
public class PageQuiz extends AppCompatActivity {

    LoginViewModel viewModel;

    LogsViewModel logsViewModel;

    AuthNavigator authNavigator;
    private SessionManager sessionManager;

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

    private AppBarConfiguration appBarConfiguration;
    private ActivityPageQuizBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sessionManager = SessionManager.newInstance(this);
        binding = ActivityPageQuizBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        logsViewModel = new ViewModelProvider(this).get(LogsViewModel.class);
        viewModel = new ViewModelProvider(this).get(LoginViewModel.class);
        authNavigator = new AuthNavigator(this, getSupportFragmentManager(), sessionManager, viewModel, logsViewModel, this);
        setSupportActionBar(binding.toolbar);
        binding.toolbar.setBackgroundColor(Color.parseColor("#501C5A29"));
    }

//    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(true);
//
//        dialog = builder.create();
//        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
//
//        view.findViewById(R.id.cancel).setOnClickListener(v -> dialog.dismiss());
//// 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() < 4){
//                pin.setError("Le pin doit contenir minimum quatre 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:
//                            view.findViewById(R.id.pin_validate).setEnabled(false);
//                            view.findViewById(R.id.pin_validate).setAlpha(0.5f);
//                            break;
//                        case ERROR:
//                            Toast.makeText(getApplicationContext(), loginResponseResult.message, Toast.LENGTH_SHORT).show();
//                            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);
//                            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());
//    }


    private void checkPermission(){
        Pref.init(this);
        if (BluetoothUtils.needsBluetoothPermissions()) {
            if (!BluetoothUtils.hasBluetoothPermission(this)) {
                // Demande la permission si non accordée
                BluetoothUtils.requestBluetoothPermission(this);
                return; // arrête ici, la popup va apparaître
            }
        }

        // 2️⃣ Permission OK, on peut afficher la liste
        try {
            Printama printama = Printama.with(this);
            if(printama.getConnectedPrinter() == null){
                BluetoothUtils.showPrinterList(this, this);
            }
        } catch (SecurityException e) {
            MessageDialog.showError(this, "Permission refusée");
        }
    }

    @Override
    protected void onResume() {
        checkPermission();
        super.onResume();
        handler = new Handler(Looper.getMainLooper());
        checkRunnable = new Runnable() {
            @Override
            public void run() {
                if (sessionManager.isExpired()) {
                    if (!authNavigator.dialogIsShowing()) {
                        authNavigator.showPinDialog(() -> {
                            sessionManager.updateLastExpiredDate();
                            handler.postDelayed(checkRunnable, 1);
                        });
                    }
                } else {
                    // Replanifie le check toutes les secondes
                    handler.postDelayed(this, 1);
                }
            }
        };

        handler.postDelayed(checkRunnable, 1);
    }

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