package com.dowerx.quack.activity;

import android.os.Bundle;
import android.view.MenuItem;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.fragment.app.Fragment;

import com.dowerx.quack.fragment.FeedFragment;
import com.dowerx.quack.fragment.NewPostFragment;
import com.dowerx.quack.fragment.ProfileFragment;
import com.dowerx.quack.R;
import com.dowerx.quack.fragment.SearchFragment;
import com.google.android.material.navigation.NavigationBarView;

public class SwitcherActivity extends AppCompatActivity implements NavigationBarView.OnItemSelectedListener, NavigationBarView.OnItemReselectedListener {

    private String userId = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_switcher);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        ((NavigationBarView)findViewById(R.id.bottom_nav_bar)).setOnItemSelectedListener(this);
        ((NavigationBarView)findViewById(R.id.bottom_nav_bar)).setOnItemReselectedListener(this);

        loadFragment(new FeedFragment());
    }

    @Override
    public void onNavigationItemReselected(@NonNull MenuItem menuItem) {
        this.userId = "";
        this.onNavigationItemSelected(menuItem);
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
        if (menuItem.getItemId() == R.id.nav_feed) {
            loadFragment(new FeedFragment());
        } else if (menuItem.getItemId() == R.id.nav_search) {
            loadFragment(new SearchFragment());
        } else if (menuItem.getItemId() == R.id.nav_post) {
            loadFragment(new NewPostFragment());
        } else if (menuItem.getItemId() == R.id.nav_profile) {
            loadFragment(ProfileFragment.newInstance(userId));
        }
        return true;
    }

    private void loadFragment(Fragment fragment) {
        if (fragment != null) {
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.main_fragment_holder, fragment)
                    .commit();
        }
    }

    public void setUser(String id) {
        this.userId = id;
    }
}