package com.kbs.kbsintranett;

import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.navigation.NavController;
import androidx.navigation.fragment.NavHostFragment;
import androidx.navigation.ui.NavigationUI;

import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.material.bottomnavigation.BottomNavigationView;

public class MainActivity extends AppCompatActivity {

    public static final String GOOGLE_WEB_CLIENT_ID = BuildConfig.WEB_CLIENT_ID;

    private static final String TAG = "MainActivity";
    private NavController navController;
    private BottomNavigationView bottomNav;

    private ActivityResultLauncher<String> requestPermissionLauncher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // --- 1. SETUP UI & NAVIGASJON ---
        bottomNav = findViewById(R.id.bottom_nav_view);

        NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager()
                .findFragmentById(R.id.nav_host_fragment);

        if (navHostFragment != null) {
            navController = navHostFragment.getNavController();
            if (bottomNav != null) {
                NavigationUI.setupWithNavController(bottomNav, navController);

                // Håndter "Reselection" (Klikk på fanen man allerede er i)
                bottomNav.setOnItemReselectedListener(item -> {
                    navController.popBackStack(item.getItemId(), false);
                });
            }

            // Skjul meny på login-skjerm
            navController.addOnDestinationChangedListener((controller, destination, arguments) -> {
                if (bottomNav == null) return;

                if (destination.getId() == R.id.navigation_login) {
                    bottomNav.setVisibility(View.GONE);
                } else {
                    bottomNav.setVisibility(View.VISIBLE);
                }
            });
        }

        // --- 2. VARSLINGSOPPSETT ---
        createNotificationChannel();

        requestPermissionLauncher = registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
            if (isGranted) {
                Log.d(TAG, "Varslingstillatelse gitt!");
            } else {
                Log.e(TAG, "Varslingstillatelse avslått.");
            }
        });

        checkNotificationPermission();
        checkExactAlarmPermission();

        // GAMMEL METODE FJERNET HERFRA (NotificationWorker)

        // --- 3. AUTENTISERING ---
        checkLoginState();
    }

    private void checkLoginState() {
        GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
        if (account == null) {
            navigateToLogin();
        } else {
            refreshGoogleToken();
        }
    }

    private void refreshGoogleToken() {
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(GOOGLE_WEB_CLIENT_ID)
                .requestEmail()
                .build();
        GoogleSignInClient client = GoogleSignIn.getClient(this, gso);

        client.silentSignIn()
                .addOnSuccessListener(account -> {
                    String photoUrl = (account.getPhotoUrl() != null) ? account.getPhotoUrl().toString() : null;

                    AuthRepository.loginToWordPress(
                            account.getIdToken(),
                            account.getDisplayName(),
                            account.getEmail(),
                            photoUrl,
                            new AuthRepository.AuthCallback() {
                                @Override
                                public void onSuccess(String role) {
                                    Log.d(TAG, "Silent login fullført. Rolle: " + role);
                                    if (navController != null && navController.getCurrentDestination() != null &&
                                            navController.getCurrentDestination().getId() == R.id.navigation_login) {
                                        navController.navigate(R.id.action_login_to_home);
                                    }
                                }

                                @Override
                                public void onError(String message) {
                                    Log.e(TAG, "Silent login feilet mot WP: " + message);
                                    navigateToLogin();
                                }
                            }
                    );
                })
                .addOnFailureListener(e -> {
                    Log.e(TAG, "Silent Sign-In feilet mot Google", e);
                    navigateToLogin();
                });
    }

    private void navigateToLogin() {
        if (navController != null) {
            if (navController.getCurrentDestination() != null &&
                    navController.getCurrentDestination().getId() != R.id.navigation_login) {
                navController.navigate(R.id.navigation_login);
            }
        }
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = "KBS Kalendervarsler";
            String description = "Varsler for kalenderhendelser";
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel channel = new NotificationChannel("kbs_calendar_channel", name, importance);
            channel.setDescription(description);
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            if (notificationManager != null) {
                notificationManager.createNotificationChannel(channel);
            }
        }
    }

    private void checkNotificationPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
                requestPermissionLauncher.launch(android.Manifest.permission.POST_NOTIFICATIONS);
            }
        }
    }

    private void checkExactAlarmPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            if (alarmManager != null && !alarmManager.canScheduleExactAlarms()) {
                new AlertDialog.Builder(this)
                        .setTitle("Varslingstillatelse kreves")
                        .setMessage("For at kalenderen skal kunne varsle deg nøyaktig når et møte starter, må du gi appen tilgang til å sette alarmer.")
                        .setPositiveButton("Gå til Innstillinger", (dialog, which) -> {
                            Intent intent = new Intent(Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM);
                            intent.setData(Uri.parse("package:" + getPackageName()));
                            startActivity(intent);
                        })
                        .setNegativeButton("Senere", null)
                        .show();
            }
        }
    }
}