package com.example.doitnow;

import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
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.prolificinteractive.materialcalendarview.CalendarDay;
import com.prolificinteractive.materialcalendarview.MaterialCalendarView;

import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;

public class CalendarFragment extends Fragment {

    private MaterialCalendarView calendarView;
    private RecyclerView todoRecyclerView;
    private ToDoAdapter tasksAdapter;
    private List<ToDoModel> taskList;
    private DatabaseHandler db;
    private TextView noTaskText;
    private TextView currentDateText;

    private boolean isCalendarCollapsed = false;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_calendar, container, false);

        calendarView = view.findViewById(R.id.calendarView);
        todoRecyclerView = view.findViewById(R.id.todoRecyclerView);
        noTaskText = view.findViewById(R.id.noTaskText);
        currentDateText = view.findViewById(R.id.currentDateText);

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

        taskList = Collections.emptyList();
        todoRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        tasksAdapter = new ToDoAdapter(db, requireActivity(), taskList);
        todoRecyclerView.setAdapter(tasksAdapter);

        // 設置預設選中今天
        calendarView.setSelectedDate(CalendarDay.today());
        updateTasksForDate(new Date());

        // 點選日曆日期時折疊日曆
        calendarView.setOnDateChangedListener((widget, date, selected) -> {
            Date selectedDate = date.getDate();
            updateTasksForDate(selectedDate);

            currentDateText.setText(formatDate(selectedDate));
            currentDateText.setVisibility(View.VISIBLE);

            // 動畫折疊日曆
            calendarView.animate()
                    .translationY(-calendarView.getHeight())
                    .alpha(0f)
                    .setDuration(300)
                    .withEndAction(() -> {
                        calendarView.setVisibility(View.GONE);
                        calendarView.setTranslationY(0); // 重置位置
                        calendarView.setAlpha(1f);
                    });

            isCalendarCollapsed = true;
        });

        // 點選頂部日期欄時展開日曆
        currentDateText.setOnClickListener(v -> {
            if (isCalendarCollapsed) {
                calendarView.setVisibility(View.VISIBLE);
                calendarView.setAlpha(0f);
                calendarView.setTranslationY(-calendarView.getHeight());

                // 動畫展開日曆
                calendarView.animate()
                        .translationY(0)
                        .alpha(1f)
                        .setDuration(300)
                        .start();

                currentDateText.setVisibility(View.GONE);
                isCalendarCollapsed = false;
            }
        });

        addEventDots();

        calendarView.setOnMonthChangedListener((widget, date) -> {
            calendarView.removeDecorators();
            addEventDots();
        });

        return view;
    }

    private void updateTasksForDate(Date date) {
        String clickedDate = formatDate(date);
        List<ToDoModel> tasks = db.getTasksByDate(clickedDate);

        if (tasks.isEmpty()) {
            noTaskText.setVisibility(View.VISIBLE);
            todoRecyclerView.setVisibility(View.GONE);
        } else {
            noTaskText.setVisibility(View.GONE);
            todoRecyclerView.setVisibility(View.VISIBLE);
            tasksAdapter.setTasks(tasks);
        }
    }

    private String formatDate(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        return sdf.format(date);
    }

    private void addEventDots() {
        List<ToDoModel> allTasks = db.getAllTasks();
        HashSet<CalendarDay> eventDates = new HashSet<>();

        CalendarDay currentMonth = calendarView.getCurrentDate();

        for (ToDoModel task : allTasks) {
            try {
                String dateStr = task.getEndTime();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
                Date date = sdf.parse(dateStr);
                CalendarDay day = CalendarDay.from(date);
                if (day.getMonth() == currentMonth.getMonth() && day.getYear() == currentMonth.getYear()) {
                    eventDates.add(day);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        calendarView.addDecorator(new EventDecorator(Color.parseColor("#8E24AA"), eventDates));
    }
}
