package com.howon.lifepass;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.google.firebase.Timestamp;

import java.util.List;

public class NoticeAdapter extends RecyclerView.Adapter<NoticeAdapter.NoticeViewHolder> {

    public interface OnItemClickListener {
        void onItemClick(Notice notice); // 아이템 클릭 이벤트
    }

    private final List<Notice> noticeList;
    private final OnItemClickListener listener;

    public NoticeAdapter(List<Notice> noticeList, OnItemClickListener listener) {
        this.noticeList = noticeList;
        this.listener = listener;
    }

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

    @Override
    public void onBindViewHolder(@NonNull NoticeViewHolder holder, int position) {
        Notice notice = noticeList.get(position);

        // 데이터 설정
        holder.titleTextView.setText(notice.getTitle() != null ? notice.getTitle() : "제목 없음");
        holder.authorTextView.setText(notice.getAuthor() != null ? notice.getAuthor() : "작성자 없음");

        Timestamp timestamp = notice.getTimestamp();
        String formattedDate = (timestamp != null)
                ? new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault())
                .format(timestamp.toDate())
                : "작성 시간 없음";
        holder.dateTextView.setText(formattedDate);

        // 공지사항 클릭 이벤트
        holder.itemView.setOnClickListener(v -> listener.onItemClick(notice));
    }

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

    public static class NoticeViewHolder extends RecyclerView.ViewHolder {
        TextView titleTextView, authorTextView, dateTextView;

        public NoticeViewHolder(@NonNull View itemView) {
            super(itemView);

            titleTextView = itemView.findViewById(R.id.text_view_title);
            authorTextView = itemView.findViewById(R.id.text_view_author);
            dateTextView = itemView.findViewById(R.id.text_view_date);
        }
    }
}
