import React, { createContext, useState, useContext, useEffect, useCallback } from 'react';
import { fetchFriendsNotification } from '@api/friends';
import { StoreType, storage } from 'src/storage';

const NotificationContext = createContext({
  isNotificationActive: false,
  updateNotificationStatus: () => {}
});

export const NotificationProvider = ({ children }: { children: React.ReactNode }) => {
  const [isNotificationActive, setIsNotificationActive] = useState(
    storage.get('friendsNotification', StoreType.BOOLEAN) as boolean
  );

  const updateNotificationStatus = async () => {
    const token = storage.get('token', StoreType.STRING);

    if (token) {
      try {
        const data = await fetchFriendsNotification(token as string);
        const isActive = data && data.active;

        if (typeof isActive === 'boolean') {
          setIsNotificationActive(isActive);
          storage.set('friendsNotification', isActive);
        }
      } catch (error) {
        console.error('Failed to fetch notifications', error);
      }
    } else {
      setIsNotificationActive(false);
      storage.set('friendsNotification', false);
    }
  };

  useEffect(() => {
    updateNotificationStatus();
  }, []);

  useEffect(() => {
    const interval = setInterval(() => {
      updateNotificationStatus();
    }, 15000);

    return () => clearInterval(interval);
  }, [updateNotificationStatus]);

  return (
    <NotificationContext.Provider value={{ isNotificationActive, updateNotificationStatus }}>
      {children}
    </NotificationContext.Provider>
  );
};

export const useNotification = () => useContext(NotificationContext);
