"use client"

import { create } from "zustand"
import {
  DEMO_AGENDA_CALENDARS,
  createInitialDemoAgendaEvents,
} from "@/components/demo/demo-agenda-data"
import { dateKey, parseICSDate } from "@/lib/agenda/agenda-date"
import type { AgendaApiEvent, AgendaCalendar } from "@/lib/agenda/agenda-types"

type DemoAgendaStoreState = {
  calendars: AgendaCalendar[]
  events: AgendaApiEvent[]
  version: number
}

type DemoAgendaStoreActions = {
  reset: () => void
  bump: () => void
  listCalendars: () => AgendaCalendar[]
  listEvents: (calendarId: string, from: string, to: string) => AgendaApiEvent[]
  upsertEvent: (calendarId: string, event: AgendaApiEvent) => void
  deleteEvent: (path: string) => void
}

function calendarPathPrefix(calendarId: string): string {
  return `/calendars/${calendarId}/`
}

export const useDemoAgendaStore = create<DemoAgendaStoreState & DemoAgendaStoreActions>(
  (set, get) => ({
    calendars: DEMO_AGENDA_CALENDARS,
    events: createInitialDemoAgendaEvents(),
    version: 0,

    reset: () =>
      set({
        calendars: DEMO_AGENDA_CALENDARS,
        events: createInitialDemoAgendaEvents(),
        version: get().version + 1,
      }),

    bump: () => set({ version: get().version + 1 }),

    listCalendars: () => get().calendars,

    listEvents: (calendarId, from, to) => {
      const prefix = calendarPathPrefix(calendarId)
      return get().events.filter((event) => {
        if (!event.path?.startsWith(prefix)) return false
        const start = parseICSDate(event.start)
        if (!start) return false
        const startKey = dateKey(start)
        return startKey >= from && startKey <= to
      })
    },

    upsertEvent: (calendarId, event) => {
      set((state) => {
        const path =
          event.path ?? `${calendarPathPrefix(calendarId)}${event.uid}.ics`
        const next = state.events.filter((e) => e.path !== path)
        next.push({ ...event, path })
        return { events: next, version: state.version + 1 }
      })
    },

    deleteEvent: (path) => {
      set((state) => ({
        events: state.events.filter((e) => e.path !== path),
        version: state.version + 1,
      }))
    },
  })
)
