import { useEffect, useRef } from 'react';
import * as Notifications from 'expo-notifications';
import { useAuth } from '@/src/context/AuthContext';
import { fetchDueReminders } from '@/src/api/diet.api';
import { todayIso } from '@/src/types/diet';

Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: true,
    shouldSetBadge: false,
    shouldShowBanner: true,
    shouldShowList: true,
  }),
});

const POLL_MS = 60_000;

function currentTimeHHmm(): string {
  const now = new Date();
  return `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
}

export function useReminderNotifications() {
  const { isAuthenticated } = useAuth();
  const notifiedRef = useRef<Set<number>>(new Set());

  useEffect(() => {
    if (!isAuthenticated) return;

    let cancelled = false;
    let interval: ReturnType<typeof setInterval> | undefined;

    const poll = async () => {
      if (cancelled) return;
      try {
        const due = await fetchDueReminders(todayIso(), currentTimeHHmm());
        for (const reminder of due) {
          if (notifiedRef.current.has(reminder.id)) continue;
          notifiedRef.current.add(reminder.id);
          await Notifications.scheduleNotificationAsync({
            content: {
              title: reminder.title,
              body: reminder.message ?? undefined,
            },
            trigger: null,
          });
        }
      } catch {
        // ignore polling errors
      }
    };

    void (async () => {
      const { status } = await Notifications.requestPermissionsAsync();
      if (status !== 'granted' || cancelled) return;
      await poll();
      interval = setInterval(() => void poll(), POLL_MS);
    })();

    return () => {
      cancelled = true;
      if (interval) clearInterval(interval);
      notifiedRef.current.clear();
    };
  }, [isAuthenticated]);
}
