import { watch, type ComputedRef, type Ref } from 'vue'

import type { AuthStore } from '../../stores/auth'
import type { AwardsStore } from '../../stores/awards'
import type { HomeDisplayCategory, HomeInteractionModalKind, HomePreviewPhase, HomeSuccessKind } from './homeLandingTypes'
import { useHomeParticipationSessionActions } from './useHomeParticipationSessionActions'
import { useHomeParticipationSubmitActions } from './useHomeParticipationSubmitActions'

export function useHomeParticipationActions(params: {
  store: AwardsStore
  authStore: AuthStore
  routerPush: (path: string) => Promise<unknown>
  twitchUser: ComputedRef<string>
  displayCategories: ComputedRef<HomeDisplayCategory[]>
  archiveYears: ComputedRef<Array<{ year: number }>>
  archiveYear: Ref<number>
  previewPhase: Ref<HomePreviewPhase>
  activeCat: Ref<number>
  deleteConfirm: Ref<boolean>
  accountActionError: Ref<string>
  openModal: (kind: HomeInteractionModalKind) => void
  closeAccountModal: () => void
  votes: Ref<Record<string, number>>
  savedVoteCount: Ref<number>
  submitted: Ref<boolean>
  submitting: Ref<boolean>
  formError: Ref<string>
  successKind: Ref<null | HomeSuccessKind>
  clipCatIdx: Ref<number>
  clipDsgvo: Ref<boolean>
  clipSubmissionsEnabled: ComputedRef<boolean>
  clipSubmissionDisabledMessage: ComputedRef<string>
}) {
  const {
    store,
    authStore,
    routerPush,
    twitchUser,
    displayCategories,
    archiveYears,
    archiveYear,
    previewPhase,
    activeCat,
    deleteConfirm,
    accountActionError,
    openModal,
    closeAccountModal,
    votes,
    savedVoteCount,
    submitted,
    submitting,
    formError,
    successKind,
    clipCatIdx,
    clipDsgvo,
    clipSubmissionsEnabled,
    clipSubmissionDisabledMessage,
  } = params

  const {
    ensureViewerSession,
    loadMyParticipation,
    onLogin,
    onLogout,
    onConfirmDelete,
    openAdminPanel,
  } = useHomeParticipationSessionActions({
    store,
    authStore,
    routerPush,
    displayCategories,
    votes,
    savedVoteCount,
    formError,
    deleteConfirm,
    accountActionError,
    clipDsgvo,
    closeAccountModal,
  })
  const {
    setCat,
    pickNominee,
    submitVote,
    submitReminder,
    submitNomination,
    clipDsgvoChange,
    onClipCatChange,
    submitClip,
  } = useHomeParticipationSubmitActions({
    store,
    displayCategories,
    activeCat,
    previewPhase,
    votes,
    savedVoteCount,
    submitted,
    submitting,
    formError,
    successKind,
    clipCatIdx,
    clipDsgvo,
    ensureViewerSession,
    loadMyParticipation,
    fallbackCreatorName: twitchUser,
    clipSubmissionsEnabled,
    clipSubmissionDisabledMessage,
  })

  async function initializeHomeInteractions() {
    syncPreviewPhaseFromOverview()
    await loadMyParticipation()
    archiveYear.value = archiveYears.value[0]?.year ?? store.overview.year - 1
  }

  function onPrimaryPhaseAction(event?: Event) {
    if (previewPhase.value === 'nomination') {
      event?.preventDefault()
      openModal('nominate')
      return
    }
    if (previewPhase.value === 'voting') {
      event?.preventDefault()
      openModal('vote')
      return
    }
    if (previewPhase.value === 'preparation') {
      event?.preventDefault()
      return
    }
  }

  function onSectionAction(event?: Event) {
    onPrimaryPhaseAction(event)
  }

  function onTimelineFinalAction(event?: Event) {
    if (previewPhase.value === 'show') return
    event?.preventDefault()
    openModal('show')
  }

  function syncPreviewPhaseFromOverview() {
    const activeTimelineItem = store.overview.timeline.find((entry) => entry.state === 'active')
    if (isHomePreviewPhaseKey(activeTimelineItem?.key)) {
      previewPhase.value = activeTimelineItem.key
      return
    }

    if (isCompletedPhase(store.overview.currentPhase)) {
      previewPhase.value = 'completed'
    }
  }

  watch(displayCategories, (categories) => {
    if (activeCat.value >= categories.length) {
      activeCat.value = 0
    }
    if (clipCatIdx.value >= categories.length) {
      clipCatIdx.value = 0
    }
  })

  watch(() => store.overview.currentPhase, () => {
    syncPreviewPhaseFromOverview()
  })

  watch(() => authStore.session?.twitchUserId, () => {
    void loadMyParticipation()
  })

  return {
    initializeHomeInteractions,
    onLogin,
    onLogout,
    onConfirmDelete,
    openAdminPanel,
    setCat,
    pickNominee,
    submitVote,
    submitReminder,
    submitNomination,
    clipDsgvoChange,
    onClipCatChange,
    submitClip,
    onPrimaryPhaseAction,
    onSectionAction,
    onTimelineFinalAction,
    syncPreviewPhaseFromOverview,
  }
}

function isHomePreviewPhaseKey(value: string | undefined): value is HomePreviewPhase {
  return value === 'nomination' || value === 'voting' || value === 'preparation' || value === 'show'
}

function isCompletedPhase(value: string) {
  const normalized = value.trim().toLowerCase()
  return normalized.includes('abgeschlossen') || normalized.includes('archiv') || normalized.includes('complete') || normalized.includes('ended')
}
