import { useMemo } from 'react';

import type { FollowUp } from '@/types/entities';
import { useData } from '@/providers/data-provider';

type UseFollowUpsResult = {
    followUps: FollowUp[];
    overdue: FollowUp[];
    upcoming: FollowUp[];
};

export const useFollowUps = (): UseFollowUpsResult => {
    const { followUps } = useData();

    const now = useMemo(() => new Date(), []);

    const overdue = useMemo(() => {
        return followUps.filter((followUp) => {
            if (followUp.followUpStatus === 'OVERDUE') {
                return true;
            }

            if (followUp.followUpStatus === 'PENDING' && followUp.scheduledAt !== null) {
                return new Date(followUp.scheduledAt) < now;
            }

            return false;
        });
    }, [followUps, now]);

    const upcoming = useMemo(() => {
        return followUps.filter((followUp) => {
            return followUp.followUpStatus === 'PENDING' && followUp.scheduledAt !== null && new Date(followUp.scheduledAt) >= now;
        });
    }, [followUps, now]);

    return {
        followUps,
        overdue,
        upcoming,
    };
};
