import { View, Text } from "react-native-ui-lib";
import React from "react";
import { IToDo, useToDosContext } from "@/contexts/ToDosContext";
import ToDoItem from "./ToDoItem";
import { format, isToday, isTomorrow } from "date-fns"; 

const groupToDosByDate = (toDos: IToDo[]) => {
  return toDos.reduce((groups, toDo) => {
    let dateKey;

    if (toDo.date === null) {
      dateKey = "No Date";
    } else if (isToday(toDo.date)) {
      dateKey = "Today • " + format(toDo.date, "EEE MMM dd");
    } else if (isTomorrow(toDo.date)) {
      dateKey = "Tomorrow • " + format(toDo.date, "EEE MMM dd");
    } else {
      dateKey = format(toDo.date, "EEE MMM dd");
    }

    if (!groups[dateKey]) {
      groups[dateKey] = [];
    }

    groups[dateKey].push(toDo);
    return groups;
  }, {} as { [key: string]: IToDo[] });
};

const ToDosList = () => {
  const { toDos } = useToDosContext();
  const groupedToDos = groupToDosByDate(toDos);

  const noDateToDos = groupedToDos["No Date"] || [];
  const datedToDos = Object.keys(groupedToDos).filter((key) => key !== "No Date");

  return (
    <View marginB-140>

      {noDateToDos.length > 0 && (
        <View key="No Date">
          {noDateToDos
            .sort((a, b) => Number(a.done) - Number(b.done))
            .map((item) => (
              <ToDoItem key={item.id} item={item} />
            ))}
        </View>
      )}

      {datedToDos.map((dateKey) => {
        const sortedToDos = [
          ...groupedToDos[dateKey].filter((toDo) => !toDo.done),
          ...groupedToDos[dateKey].filter((toDo) => toDo.done),
        ];

        return (
          <View key={dateKey}>
            <Text
              text70
              style={{
                fontWeight: "bold",
                marginVertical: 8,
                paddingHorizontal: 20,
              }}
            >
              {dateKey}
            </Text>
            {sortedToDos.map((item) => (
              <ToDoItem key={item.id} item={item} />
            ))}
          </View>
        );
      })}
    </View>
  );
};

export default ToDosList;
