package com.howon.lifepass;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.Timestamp;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;

import java.util.ArrayList;

public class NotificationActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private NoticeAdapter adapter;
    private ArrayList<Notice> noticeList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notification);

        // 하단 네비게이션 버튼 초기화
        ImageButton bottomButton1 = findViewById(R.id.bottomButton1);
        ImageButton bottomButton2 = findViewById(R.id.bottomButton2);
        ImageButton bottomButton3 = findViewById(R.id.bottomButton3);
        ImageButton bottomButton4 = findViewById(R.id.bottomButton4);

        // 하단 버튼 클릭 이벤트 설정
        View.OnClickListener bottomButtonListener = v -> {
            int id = v.getId();
            if (id == R.id.bottomButton1) {
                startActivity(new Intent(NotificationActivity.this, WeatherActivity.class));
            } else if (id == R.id.bottomButton2) {
                startActivity(new Intent(NotificationActivity.this, AlertActivity.class));
            } else if (id == R.id.bottomButton3) {
                Toast.makeText(NotificationActivity.this, "현재 페이지입니다.", Toast.LENGTH_SHORT).show();
            } else if (id == R.id.bottomButton4) {
                startActivity(new Intent(NotificationActivity.this, DisasterActivity.class));
            }
        };

        bottomButton1.setOnClickListener(bottomButtonListener);
        bottomButton2.setOnClickListener(bottomButtonListener);
        bottomButton3.setOnClickListener(bottomButtonListener);
        bottomButton4.setOnClickListener(bottomButtonListener);

        // RecyclerView 초기화
        recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        // 어댑터 초기화
        noticeList = new ArrayList<>();
        adapter = new NoticeAdapter(noticeList, notice -> {
            // 공지사항 클릭 시 세부 화면으로 이동
            Intent intent = new Intent(NotificationActivity.this, NoticeDetailActivity.class);
            intent.putExtra("title", notice.getTitle());
            intent.putExtra("author", notice.getAuthor());
            intent.putExtra("content", notice.getContent());
            intent.putExtra("documentId", notice.getDocumentId()); // Firestore 문서 ID 전달
            Timestamp timestamp = notice.getTimestamp();
            if (timestamp != null) {
                intent.putExtra("createdAt", timestamp.toDate().getTime());
            }
            startActivity(intent);
        });
        recyclerView.setAdapter(adapter);

        // Firestore 데이터 로드
        loadNoticesFromFirestore();

        // 공지사항 추가 버튼
        FloatingActionButton fabAddNotice = findViewById(R.id.fab_add_notice);
        fabAddNotice.setOnClickListener(v -> {
            Intent intent = new Intent(NotificationActivity.this, AddNoticeActivity.class);
            startActivity(intent);
        });
    }

    private void loadNoticesFromFirestore() {
        FirebaseFirestore db = FirebaseFirestore.getInstance();

        // Firestore 실시간 리스너 추가
        db.collection("notices")
                .orderBy("timestamp", com.google.firebase.firestore.Query.Direction.DESCENDING) // 내림차순 정렬
                .addSnapshotListener((queryDocumentSnapshots, e) -> {
                    if (e != null) {
                        Toast.makeText(NotificationActivity.this, "오류 발생: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                        return;
                    }

                    if (queryDocumentSnapshots != null) {
                        noticeList.clear(); // 기존 목록 비우기
                        for (QueryDocumentSnapshot document : queryDocumentSnapshots) {
                            try {
                                Notice notice = document.toObject(Notice.class);
                                if (notice != null) {
                                    notice.setDocumentId(document.getId()); // 문서 ID 설정
                                    noticeList.add(notice);
                                }
                            } catch (Exception ex) {
                                Toast.makeText(NotificationActivity.this, "데이터 매핑 중 오류 발생", Toast.LENGTH_SHORT).show();
                            }
                        }
                        adapter.notifyDataSetChanged(); // 데이터 갱신
                    }
                });
    }

}