import type { AppStateV1, LearningGoal, LearningTask } from './types'

export function createId(): string {
  if (globalThis.crypto?.randomUUID) return globalThis.crypto.randomUUID()
  return `lp-${Date.now()}-${Math.random().toString(16).slice(2)}`
}

export function goalProgress(goalId: string, tasks: LearningTask[]): number {
  const matching = tasks.filter((task) => task.goalId === goalId)
  if (!matching.length) return 0
  return Math.round((matching.filter((task) => task.status === 'done').length / matching.length) * 100)
}

export function dashboardStats(state: AppStateV1) {
  const completed = state.tasks.filter((task) => task.status === 'done').length
  const active = state.tasks.filter((task) => task.status === 'in-progress').length
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  const nextWeek = new Date(today)
  nextWeek.setDate(today.getDate() + 7)
  const dueSoon = state.tasks.filter((task) => {
    if (task.status === 'done' || !task.dueDate) return false
    const due = new Date(`${task.dueDate}T00:00:00`)
    return due >= today && due <= nextWeek
  }).length

  return {
    goals: state.goals.length,
    completed,
    active,
    dueSoon,
    totalMinutes: state.tasks.reduce((sum, task) => sum + task.estimatedMinutes, 0),
  }
}

export function sortedUpcoming(tasks: LearningTask[]): LearningTask[] {
  return [...tasks]
    .filter((task) => task.status !== 'done' && task.dueDate)
    .sort((a, b) => a.dueDate.localeCompare(b.dueDate))
}

export function goalForTask(task: LearningTask, goals: LearningGoal[]): LearningGoal | undefined {
  return goals.find((goal) => goal.id === task.goalId)
}

export function formatDate(date: string): string {
  if (!date) return 'No date'
  return new Intl.DateTimeFormat('en-GB', { day: 'numeric', month: 'short', year: 'numeric' }).format(
    new Date(`${date}T00:00:00`),
  )
}
