/**
 * TabataFit Notification Hook
 * Manages daily reminder scheduling via expo-notifications
 */

import { useEffect } from 'react'
import * as Notifications from 'expo-notifications'
import { useUserStore } from '@/src/shared/stores'
import i18n from '@/src/shared/i18n'

const REMINDER_ID = 'daily-reminder'

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

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

async function scheduleDaily(time: string) {
  await Notifications.cancelAllScheduledNotificationsAsync()

  const [hour, minute] = time.split(':').map(Number)

  await Notifications.scheduleNotificationAsync({
    identifier: REMINDER_ID,
    content: {
      title: i18n.t('notifications:dailyReminder.title'),
      body: i18n.t('notifications:dailyReminder.body'),
      sound: true,
    },
    trigger: {
      type: Notifications.SchedulableTriggerInputTypes.DAILY,
      hour,
      minute,
    },
  })
}

async function cancelAll() {
  await Notifications.cancelAllScheduledNotificationsAsync()
}

export function useNotifications() {
  const reminders = useUserStore((s) => s.settings.reminders)
  const reminderTime = useUserStore((s) => s.settings.reminderTime)

  useEffect(() => {
    if (reminders) {
      scheduleDaily(reminderTime)
    } else {
      cancelAll()
    }
  }, [reminders, reminderTime])
}
