package com.example.quiz;
import android.graphics.Color;
import android.os.Build;
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.utils.SunmiPrinterManager;
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 android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
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 java.util.HashSet;
import java.util.Set;

import javax.inject.Inject;

import dagger.hilt.android.AndroidEntryPoint;

@AndroidEntryPoint
public class PageQuiz extends AppCompatActivity {

    LoginViewModel viewModel;

    LogsViewModel logsViewModel;

    AuthNavigator authNavigator;
    private SessionManager sessionManager;

    String mobileName;


    private Set<Class<?>> exemptedFragment = new HashSet<>();

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

    private AppBarConfiguration appBarConfiguration;
    private ActivityPageQuizBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        exemptedFragment.add(ServerConfig.class);
        exemptedFragment.add(Logs.class);
        exemptedFragment.add(ApiUrlConfiguration.class);
        sessionManager = SessionManager.newInstance(this);
        mobileName = Build.MANUFACTURER;
        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());
//    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        View touchedView = findTouchedView(ev);
        Fragment currentFragment = getCurrentFragment();
        if(currentFragment != null && exemptedFragment.contains(currentFragment.getClass())){
            return super.dispatchTouchEvent(ev);
        }
        if(touchedView!=null && "tag_pin_exempt".equals(touchedView.getTag())){
            return super.dispatchTouchEvent(ev);
        }
        if (authNavigator.isSessionExpired()) {
            authNavigator.showPinDialog(() -> {
                authNavigator.updatedLastExpiredDate();
            });
            return false; // Consomme l'événement pour ne pas le propager
        }
        authNavigator.updatedLastExpiredDate();
        return super.dispatchTouchEvent(ev);
    }

    private Fragment getCurrentFragment() {
        FragmentManager fm = getSupportFragmentManager();
        // Méthode 1: Par conteneur
        Fragment fragment = fm.findFragmentById(R.id.nav_host_fragment_content_main);

        // Méthode 2: Par tag si vous utilisez des tags
        if (fragment == null) {
            fragment = fm.findFragmentByTag("current_fragment");
        }

        return fragment;
    }

    private View findTouchedView(MotionEvent ev) {
        float x = ev.getRawX();
        float y = ev.getRawY();

        View rootView = getWindow().getDecorView().getRootView();
        return findViewAtPosition(rootView, (int) x, (int) y);
    }

    private View findViewAtPosition(View view, int x, int y) {
        if (view == null) return null;

        int[] location = new int[2];
        view.getLocationOnScreen(location);

        int left = location[0];
        int top = location[1];
        int right = left + view.getWidth();
        int bottom = top + view.getHeight();

        if (x >= left && x <= right && y >= top && y <= bottom) {
            if (view instanceof ViewGroup) {
                ViewGroup group = (ViewGroup) view;
                for (int i = group.getChildCount() - 1; i >= 0; i--) {
                    View child = group.getChildAt(i);
                    View found = findViewAtPosition(child, x, y);
                    if (found != null) return found;
                }
            }
            return view;
        }
        return null;
    }

    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() {
//        if(!mobileName.toLowerCase().contains("sunmi")){
//            checkPermission();
//        }
        super.onResume();
        handler = new Handler(Looper.getMainLooper());
        checkRunnable = new Runnable() {
            @Override
            public void run() {
                if (sessionManager.isExpired()) {
                    if (!authNavigator.dialogIsShowing()) {
                        authNavigator.showPinDialog(() -> {
                            authNavigator.updatedLastExpiredDate();
                            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();
    }
}