const STORAGE_KEY = 'ten-minute-planner-state'

function readStorageState() {
  if (typeof window === 'undefined') {
    return {}
  }

  try {
    return JSON.parse(window.localStorage.getItem(STORAGE_KEY) ?? '{}')
  } catch (error) {
    console.warn('저장된 플래너 상태를 불러오지 못했습니다.', error)
    return {}
  }
}

export function readPlannerStorageState() {
  return readStorageState()
}

export function createInitialPlannerRecords(seedRecords, normalizeRecord) {
  const baseRecords = Object.fromEntries(
    Object.entries(seedRecords).map(([key, record]) => [key, normalizeRecord(record)]),
  )

  const savedState = readStorageState()
  const savedRecords = savedState.records ?? {}

  Object.entries(savedRecords).forEach(([key, record]) => {
    baseRecords[key] = normalizeRecord(record)
  })

  return baseRecords
}

export function restorePlannerUiState({
  selectedDate,
  calendarViewDate,
  statsRangeStart,
  statsRangeEnd,
  toDateValue,
}) {
  const savedState = readStorageState()
  selectedDate.value = toDateValue(new Date(), selectedDate.value)
  calendarViewDate.value = new Date(selectedDate.value)

  if (savedState.statsRangeStart) {
    statsRangeStart.value = savedState.statsRangeStart
  }

  if (savedState.statsRangeEnd) {
    statsRangeEnd.value = savedState.statsRangeEnd
  }
}

export function persistPlannerState({
  plannerRecords,
  selectedDate,
  calendarViewDate,
  statsRangeStart,
  statsRangeEnd,
  includeRecords = true,
}) {
  if (typeof window === 'undefined') {
    return
  }

  const previousState = readStorageState()
  const nextState = {
    ...previousState,
    statsRangeStart,
    statsRangeEnd,
  }

  delete nextState.selectedDate
  delete nextState.calendarViewDate

  if (includeRecords) {
    nextState.records = Object.fromEntries(
      Object.entries(plannerRecords).map(([key, record]) => [
        key,
        {
          ...record,
          tasks: record.tasks.map((task) => ({ ...task })),
          memo: record.memo.map((item) => ({ ...item })),
          timetable: [...record.timetable],
        },
      ]),
    )
  }

  window.localStorage.setItem(
    STORAGE_KEY,
    JSON.stringify(nextState),
  )
}
