import type { ComputedRef, Ref } from 'vue'

import { api } from '../../lib/api'
import type { AuthSession } from '../../types/awards'
import type { AuthStore } from '../../stores/auth'
import type { AwardsStore } from '../../stores/awards'
import type { HomeDisplayCategory } from './homeLandingTypes'

export function useHomeParticipationSessionActions(params: {
  store: AwardsStore
  authStore: AuthStore
  routerPush: (path: string) => Promise<unknown>
  displayCategories: ComputedRef<HomeDisplayCategory[]>
  votes: Ref<Record<string, number>>
  savedVoteCount: Ref<number>
  formError: Ref<string>
  deleteConfirm: Ref<boolean>
  accountActionError: Ref<string>
  clipDsgvo: Ref<boolean>
  closeAccountModal: () => void
}) {
  const {
    store,
    authStore,
    routerPush,
    displayCategories,
    votes,
    savedVoteCount,
    formError,
    deleteConfirm,
    accountActionError,
    clipDsgvo,
    closeAccountModal,
  } = params

  async function ensureViewerSession(): Promise<AuthSession> {
    if (authStore.session) return authStore.session

    await authStore.login({
      twitchUserId: 'local_user',
      displayName: 'Local User',
      role: 'viewer',
    })

    if (!authStore.session) {
      throw new Error('Eine aktive Session konnte nicht erstellt werden.')
    }

    return authStore.session
  }

  async function loadMyParticipation() {
    if (!authStore.session || !store.overview.year) return
    try {
      const participation = await api.getMyParticipation(store.overview.year)
      const nextVotes: Record<string, number> = {}
      for (const vote of participation.votes) {
        const category = displayCategories.value.find((item) => Number(item.id) === vote.categoryId)
        const candidateIndex = category?.candidates.findIndex((candidate) => candidate.id === vote.candidateId) ?? -1
        if (category && candidateIndex >= 0) {
          nextVotes[category.id] = candidateIndex
        }
      }
      votes.value = nextVotes
      savedVoteCount.value = Object.keys(nextVotes).length
    } catch {
      votes.value = {}
      savedVoteCount.value = 0
    }
  }

  async function onLogin() {
    formError.value = ''
    await ensureViewerSession()
    await loadMyParticipation()
  }

  async function onLogout() {
    await authStore.logout()
    closeAccountModal()
    deleteConfirm.value = false
    accountActionError.value = ''
    clipDsgvo.value = false
    votes.value = {}
    savedVoteCount.value = 0
    await routerPush('/login')
  }

  async function onConfirmDelete() {
    accountActionError.value = ''
    try {
      await authStore.deleteMyData()
      closeAccountModal()
      deleteConfirm.value = false
      clipDsgvo.value = false
      votes.value = {}
      savedVoteCount.value = 0
      await store.loadHomeData()
      await routerPush('/login')
    } catch (error) {
      accountActionError.value = error instanceof Error ? error.message : 'Deine Daten konnten gerade nicht gelöscht werden.'
    }
  }

  async function openAdminPanel(event?: Event) {
    event?.preventDefault()
    await routerPush(authStore.isAdmin ? '/admin' : '/login?redirect=/admin')
  }

  return {
    ensureViewerSession,
    loadMyParticipation,
    onLogin,
    onLogout,
    onConfirmDelete,
    openAdminPanel,
  }
}
