/**
 * Daily reminder — uses Firebase Cloud Messaging (FCM) for true push notifications.
 * Works even when the browser is fully closed (on mobile PWA).
 *
 * Flow:
 *  1. User picks a time in Settings → enableReminder() is called
 *  2. Browser notification permission is requested
 *  3. FCM token is fetched via the firebase-messaging-sw.js service worker
 *  4. Token + reminder settings are saved to the backend
 *  5. Backend scheduler sends a push at the right time each day
 */
import { getToken, onMessage } from 'firebase/messaging'
import { messagingPromise } from '../lib/firebase'
import { saveFcmToken, saveReminderSettings } from './reminderApi'

const VAPID_KEY = import.meta.env.VITE_FIREBASE_VAPID_KEY

export const REMINDER_TIME_KEY = 'gj-reminder-time'
export const REMINDER_ENABLED_KEY = 'gj-reminder-enabled'

export function getSavedReminderTime(): string | null {
  return localStorage.getItem(REMINDER_TIME_KEY)
}

export function isReminderEnabled(): boolean {
  return localStorage.getItem(REMINDER_ENABLED_KEY) === 'true'
}

/** Get FCM token using the existing sw.js (which includes Firebase messaging). */
async function getFcmToken(): Promise<string | null> {
  const messaging = await messagingPromise
  if (!messaging) {
    console.warn('[FCM] Firebase Messaging not supported in this browser')
    return null
  }

  const swReg = await navigator.serviceWorker.ready
  // console.log('[FCM] Service worker ready:', swReg.active?.scriptURL)

  const token = await getToken(messaging, { vapidKey: VAPID_KEY, serviceWorkerRegistration: swReg })
  if (token) {
    // console.log('[FCM] Token obtained:', token.slice(0, 20) + '…')
  } else {
    console.warn('[FCM] getToken returned empty — VAPID key wrong or SW not registered?')
  }
  return token
}

/**
 * Request permission, get FCM token, and save reminder settings to backend.
 * Returns an error string on failure, or null on success.
 */
export async function enableReminder(
  timeStr: string,
  userId: string,
  authToken: string
): Promise<string | null> {
  if (!('Notification' in window)) {
    return 'Notifications are not supported in this browser.'
  }

  let perm = Notification.permission
  if (perm === 'default') {
    perm = await Notification.requestPermission()
  }
  if (perm !== 'granted') {
    return 'Permission denied. To enable reminders, allow notifications for this site in your browser settings.'
  }

  try {
    const fcmToken = await getFcmToken()
    if (!fcmToken) {
      return 'Push notifications are not supported in this browser. Try Chrome or Edge.'
    }

    const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone
    // console.log('[FCM] Saving token and reminder settings:', { timeStr, timezone })

    await saveFcmToken(userId, fcmToken, authToken)
    // console.log('[FCM] Token saved to backend')

    await saveReminderSettings(userId, { time: timeStr, enabled: true, timezone }, authToken)
    // console.log('[FCM] Reminder settings saved to backend')

    localStorage.setItem(REMINDER_TIME_KEY, timeStr)
    localStorage.setItem(REMINDER_ENABLED_KEY, 'true')
    return null
  } catch (err) {
    const msg = err instanceof Error ? err.message : String(err)
    console.error('[FCM] Reminder setup failed:', msg)
    return `Failed to set up reminder: ${msg}`
  }
}

/** Pause the reminder (keeps the saved time). */
export async function disableReminder(userId: string, authToken: string): Promise<void> {
  await saveReminderSettings(userId, { enabled: false }, authToken)
  localStorage.setItem(REMINDER_ENABLED_KEY, 'false')
}

/** Re-enable using the previously saved time. Returns error string or null. */
export async function reenableReminder(userId: string, authToken: string): Promise<string | null> {
  const time = localStorage.getItem(REMINDER_TIME_KEY)
  if (!time) return 'No reminder time saved.'
  return enableReminder(time, userId, authToken)
}

/**
 * Listen for foreground FCM messages and show a manual notification.
 * Call once after the app mounts. Returns an unsubscribe function.
 */
export async function listenForegroundMessages(): Promise<() => void> {
  const messaging = await messagingPromise
  if (!messaging) return () => {}

  // console.log('[FCM] Foreground message listener registered')

  const unsubscribe = onMessage(messaging, (payload) => {
    // console.log('[FCM] Foreground message received:', payload)
    const title = payload.notification?.title || 'Grateful Journal 🌱'
    const body = payload.notification?.body || "You haven't written today yet."
    if (Notification.permission !== 'granted') {
      console.warn('[FCM] Notification permission not granted — cannot show notification')
      return
    }
    new Notification(title, {
      body,
      icon: '/web-app-manifest-192x192.png',
      tag: 'gj-daily-reminder',
    })
  })

  return unsubscribe
}
