package com.example.gallery;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
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;

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

        // Initialize all views BEFORE using them
        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);

        // RecyclerView setup
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        postsAdapter = new PostsAdapter(new ArrayList<>());
        recyclerView.setAdapter(postsAdapter);

        setupButtons();
        updateAuthUI();
        loadPublications();
    }

    private void setupButtons() {
        if (loginBtn != null) {
            loginBtn.setOnClickListener(v ->
                    startActivity(new Intent(MainActivity.this, LoginActivity.class))
            );
        }

        if (registerBtn != null) {
            registerBtn.setOnClickListener(v ->
                    startActivity(new Intent(MainActivity.this, RegisterActivity.class))
            );
        }

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

        if (newPostBtn != null) {
            newPostBtn.setOnClickListener(v ->
                    startActivityForResult(
                            new Intent(MainActivity.this, NewPostActivity.class), 100)
            );
        }
    }

    private void updateAuthUI() {
        boolean isLoggedIn = getSharedPreferences("MyAppPrefs", MODE_PRIVATE)
                .getBoolean("isLoggedIn", false);

        if (loginBtn != null) loginBtn.setVisibility(isLoggedIn ? View.GONE : View.VISIBLE);
        if (registerBtn != null) registerBtn.setVisibility(isLoggedIn ? View.GONE : View.VISIBLE);
        if (logoutBtn != null) logoutBtn.setVisibility(isLoggedIn ? View.VISIBLE : View.GONE);
        if (newPostBtn != null) newPostBtn.setVisibility(isLoggedIn ? View.VISIBLE : View.GONE);
    }

    private void loadPublications() {
        ApiService apiService = ApiClient.getClient().create(ApiService.class);

        String token = getSharedPreferences("MyAppPrefs", MODE_PRIVATE)
                .getString("authToken", null);
        String authHeader = token != null ? "Token " + token : null;

        Call<PublicationListResponse> call = apiService.getPublications(authHeader);
        call.enqueue(new Callback<PublicationListResponse>() {
            @Override
            public void onResponse(Call<PublicationListResponse> call, Response<PublicationListResponse> response) {
                if (response.isSuccessful() && response.body() != null) {
                    List<Publication> posts = response.body().results;
                    Toast.makeText(MainActivity.this,
                            "Posts loaded: " + posts.size(),
                            Toast.LENGTH_SHORT).show();
                    postsAdapter.updateData(posts);
                } else {
                    Toast.makeText(MainActivity.this,
                            "Failed to load publications: " + response.code(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<PublicationListResponse> call, Throwable t) {
                Toast.makeText(MainActivity.this,
                        "Failed to load publications: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == RESULT_OK) {
            loadPublications(); // reload feed after new post
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        updateAuthUI();
        loadPublications();
    }
}
