"use client"

import { useEffect, useMemo, useRef } from "react"
import { useAgendaCalendars } from "@/lib/api/hooks/use-calendar-queries"
import { useMailAccounts } from "@/lib/api/hooks/use-mail-queries"
import {
  filterAgendaCalendars,
  mergeAgendaCalendars,
  resolveActiveCalendarView,
  resolveVisibleCalendarIds,
} from "@/lib/agenda/agenda-calendar-visibility"
import { useAgendaSettingsStore } from "@/lib/agenda/agenda-store"
import type { AgendaCalendar } from "@/lib/agenda/agenda-types"

export function useMergedAgendaCalendars() {
  const externalCalendars = useAgendaSettingsStore((s) => s.externalCalendars)
  const { data: apiCalendars = [], isLoading, isError } = useAgendaCalendars()

  const calendars = useMemo(
    () => mergeAgendaCalendars(apiCalendars, externalCalendars),
    [apiCalendars, externalCalendars],
  )

  return { calendars, apiCalendars, externalCalendars, isLoading, isError }
}

export function useVisibleAgendaCalendars() {
  const hiddenCalendarIds = useAgendaSettingsStore((s) => s.hiddenCalendarIds)
  const accountEnabledCalendarIds = useAgendaSettingsStore(
    (s) => s.accountEnabledCalendarIds,
  )
  const calendarViews = useAgendaSettingsStore((s) => s.calendarViews)
  const activeCalendarViewId = useAgendaSettingsStore((s) => s.activeCalendarViewId)
  const defaultCalendarViewId = useAgendaSettingsStore((s) => s.defaultCalendarViewId)
  const setActiveCalendarViewId = useAgendaSettingsStore(
    (s) => s.setActiveCalendarViewId,
  )
  const { data: accounts = [] } = useMailAccounts()
  const { calendars, apiCalendars, externalCalendars, isLoading, isError } =
    useMergedAgendaCalendars()

  const accountIds = useMemo(() => accounts.map((account) => account.id), [accounts])

  const activeView = useMemo(
    () => resolveActiveCalendarView(calendarViews, activeCalendarViewId),
    [calendarViews, activeCalendarViewId],
  )

  const defaultViewApplied = useRef(false)

  useEffect(() => {
    if (defaultViewApplied.current) return
    if (activeCalendarViewId !== null) {
      defaultViewApplied.current = true
      return
    }
    if (!defaultCalendarViewId) {
      defaultViewApplied.current = true
      return
    }
    const exists = calendarViews.some((view) => view.id === defaultCalendarViewId)
    if (exists) setActiveCalendarViewId(defaultCalendarViewId)
    defaultViewApplied.current = true
  }, [
    activeCalendarViewId,
    calendarViews,
    defaultCalendarViewId,
    setActiveCalendarViewId,
  ])

  const visibleIds = useMemo(
    () =>
      resolveVisibleCalendarIds({
        allCalendars: [
          ...apiCalendars.map((calendar) => ({
            id: calendar.id,
            account_id: null as string | null,
          })),
          ...externalCalendars.map((calendar) => ({
            id: calendar.id,
            account_id: calendar.account_id,
          })),
        ],
        hiddenCalendarIds,
        accountIds,
        accountEnabledCalendarIds,
        activeView,
      }),
    [
      apiCalendars,
      externalCalendars,
      hiddenCalendarIds,
      accountIds,
      accountEnabledCalendarIds,
      activeView,
    ],
  )

  const visibleCalendars = useMemo(
    () => filterAgendaCalendars(calendars, visibleIds),
    [calendars, visibleIds],
  )

  return {
    calendars,
    visibleCalendars,
    visibleIds,
    activeView,
    activeCalendarViewId,
    calendarViews,
    isLoading,
    isError,
  }
}

export function useAgendaCalendarOptions(): AgendaCalendar[] {
  const { calendars } = useMergedAgendaCalendars()
  return calendars
}
