import * as Device from 'expo-device';
import * as Notifications from 'expo-notifications';
import { Platform } from 'react-native';

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

export async function registerForPushNotificationsAsync() {
  let token;

  if (Platform.OS === 'android') {
    await Notifications.setNotificationChannelAsync('default', {
      name: 'default',
      importance: Notifications.AndroidImportance.MAX,
      vibrationPattern: [0, 250, 250, 250],
      lightColor: '#FF231F7C',
    });
  }

  if (Device.isDevice) {
    const { status: existingStatus } = await Notifications.getPermissionsAsync();
    let finalStatus = existingStatus;

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

    if (finalStatus !== 'granted') {
      console.log('Notification uchun ruxsat berilmadi!');
      return;
    }

    token = (
      await Notifications.getExpoPushTokenAsync({
        projectId: '67d5a024-4eb7-44ec-8b18-6c9187bd1862',
      })
    ).data;

    console.log('Push Token:', token);
  } else {
    console.log('Push notification faqat real qurilmalarda ishlaydi!');
  }

  return token;
}

export async function sendTestNotification() {
  await Notifications.scheduleNotificationAsync({
    content: {
      title: 'Test xabar 📬',
      body: 'Bu test notification! Notification tizimi muvaffaqiyatli ishlayapti.',
      data: { screen: 'monitoring', type: 'test' },
    },
    trigger: {
      type: Notifications.SchedulableTriggerInputTypes.TIME_INTERVAL,
      seconds: 3, // 2 o'rniga 3
    },
  });
}
