package com.example.vdcscore.ui.news;

import android.os.Build;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.example.vdcscore.R;
import com.example.vdcscore.models.News;

public class NewsDetailFragment extends Fragment {

    private ImageView imgNewsDetail;
    private TextView textDate, textTitle, textBody;
    private com.google.android.material.button.MaterialButton btnPrev, btnNext;
    private java.util.List<News> newsList;
    private int currentIndex;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_news_detail, container, false);

        imgNewsDetail = root.findViewById(R.id.img_news_detail);
        textDate = root.findViewById(R.id.text_news_detail_date);
        textTitle = root.findViewById(R.id.text_news_detail_title);
        textBody = root.findViewById(R.id.text_news_detail_body);
        btnPrev = root.findViewById(R.id.btn_prev_news);
        btnNext = root.findViewById(R.id.btn_next_news);

        if (getArguments() != null) {
            News[] newsArray = (News[]) getArguments().getSerializable("news_list");
            if (newsArray != null) {
                newsList = java.util.Arrays.asList(newsArray);
            }
            currentIndex = getArguments().getInt("news_index", 0);
            
            if (newsList != null && currentIndex >= 0 && currentIndex < newsList.size()) {
                updateUI();
            }
        }

        btnPrev.setOnClickListener(v -> {
            if (newsList != null && currentIndex > 0) {
                currentIndex--;
                updateUI();
            }
        });

        btnNext.setOnClickListener(v -> {
            if (newsList != null && currentIndex < newsList.size() - 1) {
                currentIndex++;
                updateUI();
            }
        });

        return root;
    }

    private void updateUI() {
        if (newsList == null || currentIndex < 0 || currentIndex >= newsList.size()) return;
        
        News news = newsList.get(currentIndex);
        populateUI(news);
        
        // Update button states
        btnPrev.setEnabled(currentIndex > 0);
        btnNext.setEnabled(currentIndex < newsList.size() - 1);
        
        // Reset scroll position if needed
        View scroll = getView() != null ? getView().findViewById(R.id.scroll_detail) : null;
        if (scroll != null) {
            scroll.scrollTo(0, 0);
        }
    }

    private void populateUI(News news) {
        textTitle.setText(news.getTitle());

        if (news.getBody() != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                textBody.setText(Html.fromHtml(news.getBody(), Html.FROM_HTML_MODE_COMPACT).toString().trim());
            } else {
                textBody.setText(Html.fromHtml(news.getBody()).toString().trim());
            }
        }

        String dateStr = news.getInsertDate();
        if (dateStr != null && dateStr.length() >= 10) {
            try {
                java.text.SimpleDateFormat inputFormat = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", java.util.Locale.getDefault());
                java.util.Date date = inputFormat.parse(dateStr);
                if (date != null) {
                    java.text.SimpleDateFormat outputFormat = new java.text.SimpleDateFormat("dd MMM yyyy", new java.util.Locale("pt", "PT"));
                    dateStr = outputFormat.format(date);
                }
            } catch (Exception e) {
                if(dateStr.contains("T")) {
                    dateStr = dateStr.split("T")[0];
                }
            }
        }
        textDate.setText(dateStr);

        Glide.with(this)
                .load(news.getPhotoURL())
                .placeholder(R.drawable.ic_menu_gallery)
                .error(R.drawable.ic_menu_gallery)
                .into(imgNewsDetail);
    }
}
