package com.kbs.kbsintranett;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
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;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class NewsFullFragment extends Fragment {

    private RecyclerView recyclerViewNews;
    private RecyclerView recyclerViewCategories;
    private ProgressBar progressBar;
    private NewsAdapter newsAdapter;
    private List<WpPost> allPosts = new ArrayList<>();

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

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

        recyclerViewNews = view.findViewById(R.id.recycler_news_full);
        recyclerViewCategories = view.findViewById(R.id.recycler_categories);
        progressBar = view.findViewById(R.id.loading_news_full);

        // Setup Nyhetsliste
        recyclerViewNews.setLayoutManager(new LinearLayoutManager(getContext()));

        // Setup Kategorier (Horisontal)
        recyclerViewCategories.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        setupCategories();

        fetchAllNews();
    }

    private void setupCategories() {
        List<String> categories = Arrays.asList(
                "Alle",
                "Avtaler og invitasjoner", "BHT", "Bilhold", "Cordel",
                "Ferieavvikling", "Fest og moro", "Generell drift",
                "HMS", "IT og sikkerhet", "Miljøfyrtårn", "Møtereferat", "SMX"
        );

        CategoryAdapter catAdapter = new CategoryAdapter(categories, selectedCategory -> {
            filterNews(selectedCategory);
        });
        recyclerViewCategories.setAdapter(catAdapter);
    }

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

                if (response.isSuccessful() && response.body() != null) {
                    allPosts = response.body();
                    formatDates(allPosts);

                    newsAdapter = new NewsAdapter(new ArrayList<>(allPosts), post -> {
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("post_data", post);
                        Navigation.findNavController(getView()).navigate(R.id.action_newsFull_to_newsDetail, bundle);
                    });
                    recyclerViewNews.setAdapter(newsAdapter);
                } else {
                    Toast.makeText(getContext(), "Klarte ikke laste nyheter", Toast.LENGTH_SHORT).show();
                }
            }

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

    private void filterNews(String category) {
        if (newsAdapter == null) return;
        List<WpPost> filteredList = new ArrayList<>();

        if (category.equals("Alle")) {
            filteredList.addAll(allPosts);
        } else {
            for (WpPost post : allPosts) {
                if (post.getCategoryName().equals(category)) {
                    filteredList.add(post);
                }
            }
        }
        newsAdapter.updateList(filteredList);
    }

    private void formatDates(List<WpPost> posts) {
        SimpleDateFormat rawFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault());
        SimpleDateFormat targetFormat = new SimpleDateFormat("dd. MMM yyyy", Locale.getDefault());

        for (WpPost post : posts) {
            try {
                Date date = rawFormat.parse(post.date);
                post.date = targetFormat.format(date);
            } catch (Exception e) {}
        }
    }
}