import { useCallback, useMemo } from 'react';
import { differenceInCalendarDays } from 'date-fns';
import { Conversation } from '../contexts/ChatContext';
// import useRenderTracker from './useRenderTracker'

export interface GroupedConversation {
    category: string;
    categoryOrder: number;
    conversations: Conversation[];
  }

interface useGroupedConversationsProps {
  conversations: Conversation[];
}

const useGroupedConversations = ({ conversations }: useGroupedConversationsProps) => {
  
  const groupConversationsByDate = useCallback((convs: Conversation[]) => {
    const now = new Date();
    const groups: { [key: string]: { categoryOrder: number; conversations: Conversation[] } } = {};

    convs.forEach((conv) => {
      const convDate = new Date(conv.updated_at);
      const dayDifference = differenceInCalendarDays(now, convDate);

      let category = '';
      let categoryOrder = 0;

      if (dayDifference === 0) {
        category = 'Today';
        categoryOrder = 1;
      } else if (dayDifference === 1) {
        category = 'Yesterday';
        categoryOrder = 2;
      } else if (dayDifference < 7) {
        category = 'Past Week';
        categoryOrder = 3;
      } else if (dayDifference < 30) {
        category = 'Past Month';
        categoryOrder = 4;
      } else {
        category = 'Earlier';
        categoryOrder = 5;
      }

      if (!groups[category]) {
        groups[category] = { categoryOrder, conversations: [] };
      }
      groups[category].conversations.push(conv);
    });

    return Object.entries(groups)
      .map(([category, { categoryOrder, conversations }]) => ({
        category,
        categoryOrder,
        conversations,
      }))
      .sort((a, b) => a.categoryOrder - b.categoryOrder);
  }, []);

  return useMemo(() => groupConversationsByDate(conversations), [conversations, groupConversationsByDate]);
};

export default useGroupedConversations;