package com.example.vdcscore.ui.news;

import android.os.Build;
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.recyclerview.widget.RecyclerView;

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

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

public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.ViewHolder> {

    private List<News> newsList = new ArrayList<>();
    private OnNewsClickListener listener;

    public interface OnNewsClickListener {
        void onNewsClick(News news, int position);
    }

    public void setOnNewsClickListener(OnNewsClickListener listener) {
        this.listener = listener;
    }

    public void setNewsList(List<News> newsList) {
        this.newsList = (newsList != null) ? newsList : new ArrayList<>();
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_news, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        News news = newsList.get(position);

        holder.textTitle.setText(news.getTitle());
        
        // Tratar o corpo da notícia (remover HTML)
        if (news.getBody() != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                holder.textBody.setText(Html.fromHtml(news.getBody(), Html.FROM_HTML_MODE_COMPACT).toString().trim());
            } else {
                holder.textBody.setText(Html.fromHtml(news.getBody()).toString().trim());
            }
        }

        // Formatar data se necessário (assumindo que vem da API/Firebase como ISO ou similar)
        String dateStr = news.getInsertDate();
        if (dateStr != null && dateStr.length() >= 10) {
            try {
                // Tentar extrair "2026-04-20" do formato "2026-04-20T20:05:01.000Z"
                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) {
                // Fallback para exibir apenas a parte da data "YYYY-MM-DD"
                if(dateStr.contains("T")) {
                    dateStr = dateStr.split("T")[0];
                }
            }
        }
        holder.textDate.setText(dateStr);

        Glide.with(holder.itemView.getContext())
                .load(news.getPhotoURL())
                .placeholder(R.drawable.ic_menu_gallery)
                .error(R.drawable.ic_menu_gallery)
                .into(holder.imgNews);
                
        holder.itemView.setOnClickListener(v -> {
            if (listener != null) {
                int pos = holder.getAdapterPosition();
                if (pos != RecyclerView.NO_POSITION) {
                    listener.onNewsClick(news, pos);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return newsList.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public final ImageView imgNews;
        public final TextView textTitle;
        public final TextView textBody;
        public final TextView textDate;

        public ViewHolder(View view) {
            super(view);
            imgNews = view.findViewById(R.id.img_news);
            textTitle = view.findViewById(R.id.text_news_title);
            textBody = view.findViewById(R.id.text_news_body);
            textDate = view.findViewById(R.id.text_news_date);
        }
    }
}
