package com.example.petstoremobile.activities;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;

import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.navigation.NavController;
import androidx.navigation.fragment.NavHostFragment;
import androidx.navigation.ui.NavigationUI;

import com.example.petstoremobile.R;
import com.example.petstoremobile.databinding.ActivityHomeBinding;
import com.example.petstoremobile.services.ChatNotificationService;

import dagger.hilt.android.AndroidEntryPoint;

@AndroidEntryPoint
public class HomeActivity extends AppCompatActivity {
    private ActivityHomeBinding binding;
    private NavController navController;

    // Launcher to ask for notification permission
    private final ActivityResultLauncher<String> requestPermissionLauncher =
            registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
                if (!isGranted) {
                    Log.w("HomeActivity", "Notification permission denied");
                }
            });

    /**
     * Sets up the home screen, initializes bottom navigation, and handles incoming navigation intents.
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        EdgeToEdge.enable(this);
        super.onCreate(savedInstanceState);
        binding = ActivityHomeBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        ViewCompat.setOnApplyWindowInsetsListener(binding.main, (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        // Initialize Navigation Component
        NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager()
                .findFragmentById(R.id.nav_host_fragment);
        if (navHostFragment != null) {
            navController = navHostFragment.getNavController();
            NavigationUI.setupWithNavController(binding.bottomNavigation, navController);
        }

        //load the list fragment by default if it's a fresh start
        if (savedInstanceState == null) {
            handleIntent(getIntent());
        }

        // Start the notification service and request for notification permission
        startNotificationService();
        requestNotificationPermission();
    }
    
    /**
     * Handles new intents received while the activity is already running (like notifications).
     */
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent); // Set the new intent so fragments can access updated extras
        handleIntent(intent);
    }

    /**
     * Processes the intent to determine if specific navigation (like opening a chat) is required.
     */
    private void handleIntent(Intent intent) {
        if (intent != null && "chat".equals(intent.getStringExtra("navigate_to"))) {
            if (binding.bottomNavigation != null) {
                // Navigate by selecting the bottom nav item.
                binding.bottomNavigation.setSelectedItemId(R.id.nav_chat);
            }
        }
    }

    /**
     * Starts the background service responsible for monitoring chat notifications.
     */
    private void startNotificationService() {
        Intent serviceIntent = new Intent(this, ChatNotificationService.class);
        startService(serviceIntent);
    }

    /**
     * Requests POST_NOTIFICATIONS permission from the user if running on Android 13 and above.
     */
    private void requestNotificationPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
                requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS);
            }
        }
    }
}
