"use client"

import { useMemo } from "react"
import { useCurrentUser } from "@/lib/api/hooks/use-current-user"
import { useMailSettingsStore } from "@/lib/stores/mail-settings-store"
import {
  DEFAULT_AGENDA_ORG_SETTINGS,
  DEFAULT_AGENDA_USER_SETTINGS,
} from "@/lib/agenda/agenda-settings-defaults"
import type {
  AgendaOrgAgendaPublic,
  AgendaUserSettings,
  AgendaVideoProvider,
} from "@/lib/agenda/agenda-settings-types"
import {
  migrateAutoImportIdentityKeys,
  normalizeAutoImportInvitationSources,
} from "@/lib/agenda/agenda-destination-identities"
import { useAgendaSettingsStore } from "@/lib/agenda/agenda-store"

export type EffectiveAgendaSettings = AgendaUserSettings & {
  themeMode: ReturnType<typeof useMailSettingsStore.getState>["themeMode"]
  orgEnforcesTheme: boolean
  orgEnforcesVideoProvider: boolean
}

const DEFAULT_ORG_AGENDA_PUBLIC: AgendaOrgAgendaPublic = {
  default_theme_mode: DEFAULT_AGENDA_ORG_SETTINGS.default_theme_mode,
  enforce_org_theme: false,
  default_video_provider: DEFAULT_AGENDA_ORG_SETTINGS.default_video_provider,
  enforce_org_video_provider: false,
  configured_video_providers: ["ultimeet"],
}

function normalizeUserSettings(raw: Partial<AgendaUserSettings> & {
  autoImportInvitationIdentityKeys?: string[]
}): AgendaUserSettings {
  const base = { ...DEFAULT_AGENDA_USER_SETTINGS, ...raw }
  const autoImportInvitationSources =
    base.autoImportInvitationSources ??
    (raw.autoImportInvitationIdentityKeys
      ? migrateAutoImportIdentityKeys(raw.autoImportInvitationIdentityKeys)
      : DEFAULT_AGENDA_USER_SETTINGS.autoImportInvitationSources)
  const start = clampMinutes(base.visibleHoursStart, 0, 23 * 60 + 59)
  let end = clampMinutes(base.visibleHoursEnd, 0, 23 * 60 + 59)
  if (end < start) end = start
  return {
    ...base,
    autoImportInvitationSources: normalizeAutoImportInvitationSources(
      autoImportInvitationSources,
    ),
    visibleHoursStart: start,
    visibleHoursEnd: end,
    defaultQuickDurationMinutes: Math.max(5, base.defaultQuickDurationMinutes),
  }
}

function clampMinutes(value: number, min: number, max: number): number {
  if (!Number.isFinite(value)) return min
  return Math.min(max, Math.max(min, Math.round(value)))
}

export function useEffectiveAgendaSettings(): EffectiveAgendaSettings {
  const defaultVideoProvider = useAgendaSettingsStore((s) => s.defaultVideoProvider)
  const videoProviderApiKeys = useAgendaSettingsStore((s) => s.videoProviderApiKeys)
  const defaultInvitationIdentityKey = useAgendaSettingsStore(
    (s) => s.defaultInvitationIdentityKey,
  )
  const autoImportInvitationSources = useAgendaSettingsStore(
    (s) => s.autoImportInvitationSources,
  )
  const invitationImportExclusions = useAgendaSettingsStore(
    (s) => s.invitationImportExclusions,
  )
  const weekStart = useAgendaSettingsStore((s) => s.weekStart)
  const defaultQuickDurationMinutes = useAgendaSettingsStore(
    (s) => s.defaultQuickDurationMinutes,
  )
  const visibleHoursStart = useAgendaSettingsStore((s) => s.visibleHoursStart)
  const visibleHoursEnd = useAgendaSettingsStore((s) => s.visibleHoursEnd)
  const timeFormat = useAgendaSettingsStore((s) => s.timeFormat)
  const dragSnapMinutes = useAgendaSettingsStore((s) => s.dragSnapMinutes)
  const buttonSnapMinutes = useAgendaSettingsStore((s) => s.buttonSnapMinutes)
  const themeMode = useMailSettingsStore((s) => s.themeMode)
  const { data: user } = useCurrentUser()

  const org = user?.org_agenda ?? DEFAULT_ORG_AGENDA_PUBLIC
  const orgEnforcesTheme = org.enforce_org_theme
  const orgEnforcesVideoProvider = org.enforce_org_video_provider
  const orgDefaultTheme = org.default_theme_mode
  const orgDefaultVideoProvider = org.default_video_provider

  return useMemo(() => {
    const normalized = normalizeUserSettings({
      defaultVideoProvider,
      videoProviderApiKeys,
      defaultInvitationIdentityKey,
      autoImportInvitationSources,
      invitationImportExclusions,
      weekStart,
      defaultQuickDurationMinutes,
      visibleHoursStart,
      visibleHoursEnd,
      timeFormat,
      dragSnapMinutes,
      buttonSnapMinutes,
    })
    const provider: AgendaVideoProvider = orgEnforcesVideoProvider
      ? orgDefaultVideoProvider
      : normalized.defaultVideoProvider

    return {
      ...normalized,
      defaultVideoProvider: provider,
      themeMode: orgEnforcesTheme ? orgDefaultTheme : themeMode,
      orgEnforcesTheme,
      orgEnforcesVideoProvider,
    }
  }, [
    defaultVideoProvider,
    videoProviderApiKeys,
    defaultInvitationIdentityKey,
    autoImportInvitationSources,
    invitationImportExclusions,
    weekStart,
    defaultQuickDurationMinutes,
    visibleHoursStart,
    visibleHoursEnd,
    timeFormat,
    dragSnapMinutes,
    buttonSnapMinutes,
    themeMode,
    orgEnforcesTheme,
    orgEnforcesVideoProvider,
    orgDefaultTheme,
    orgDefaultVideoProvider,
  ])
}
