package com.example.doitnow;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.doitnow.Adapter.ToDoAdapter;
import com.example.doitnow.Model.ToDoModel;
import com.example.doitnow.Utils.DatabaseHandler;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.Collections;
import java.util.List;

public class AllTodoFragment extends Fragment {

    private RecyclerView recyclerView;
    private ToDoAdapter adapter;
    private List<ToDoModel> taskList;
    private DatabaseHandler db;

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

        db = new DatabaseHandler(requireContext());
        db.openDatabase();

        recyclerView = view.findViewById(R.id.tasksRecyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        taskList = db.getAllTasks();
        Collections.reverse(taskList);

        adapter = new ToDoAdapter(db, requireActivity(), taskList);
        recyclerView.setAdapter(adapter);

        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new RecyclerItemTouchHelper(adapter));
        itemTouchHelper.attachToRecyclerView(recyclerView);

        getParentFragmentManager().setFragmentResultListener("taskAdded", this, (key, bundle) -> {
            boolean added = bundle.getBoolean("taskAdded", false);
            if (added) {
                refreshTaskList();
            }
        });
        return view;
    }

    public void refreshData() {
        taskList = db.getAllTasks();
        Collections.reverse(taskList);
        adapter.setTasks(taskList);
        adapter.notifyDataSetChanged();
    }
    public void refreshTaskList() {
        taskList.clear(); // 清空舊資料
        taskList.addAll(db.getAllTasks()); // 重新從資料庫讀取
        Collections.reverse(taskList); // 保持倒序排列（若有這需求）
        adapter.notifyDataSetChanged(); // 通知 RecyclerView 更新
    }

}
