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

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

/**
 * Ask for notification permission and (when running in a dev build with an EAS
 * projectId) return the Expo push token to register with the server.
 *
 * NOTE: remote push does NOT work inside Expo Go since SDK 53 — it needs a dev
 * build (`npx expo run:android` / eas build). Local notifications work anywhere,
 * so the app falls back to those until then. Returns null when no token is
 * available; that's fine, nothing else should break.
 */
export async function registerForPushNotificationsAsync(): Promise<string | null> {
  if (Platform.OS === 'android') {
    await Notifications.setNotificationChannelAsync('default', {
      name: 'Scores & disputes',
      importance: Notifications.AndroidImportance.HIGH,
      vibrationPattern: [0, 250, 250, 250],
    });
  }

  if (!Device.isDevice) return null;

  const { status: existing } = await Notifications.getPermissionsAsync();
  let status = existing;
  if (existing !== 'granted') {
    ({ status } = await Notifications.requestPermissionsAsync());
  }
  if (status !== 'granted') return null;

  const projectId =
    Constants.expoConfig?.extra?.eas?.projectId ?? Constants.easConfig?.projectId;
  if (!projectId) return null; // Expo Go / no EAS project yet

  try {
    const { data } = await Notifications.getExpoPushTokenAsync({ projectId });
    // TODO(backend): POST this token to /players/:id/push-token so the server
    // can push to the other phone.
    return data;
  } catch {
    return null;
  }
}

/** Immediately show a local notification (works in Expo Go). */
export async function presentLocalNotification(title: string, body: string) {
  try {
    await Notifications.scheduleNotificationAsync({
      content: { title, body, sound: 'default' },
      trigger: null,
    });
  } catch {
    // permission denied — the in-app UI already reflects the change
  }
}
