// FILSTI: app\src\main\java\com\kbs\kbsintranett\HandbookFragment.java
package com.kbs.kbsintranett;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation; // Viktig
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class HandbookFragment extends Fragment {

    private RecyclerView recyclerView;
    private ProgressBar progressBar;
    private EditText searchField;
    private HandbookAdapter adapter;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_handbook, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        recyclerView = view.findViewById(R.id.recycler_handbook);
        progressBar = view.findViewById(R.id.progressBar);
        searchField = view.findViewById(R.id.search_field);

        recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2));

        searchField.addTextChangedListener(new TextWatcher() {
            @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override public void onTextChanged(CharSequence s, int start, int before, int count) {}
            @Override public void afterTextChanged(Editable s) {
                if (adapter != null) adapter.filter(s.toString());
            }
        });

        fetchHandbook();
    }

    private void fetchHandbook() {
        RetrofitClient.getApiService().getHandbookItems().enqueue(new Callback<List<HandbookItem>>() {
            @Override
            public void onResponse(Call<List<HandbookItem>> call, Response<List<HandbookItem>> response) {
                if (!isAdded()) return;
                progressBar.setVisibility(View.GONE);

                if (response.isSuccessful() && response.body() != null) {
                    adapter = new HandbookAdapter(response.body(), item -> {
                        // NYTT: Naviger til Native Detail Fragment
                        Bundle bundle = new Bundle();
                        bundle.putInt("page_id", item.getId());
                        bundle.putString("page_title", item.getTitle());

                        Navigation.findNavController(getView())
                                .navigate(R.id.action_handbook_to_detail, bundle);
                    });
                    recyclerView.setAdapter(adapter);
                } else {
                    String msg = "Kunne ikke laste håndboken. Kode: " + response.code();
                    if (response.code() == 404) msg += "\n(Fant ikke foreldresiden 'interninstruks-hms')";
                    Toast.makeText(getContext(), msg, Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(Call<List<HandbookItem>> call, Throwable t) {
                if (!isAdded()) return;
                progressBar.setVisibility(View.GONE);
                Toast.makeText(getContext(), "Nettverksfeil", Toast.LENGTH_SHORT).show();
            }
        });
    }
}