package com.example.gallery;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.gallery.adapters.PostsAdapter;
import com.example.gallery.api.ApiClient;
import com.example.gallery.api.ApiService;
import com.example.gallery.models.Publication;
import com.example.gallery.models.PublicationListResponse;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {

    private Button loginBtn, registerBtn, logoutBtn, newPostBtn;
    private RecyclerView recyclerView;
    private PostsAdapter postsAdapter;
    private ImageButton burgerMenuBtn;
    private LinearLayout dropdownMenu;
    private TextView menuLogout, menuNewPost;
    private ImageButton filterBtnToolbar;

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

        loginBtn = findViewById(R.id.Loginbtn);
        registerBtn = findViewById(R.id.Registerbtn);
        logoutBtn = findViewById(R.id.btnLogout);
        newPostBtn = findViewById(R.id.newPostBtn);
        recyclerView = findViewById(R.id.postsRecyclerView);
        burgerMenuBtn = findViewById(R.id.burgerMenuBtn);
        dropdownMenu = findViewById(R.id.dropdownMenu);
        menuLogout = findViewById(R.id.menuLogout);
        menuNewPost = findViewById(R.id.menuNewPost);
        filterBtnToolbar = findViewById(R.id.filterBtnToolbar);

        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        boolean isLoggedIn = getSharedPreferences("MyAppPrefs", MODE_PRIVATE)
                .getBoolean("isLoggedIn", false);

        postsAdapter = new PostsAdapter(this, new ArrayList<>(), isLoggedIn);
        recyclerView.setAdapter(postsAdapter);

        setupButtons();
        setupDropdownMenu();
        updateAuthUI();
        loadPublications();
        setupFilterButton();
    }

    private void setupButtons() {
        loginBtn.setOnClickListener(v ->
                startActivity(new Intent(this, LoginActivity.class)));

        registerBtn.setOnClickListener(v ->
                startActivity(new Intent(this, RegisterActivity.class)));

        logoutBtn.setOnClickListener(v -> {
            getSharedPreferences("MyAppPrefs", MODE_PRIVATE)
                    .edit().clear().apply();
            updateAuthUI();
            Toast.makeText(this, "Logged out", Toast.LENGTH_SHORT).show();
        });

        newPostBtn.setOnClickListener(v ->
                startActivityForResult(
                        new Intent(this, NewPostActivity.class), 100));
    }
    private void setupDropdownMenu() {
        burgerMenuBtn.setOnClickListener(v ->
                dropdownMenu.setVisibility(
                        dropdownMenu.getVisibility() == View.VISIBLE
                                ? View.GONE : View.VISIBLE));

        menuLogout.setOnClickListener(v -> {
            getSharedPreferences("MyAppPrefs", MODE_PRIVATE)
                    .edit().clear().apply();
            updateAuthUI();
            dropdownMenu.setVisibility(View.GONE);
        });

        menuNewPost.setOnClickListener(v -> {
            startActivityForResult(
                    new Intent(this, NewPostActivity.class), 100);
            dropdownMenu.setVisibility(View.GONE);
        });
    }
    //Sortiranje i filtriranje.
    private void setupFilterButton() {

        filterBtnToolbar.setOnClickListener(v -> {

            String[] options = {
                    "Show all posts",
                    "Only pinned",
                    "Not pinned",
                    "Only images",
                    "Only videos",
                    "Sort by newest",
                    "Sort by rating"
            };
            new androidx.appcompat.app.AlertDialog.Builder(this)
                    .setTitle("Filter & Sort")
                    .setItems(options, (dialog, which) -> {

                        switch (which) {

                            case 0: //All.
                                postsAdapter.filterPinned(null);
                                postsAdapter.filterContentType(null);
                                break;

                            case 1: //Pinned.
                                postsAdapter.filterPinned(true);
                                break;

                            case 2: //Not pinned.
                                postsAdapter.filterPinned(false);
                                break;

                            case 3: // images
                                postsAdapter.filterContentType("image");
                                break;

                            case 4: // videos
                                postsAdapter.filterContentType("video");
                                break;

                            case 5: // newest
                                postsAdapter.sortBy(PostsAdapter.SortMode.TIME);
                                break;

                            case 6: // rating
                                postsAdapter.sortBy(PostsAdapter.SortMode.RATING);
                                break;
                        }
                    })
                    .show();
        });
    }
    private void updateAuthUI() {
        boolean isLoggedIn = getSharedPreferences("MyAppPrefs", MODE_PRIVATE)
                .getBoolean("isLoggedIn", false);

        loginBtn.setVisibility(isLoggedIn ? View.GONE : View.VISIBLE);
        registerBtn.setVisibility(isLoggedIn ? View.GONE : View.VISIBLE);
        logoutBtn.setVisibility(isLoggedIn ? View.VISIBLE : View.GONE);
        newPostBtn.setVisibility(isLoggedIn ? View.VISIBLE : View.GONE);
    }
    public void loadPublications() {
        ApiService api = ApiClient.getClient().create(ApiService.class);
        String token = getSharedPreferences("MyAppPrefs", MODE_PRIVATE)
                .getString("authToken", null);
        String authHeader = token != null ? "Token " + token : null;
        api.getPublications(authHeader).enqueue(new Callback<PublicationListResponse>() {
            @Override
            public void onResponse(Call<PublicationListResponse> call,
                                   Response<PublicationListResponse> response) {
                if (response.isSuccessful() && response.body() != null) {
                    List<Publication> publications = response.body().results;

                    // Pass the fully populated list to adapter
                    postsAdapter.setPosts(publications);
                } else {
                    Toast.makeText(MainActivity.this,
                            "Failed to load posts",
                            Toast.LENGTH_SHORT).show();
                }
            }
            @Override
            public void onFailure(Call<PublicationListResponse> call, Throwable t) {
                Toast.makeText(MainActivity.this,
                        "Network error",
                        Toast.LENGTH_SHORT).show();
            }
        });
    }
    @Override
    protected void onResume() {
        super.onResume();
        updateAuthUI();
        loadPublications();
    }
}