import { View, Text, TouchableOpacity, Icon } from "react-native-ui-lib";
import React, { useState } from "react";
import { useToDosContext } from "@/contexts/ToDosContext";
import ToDoItem from "./ToDoItem";
import { format, isToday, isTomorrow } from "date-fns";
import { AntDesign } from "@expo/vector-icons";
import { IToDo } from "@/hooks/firebase/types/todoData";

const groupToDosByDate = (toDos: IToDo[]) => {
  let sortedTodos = toDos.sort((a, b) => a.date - b.date);
  return sortedTodos.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 = ({ isSettings }: { isSettings?: boolean }) => {
  const { toDos } = useToDosContext();
  const groupedToDos = groupToDosByDate(toDos);

  const [expandedGroups, setExpandedGroups] = useState<{
    [key: string]: boolean;
  }>({});

  const [expandNoDate, setExpandNoDate] = useState<boolean>(true);

  const toggleExpand = (dateKey: string) => {
    setExpandedGroups((prev) => ({
      ...prev,
      [dateKey]: !prev[dateKey],
    }));
  };

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

  return (
    <View marginB-402>
      {noDateToDos.length > 0 && (
        <View key="No Date">
          <View row spread paddingH-19 marginB-12>
            <Text
              text70
              style={{
                fontWeight: "bold",
              }}
            >
              Unscheduled
            </Text>
            {!expandNoDate && (
              <AntDesign
                name="caretright"
                size={24}
                color="#fd1575"
                onPress={() => {
                  setExpandNoDate(!expandNoDate);
                }}
              />
            )}
            {expandNoDate && (
              <AntDesign
                name="caretdown"
                size={24}
                color="#fd1575"
                onPress={() => {
                  setExpandNoDate(!expandNoDate);
                }}
              />
            )}
          </View>
          {expandNoDate &&
            noDateToDos
              .sort((a, b) => Number(a.done) - Number(b.done))
              .map((item) => (
                <ToDoItem isSettings={isSettings} key={item.id} item={item} />
              ))}
        </View>
      )}

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

        return (
          <View key={dateKey}>
            <TouchableOpacity
              onPress={() => toggleExpand(dateKey)}
              style={{
                flexDirection: "row",
                justifyContent: "space-between",
                alignItems: "center",
                paddingHorizontal: 20,
                marginVertical: 8,
              }}
            >
              <Text
                text70
                style={{
                  fontFamily: "Manrope_700Bold",
                  fontSize: 15,
                  color: "#484848",
                }}
              >
                {dateKey}
              </Text>
              {!isExpanded && (
                <AntDesign name="caretright" size={24} color="#fd1575" />
              )}
              {isExpanded && (
                <AntDesign name="caretdown" size={24} color="#fd1575" />
              )}
            </TouchableOpacity>

            {isExpanded &&
              sortedToDos.map((item) => (
                <ToDoItem isSettings={isSettings} key={item.id} item={item} />
              ))}
          </View>
        );
      })}
    </View>
  );
};

export default ToDosList;
