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

import AdminPageHeader from '../../components/admin/AdminPageHeader.vue'
import AdminReleaseNotesCard from '../../components/admin/AdminReleaseNotesCard.vue'
import AdminSettingsDatabaseCard from '../../components/admin/AdminSettingsDatabaseCard.vue'
import AdminSettingsOverviewBoard from '../../components/admin/AdminSettingsOverviewBoard.vue'
import AdminSessionTimeoutCard from '../../components/admin/AdminSessionTimeoutCard.vue'
import AdminTwitchAuthCard from '../../components/admin/AdminTwitchAuthCard.vue'
import { watchAdminErrorToast, watchAdminToast } from '../../composables/useAdminToast'
import Button from '../../components/ui/Button.vue'
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 {
  operationalSaving,
  operationalError,
  operationalSuccess,
  operationalForm,
  twitchClientSecretSet,
  twitchAuthConfigured,
  twitchAuthManagedByDatabase,
  twitchClientSecretInput,
  twitchSecretHint,
  twitchAuthComplete,
  hasUnsavedOperationalChanges,
  saveOperationalSettings,
} = useAdminOperationalSettings()

watchAdminToast(operationalSuccess, operationalError)
watchAdminErrorToast(healthError)

function hasUnsavedSettingsChanges() {
  return hasUnsavedOperationalChanges.value
}

function confirmDiscardSettingsChanges() {
  if (!hasUnsavedSettingsChanges()) {
    return true
  }

  return window.confirm('Du hast ungespeicherte Änderungen in den Einstellungen. Änderungen verwerfen?')
}

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

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

<template>
  <div class="space-y-6">
    <AdminPageHeader
      eyebrow="Einstellungen"
      description="Übersicht, Twitch-Konfiguration, Session-Timeout und Systemstatus."
      :icon="Settings"
    />

    <div class="flex justify-end">
      <Button class="gap-2 rounded-2xl px-5" :disabled="operationalSaving || !canManageOperationalSettings || !hasUnsavedOperationalChanges" @click="saveOperationalSettings">
        <Save class="h-4 w-4" />
        {{ operationalSaving ? 'Speichert ...' : 'Kern-Einstellungen speichern' }}
      </Button>
    </div>

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

    <AdminReleaseNotesCard />

    <AdminTwitchAuthCard
      :form="operationalForm"
      :saving="operationalSaving"
      :can-manage="canManageOperationalSettings"
      :twitch-client-secret="twitchClientSecretInput"
      :twitch-secret-hint="twitchSecretHint"
      :twitch-client-secret-set="twitchClientSecretSet"
      :twitch-auth-configured="twitchAuthConfigured"
      :twitch-auth-managed-by-database="twitchAuthManagedByDatabase"
      :twitch-auth-complete="twitchAuthComplete"
      @save="saveOperationalSettings"
      @update:twitch-client-secret="twitchClientSecretInput = $event"
    />

    <AdminSessionTimeoutCard
      :form="operationalForm"
      :saving="operationalSaving"
      :can-manage="canManageOperationalSettings"
    />

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