import * as Notifications from 'expo-notifications';
import { Platform } from 'react-native';
import { Plant } from '../types';

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

export async function requestPermissions(): Promise<boolean> {
  const { status: existing } = await Notifications.getPermissionsAsync();
  if (existing === 'granted') return true;

  const { status } = await Notifications.requestPermissionsAsync();
  return status === 'granted';
}

export async function scheduleWateringReminder(plant: Plant): Promise<void> {
  const intervalDays = plant.careInfo.waterIntervalDays;

  await Notifications.scheduleNotificationAsync({
    identifier: `water-${plant.id}`,
    content: {
      title: 'Watering Reminder 💧',
      body: `Time to water your ${plant.name}!`,
      data: { plantId: plant.id },
    },
    trigger: {
      type: Notifications.SchedulableTriggerInputTypes.TIME_INTERVAL,
      seconds: intervalDays * 24 * 60 * 60,
      repeats: true,
    },
  });
}

export async function cancelReminder(plantId: string): Promise<void> {
  await Notifications.cancelScheduledNotificationAsync(`water-${plantId}`);
}
