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

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

export const registerForPushNotificationsAsync = async () => {
  if (!Device.isDevice) {
    console.log("Push notifications require a physical device.");
    return null;
  }

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

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

  if (finalStatus !== "granted") {
    console.log("Permission for notifications not granted!");
    return null;
  }

  if (Platform.OS === "android") {
    await Notifications.setNotificationChannelAsync("mail-notifications", {
      name: "Email Baru",
      importance: Notifications.AndroidImportance.MAX,
      vibrationPattern: [0, 250, 250, 250],
      lightColor: "#10b981",
      sound: "default",
    });
  }

  return true;
};

export const showNewMailNotification = async (sender, subject, accountEmail) => {
  try {
    await Notifications.scheduleNotificationAsync({
      content: {
        title: `📩 Surat Baru (${accountEmail})`,
        body: `${sender}: ${subject}`,
        data: { accountEmail },
        sound: "default",
        channelId: "mail-notifications",
      },
      trigger: null, // immediate
    });
  } catch (e) {
    console.log("Error displaying notification:", e);
  }
};
