import { autocompletion, type CompletionContext, type CompletionResult } from "@codemirror/autocomplete"
import { DateTime } from "luxon"

const getDateOptions = () => {
  const today = DateTime.local()

  const createDateOption = (label: string, date: DateTime) => {
    const detail = date.toFormat("ccc, LLL d")
    const apply = date.toFormat("M/dd/yyyy")
    return { label: `${label}: `, detail, apply }
  }

  const options = [
    createDateOption("today", today),
    createDateOption("tomorrow", today.plus({ days: 1 })),
    createDateOption("next week", today.plus({ days: 7 })),
    createDateOption("next month", today.plus({ months: 1 })),
  ]

  // Add remaining days of the current week (starting from day after tomorrow)
  const currentWeekday = today.weekday // 1 = Monday, 7 = Sunday
  const weekdayNames = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]

  // Add the next 5 days of the week
  for (let i = 1; i <= 6; i++) {
    const nextDay = today.plus({ days: i })
    const nameIndex = (currentWeekday + i - 1) % 7
    options.push(createDateOption(weekdayNames[nameIndex]!, nextDay))
  }

  return options
}

// Completion function that triggers after @
const dateCompletion = (context: CompletionContext) => {
  const { state, pos } = context
  const line = state.doc.lineAt(pos)
  const lineText = line.text
  const linePos = pos - line.from

  // Find the last @ symbol before cursor position
  let atPos = -1
  for (let i = linePos - 1; i >= 0; i--) {
    if (lineText[i] === "@") {
      atPos = i
      break
    } else if (lineText[i] === " ") {
      // Stop if we hit a space before finding @
      break
    }
  }

  // Only complete if we found @ and cursor is right after it or after some text following @
  if (atPos === -1) {
    return
  }

  const textAfterAt = lineText.slice(atPos + 1, linePos)

  // Get all date options
  const options = getDateOptions()

  // Filter options based on what's typed after @
  const filteredOptions = options.filter((option) =>
    option.label.toLowerCase().startsWith(textAfterAt.toLowerCase())
  )

  return {
    from: line.from + atPos + 1, // Start after the @
    filter: false,
    options: filteredOptions.map((option) => ({
      label: option.label,
      detail: option.detail,
      apply: option.apply,
    })),
  }
}

export const dateAutocompletion = autocompletion({
  override: [dateCompletion],
  activateOnTyping: true,
})
