import { useEffect, useCallback, useRef } from 'react';
import * as Notifications from 'expo-notifications';
import { Platform } from 'react-native';
import * as Device from 'expo-device';
import { deviceService, notificationService } from '@shieldai/mobile-api-client';
import { useSettingsStore } from '@/store/settingsStore';

export function usePushNotifications() {
  const preferencesRef = useRef(useSettingsStore.getState().preferences);

  useEffect(() => {
    const subscription = useSettingsStore.subscribe((state) => {
      preferencesRef.current = state.preferences;
    });
    return subscription;
  }, []);

  Notifications.setNotificationHandler({
    handleNotification: async () => {
      const prefs = preferencesRef.current;
      return {
        shouldShowAlert: prefs.pushNotifications,
        shouldPlaySound: prefs.pushNotifications,
        shouldSetBadge: false,
      };
    },
  });

  const registerForPushNotifications = useCallback(async () => {
    try {
      const { status: existingStatus } = await Notifications.getPermissionsAsync();
      let finalStatus = existingStatus;

      if (existingStatus !== 'granted') {
        const { status } = await Notifications.requestPermissionsAsync();
        finalStatus = status;
      }

      if (finalStatus !== 'granted') {
        return null;
      }

      const token = (await Notifications.getExpoPushTokenAsync({
        projectId: 'shieldai-project-id',
      })).data;

      try {
        await deviceService.registerDevice({
          platform: Platform.OS === 'ios' ? 'ios' : 'android',
          pushToken: token,
          modelName: Platform.OS === 'ios' ? 'iPhone' : 'Android',
          osVersion: Device.osVersion || '0',
          appVersion: '1.0.0',
        });
      } catch (deviceError) {
        console.warn('Device registration failed (will retry on next launch):', deviceError);
      }

      return token;
    } catch (error) {
      console.error('Failed to register for push notifications:', error);
      return null;
    }
  }, []);

  useEffect(() => {
    const subscription = Notifications.addNotificationReceivedListener((notification) => {
      const type = notification.request.content.data?.type;
      const prefs = preferencesRef.current;

      if (type === 'darkwatch_alert' && !prefs.darkwatchAlert) return;
      if (type === 'spam_blocked' && !prefs.spamBlocked) return;
      if (type === 'voiceprint_analysis' && !prefs.voiceprintAnalysis) return;
    });

    return () => subscription.remove();
  }, []);

  return { registerForPushNotifications };
}
