import * as Notifications from 'expo-notifications';
import React, { useEffect } from "react";
import { Alert, Button, Platform, Text, View } from "react-native";

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

async function registerForPushNotificationsAsync() {
  const { status: existingStatus } = await Notifications.getPermissionsAsync();
  let finalStatus = existingStatus;
  if (existingStatus !== 'granted') {
    const { status } = await Notifications.requestPermissionsAsync();
    finalStatus = status;
  }
  if (finalStatus !== 'granted') {
    Alert.alert('Permission for notifications not granted!');
    return false;
  }
  return true;
}

async function sendNotification() {
  try {
    const id = await Notifications.scheduleNotificationAsync({
      content: {
        title: "Hello!",
        body: "Ez egy értesítés példája.",
      },
      trigger: Platform.OS === 'android'
        ? ({ seconds: 1, repeats: false } as any)
        : null,
    });
    Alert.alert('Notification scheduled!', `ID: ${id}`);
  } catch (e) {
    Alert.alert('Hiba történt!', String(e));
  }
}

export default function Index() {
  useEffect(() => {
    registerForPushNotificationsAsync();
  }, []);

  return (
    <View
      style={{
        flex: 1,
        justifyContent: "center",
        alignItems: "center",
      }}
    >
      <Text>Edit app/index.tsx to edit this screen.</Text>
      <Button title="Küldj értesítést" onPress={sendNotification} />
    </View>
  );
}
