import { ref } from 'vue'
import { getRecentDigests, getDueReminders, snoozeReminder, dismissReminder } from '@/api/memory'

function formatDateKey(date: Date) {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

export function useDailyDigest() {
  const dailyDigest = ref<any>(null)
  const digestLoading = ref(false)
  const recentDigests = ref<any[]>([])
  const activeReminder = ref<any>(null)
  const reminderVisible = ref(false)
  let reminderPollTimer: ReturnType<typeof setInterval> | null = null

  async function loadDailyDigest() {
    digestLoading.value = true
    try {
      const today = formatDateKey(new Date())
      const response = await getRecentDigests(6)
      const items = response.data?.items ?? []
      recentDigests.value = items
      dailyDigest.value = items.find((item: any) => item.date === today) ?? null
    } catch (err) {
      console.warn('Failed to load daily digest:', err)
      recentDigests.value = []
      dailyDigest.value = null
    } finally {
      digestLoading.value = false
    }
  }

  async function pollDueReminders() {
    try {
      const response = await getDueReminders()
      if (response.data?.items?.length > 0) {
        activeReminder.value = response.data.items[0]
        reminderVisible.value = true
      } else {
        reminderVisible.value = false
      }
    } catch (err) {
      console.warn('Failed to poll due reminders:', err)
    }
  }

  async function handleSnooze(id: string, minutes: number) {
    try {
      await snoozeReminder(id, minutes)
      reminderVisible.value = false
      setTimeout(pollDueReminders, minutes * 60 * 1000)
    } catch (err) {
      console.warn('Failed to snooze reminder:', err)
    }
  }

  async function handleDismiss(id: string) {
    try {
      await dismissReminder(id)
      reminderVisible.value = false
    } catch (err) {
      console.warn('Failed to dismiss reminder:', err)
    }
  }

  return {
    dailyDigest, digestLoading, recentDigests,
    activeReminder, reminderVisible, reminderPollTimer,
    loadDailyDigest, pollDueReminders, handleSnooze, handleDismiss
  }
}
