<script setup lang="ts">
import { Settings } from '@lucide/vue'
import { computed, onBeforeUnmount, onMounted } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'

import AdminOperationalSettingsCard from '../../components/admin/AdminOperationalSettingsCard.vue'
import AdminPageHeader from '../../components/admin/AdminPageHeader.vue'
import AdminSeasonToolbar from '../../components/admin/AdminSeasonToolbar.vue'
import AdminSettingsDatabaseCard from '../../components/admin/AdminSettingsDatabaseCard.vue'
import AdminSettingsOverviewBoard from '../../components/admin/AdminSettingsOverviewBoard.vue'
import { watchAdminErrorToast, watchAdminToast } from '../../composables/useAdminToast'
import { useAuthStore } from '../../stores/auth'
import { useAdminOperationalSettings } from '../../components/admin/useAdminOperationalSettings'
import { useAdminSettingsOverview } from '../../components/admin/useAdminSettingsOverview'

const authStore = useAuthStore()
const canManageOperationalSettings = computed(() => authStore.canManageOperationalSettings)

const {
  healthLoading,
  healthError,
  databaseHealth,
  pendingMigrationCount,
  healthLoadedLabel,
  contentChecks,
  contentCompletion,
  checks,
  gates,
  refreshDatabaseHealth,
} = useAdminSettingsOverview()

const {
  operationalLoading,
  operationalSaving,
  operationalError,
  operationalSuccess,
  operationalForm,
  demoPasswordSet,
  demoManagedByDatabase,
  demoPasswordInput,
  twitchClientSecretSet,
  twitchAuthConfigured,
  twitchAuthManagedByDatabase,
  twitchClientSecretInput,
  demoPasswordHint,
  twitchSecretHint,
  demoCredentialsComplete,
  twitchAuthComplete,
  operationalSummary,
  hasUnsavedOperationalChanges,
  saveOperationalSettings,
} = useAdminOperationalSettings()

watchAdminToast(operationalSuccess, operationalError)
watchAdminErrorToast(healthError)

function confirmDiscardOperationalChanges() {
  if (!hasUnsavedOperationalChanges.value) {
    return true
  }

  return window.confirm('Du hast ungespeicherte Änderungen in Demo & Wartung. Änderungen verwerfen?')
}

function handleBeforeUnload(event: BeforeUnloadEvent) {
  if (!hasUnsavedOperationalChanges.value) return
  event.preventDefault()
  event.returnValue = ''
}

onBeforeRouteLeave(() => confirmDiscardOperationalChanges())
onMounted(() => window.addEventListener('beforeunload', handleBeforeUnload))
onBeforeUnmount(() => window.removeEventListener('beforeunload', handleBeforeUnload))
</script>

<template>
  <div class="space-y-6">
    <AdminPageHeader
      eyebrow="Einstellungen"
      description="Demo-Zugang, Wartungsmodus und Healthchecks."
      :icon="Settings"
    />

    <AdminSeasonToolbar />

    <AdminSettingsOverviewBoard
      :checks="checks"
      :gates="gates"
      :content-checks="contentChecks"
      :content-completion="contentCompletion"
    />

    <AdminOperationalSettingsCard
      v-model:demo-password="demoPasswordInput"
      v-model:twitch-client-secret="twitchClientSecretInput"
      :form="operationalForm"
      :loading="operationalLoading"
      :saving="operationalSaving"
      :error="operationalError"
      :success="operationalSuccess"
      :demo-password-hint="demoPasswordHint"
      :demo-password-set="demoPasswordSet"
      :demo-managed-by-database="demoManagedByDatabase"
      :demo-credentials-complete="demoCredentialsComplete"
      :twitch-secret-hint="twitchSecretHint"
      :twitch-client-secret-set="twitchClientSecretSet"
      :twitch-auth-configured="twitchAuthConfigured"
      :twitch-auth-managed-by-database="twitchAuthManagedByDatabase"
      :twitch-auth-complete="twitchAuthComplete"
      :summary="operationalSummary"
      :dirty="hasUnsavedOperationalChanges"
      :can-manage="canManageOperationalSettings"
      @save="saveOperationalSettings"
    />

    <AdminSettingsDatabaseCard
      :health-loading="healthLoading"
      :health-error="healthError"
      :database-health="databaseHealth"
      :pending-migration-count="pendingMigrationCount"
      :health-loaded-label="healthLoadedLabel"
      :refresh-database-health="refreshDatabaseHealth"
    />
  </div>
</template>
