import { useEffect, useState, useCallback, useRef } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Task } from '@shared/schema';
import { useTranslation } from 'react-i18next';
import { formatDistanceToNow } from 'date-fns';
import { de, enUS } from 'date-fns/locale';

export function useNotifications({ poll = true }: { poll?: boolean } = {}) {
    const { t, i18n } = useTranslation();
    const [permission, setPermission] = useState<NotificationPermission>('default');
    const [enabled, setEnabled] = useState(false);

    // Track notified tasks to prevent duplicate alerts in same session
    const notifiedTasksRef = useRef<Set<string>>(new Set());

    useEffect(() => {
        if ('Notification' in window) {
            setPermission(Notification.permission);
            const isEnabled = localStorage.getItem('taskflow-notifications-enabled') === 'true';
            setEnabled(isEnabled && Notification.permission === 'granted');
        }
    }, []);

    const requestPermission = useCallback(async () => {
        if (!('Notification' in window)) return false;

        const result = await Notification.requestPermission();
        setPermission(result);

        if (result === 'granted') {
            setEnabled(true);
            localStorage.setItem('taskflow-notifications-enabled', 'true');
            new Notification(t('notifications.enabledTitle'), {
                body: t('notifications.enabledBody'),
                // icon: '/favicon.ico' // Chrome sometimes blocks if icon 404
            });
            return true;
        }
        return false;
    }, [t]);

    const toggleEnabled = useCallback((value: boolean) => {
        if (value && permission !== 'granted') {
            requestPermission();
        } else {
            setEnabled(value);
            localStorage.setItem('taskflow-notifications-enabled', String(value));
        }
    }, [permission, requestPermission]);

    // Query tasks for polling
    const { data: tasks } = useQuery<Task[]>({
        queryKey: ['/api/tasks'],
        enabled: enabled && poll // Only poll if enabled AND polling is active
    });

    // Polling Logic
    useEffect(() => {
        if (!poll || !enabled || !tasks || permission !== 'granted') return;

        const checkTasks = () => {
            const now = new Date();

            tasks.forEach(task => {
                if (!task.dueDate || task.status === 'done' || notifiedTasksRef.current.has(task.id)) return;

                const dueDate = new Date(task.dueDate);
                const diffMs = dueDate.getTime() - now.getTime();
                const diffMinutes = diffMs / (1000 * 60);

                // Alert: Upcoming (15 min before)
                if (diffMinutes > 0 && diffMinutes <= 15) {
                    sendNotification(task, 'upcoming');
                    notifiedTasksRef.current.add(task.id);
                }

                // Alert: Just Overdue (within last 1 min to catch it once)
                // or purely check if overdue and not notified?
                // Let's stick to "Just became overdue" or "Is overdue" but protect with Set
                if (diffMinutes < 0) {
                    sendNotification(task, 'overdue');
                    notifiedTasksRef.current.add(task.id);
                }
            });
        };

        const sendNotification = (task: Task, type: 'upcoming' | 'overdue') => {
            const title = type === 'upcoming'
                ? t('notifications.upcomingTitle', { task: task.title })
                : t('notifications.overdueTitle', { task: task.title });

            const body = type === 'upcoming'
                ? t('notifications.upcomingBody', { time: formatDistanceToNow(new Date(task.dueDate!), { locale: i18n.language === 'de' ? de : enUS }) })
                : t('notifications.overdueBody');

            new Notification(title, {
                body,
                // icon: '/favicon.ico',
                tag: `task-${task.id}-${type}` // prevent duplicate native notifications
            });
        };

        // Check immediately and then interval
        checkTasks();
        const interval = setInterval(checkTasks, 60000); // Check every minute

        return () => clearInterval(interval);
    }, [enabled, tasks, permission, t, i18n.language]);

    return {
        permission,
        enabled,
        requestPermission,
        toggleEnabled
    };
}
