<script setup lang="ts">
import { ref } from 'vue'
import { Clock3, KeyRound, Loader2, LockKeyhole, Save, Settings, ShieldCheck, Wrench } from '@lucide/vue'
import { RouterLink } from 'vue-router'

import type { AdminOperationalSettingsForm, AdminSettingsStatusSummary, AdminSettingsTone } from './adminSettingsTypes'
import AdminSettingsToggle from './AdminSettingsToggle.vue'
import Button from '../ui/Button.vue'
import Card from '../ui/Card.vue'
import Modal from '../ui/Modal.vue'
import PasswordField from '../ui/PasswordField.vue'

defineProps<{
  form: AdminOperationalSettingsForm
  loading: boolean
  saving: boolean
  error: string
  success: string
  demoPassword: string
  twitchClientSecret: string
  demoPasswordHint: string
  demoPasswordSet: boolean
  demoManagedByDatabase: boolean
  demoCredentialsComplete: boolean
  twitchSecretHint: string
  twitchClientSecretSet: boolean
  twitchAuthConfigured: boolean
  twitchAuthManagedByDatabase: boolean
  twitchAuthComplete: boolean
  summary: AdminSettingsStatusSummary[]
  dirty: boolean
  canManage: boolean
}>()

const emit = defineEmits<{
  save: []
  'update:demoPassword': [value: string]
  'update:twitchClientSecret': [value: string]
}>()

const twitchModalOpen = ref(false)

function defaultRedirectUri() {
  if (typeof window === 'undefined') {
    return 'https://deine-domain.de/api/auth/twitch/callback'
  }

  return `${window.location.origin.replace(/:\d+$/, ':5084')}/api/auth/twitch/callback`
}

function toneClasses(tone: AdminSettingsTone) {
  if (tone === 'good') {
    return 'border-emerald-100 bg-emerald-50/55 text-emerald-800'
  }

  if (tone === 'warning') {
    return 'border-amber-100 bg-amber-50/70 text-amber-800'
  }

  if (tone === 'danger') {
    return 'border-rose-100 bg-rose-50/70 text-rose-800'
  }

  return 'border-violet-100 bg-violet-50/60 text-violet-800'
}
</script>

<template>
  <Card class="overflow-hidden">
    <div class="border-b border-violet-100 bg-gradient-to-br from-white via-violet-50/70 to-amber-50/60 p-6">
      <div class="flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
        <div>
          <p class="text-xs font-semibold uppercase tracking-[0.24em] text-violet-500">Demo & Wartung</p>
          <h2 class="mt-1 text-xl font-bold text-slate-900">Öffentlichen Zugriff steuern</h2>
          <p class="mt-2 max-w-3xl text-sm leading-6 text-slate-500">
            Demo-Schutz und Wartungsmodus sind echte Betriebs-Schalter. Änderungen werden in der Datenbank gespeichert und sofort für die Public-App verwendet.
          </p>
        </div>
        <Button :disabled="loading || saving || !canManage || !dirty" class="gap-2 rounded-2xl px-5" @click="emit('save')">
          <Loader2 v-if="saving" class="h-4 w-4 animate-spin" />
          <LockKeyhole v-else-if="!canManage" class="h-4 w-4" />
          <Save v-else class="h-4 w-4" />
          {{ saving ? 'Speichert ...' : !canManage ? 'Nur Owner' : dirty ? 'Zugriff speichern' : 'Gespeichert' }}
        </Button>
      </div>
    </div>

    <div v-if="loading" class="flex items-center gap-3 p-6 text-sm font-semibold text-violet-700">
      <Loader2 class="h-4 w-4 animate-spin" />
      Lade Demo- und Wartungseinstellungen ...
    </div>

    <div v-else class="space-y-5 p-5">
      <p
        v-if="!canManage"
        class="flex items-start gap-3 rounded-2xl border border-slate-200 bg-slate-50 px-4 py-3 text-sm font-semibold leading-6 text-slate-700"
      >
        <LockKeyhole class="mt-0.5 h-4 w-4 shrink-0 text-slate-500" />
        Demo-Zugang und Wartungsmodus sind Owner-Controls. Du kannst den Status ansehen, aber nicht bearbeiten.
      </p>
      <p
        v-else-if="dirty"
        class="rounded-2xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm font-semibold text-amber-800"
      >
        Ungespeicherte Änderungen vorhanden. Beim Verlassen der Seite fragt das Panel nach.
      </p>

      <div class="grid gap-3 md:grid-cols-4">
        <div
          v-for="item in summary"
          :key="item.label"
          class="rounded-2xl border px-4 py-3"
          :class="toneClasses(item.tone)"
        >
          <p class="text-[11px] font-semibold uppercase tracking-[0.18em] opacity-80">{{ item.label }}</p>
          <strong class="mt-1 block text-lg text-slate-950">{{ item.value }}</strong>
          <p class="mt-1 text-xs leading-5">{{ item.note }}</p>
        </div>
      </div>

      <section class="rounded-[26px] border border-violet-100 bg-white/85 p-5 shadow-[0_18px_46px_rgba(168,145,214,0.08)]">
        <div class="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
          <div class="flex gap-3">
            <div class="grid h-12 w-12 shrink-0 place-items-center rounded-2xl bg-violet-100 text-violet-700">
              <Settings class="h-5 w-5" />
            </div>
            <div>
              <p class="text-xs font-semibold uppercase tracking-[0.22em] text-violet-500">Twitch OAuth</p>
              <h3 class="mt-1 text-xl font-bold text-slate-900">Offiziellen Twitch Login konfigurieren</h3>
              <p class="mt-1 text-sm leading-6 text-slate-500">
                Einmal mit Client-ID, Client Secret und Redirect URI verbinden. Danach verwenden Login und Account-Verknüpfung den offiziellen Twitch-Flow.
              </p>
              <div class="mt-3 flex flex-wrap gap-2 text-xs font-semibold">
                <span class="rounded-full px-3 py-1" :class="twitchAuthConfigured ? 'bg-emerald-50 text-emerald-700' : 'bg-amber-50 text-amber-700'">
                  {{ twitchAuthConfigured ? 'OAuth bereit' : 'OAuth fehlt' }}
                </span>
                <span class="rounded-full bg-violet-50 px-3 py-1 text-violet-700">
                  {{ twitchAuthManagedByDatabase ? 'Quelle: Datenbank' : 'Quelle: Config' }}
                </span>
                <span class="rounded-full px-3 py-1" :class="twitchClientSecretSet ? 'bg-emerald-50 text-emerald-700' : 'bg-amber-50 text-amber-700'">
                  {{ twitchClientSecretSet ? 'Secret vorhanden' : 'Secret fehlt' }}
                </span>
              </div>
            </div>
          </div>

          <Button
            type="button"
            variant="secondary"
            class="gap-2 rounded-2xl px-5"
            :disabled="loading || saving || !canManage"
            @click="twitchModalOpen = true"
          >
            <LockKeyhole v-if="!canManage" class="h-4 w-4" />
            <Settings v-else class="h-4 w-4" />
            {{ !canManage ? 'Nur Owner' : 'Twitch konfigurieren' }}
          </Button>
        </div>
      </section>

      <div class="grid gap-5 xl:grid-cols-2">
        <section class="rounded-[26px] border border-violet-100 bg-white/85 p-5 shadow-[0_18px_46px_rgba(168,145,214,0.08)]">
          <div class="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
            <div class="flex gap-3">
              <div class="grid h-12 w-12 shrink-0 place-items-center rounded-2xl bg-violet-100 text-violet-700">
                <KeyRound class="h-5 w-5" />
              </div>
              <div>
                <p class="text-xs font-semibold uppercase tracking-[0.22em] text-violet-500">Demo Login</p>
                <h3 class="mt-1 text-xl font-bold text-slate-900">Landingpage temporär sperren</h3>
                <p class="mt-1 text-sm leading-6 text-slate-500">
                  Für Demo-Deployments oder nicht öffentliche Tests. Danach kann der Schutz hier wieder aus.
                </p>
              </div>
            </div>

            <AdminSettingsToggle
              v-model="form.demoLoginEnabled"
              label="Demo Login aktivieren"
              :disabled="saving || !canManage"
            />
          </div>

          <p
            v-if="form.demoLoginEnabled && !demoCredentialsComplete"
            class="mt-4 rounded-2xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm font-semibold text-amber-800"
          >
            Zum Aktivieren fehlen noch Login, Twitch-ID, Anzeigename oder ein gesetztes Passwort.
          </p>

          <div class="mt-5 grid gap-4 md:grid-cols-2">
            <label class="block">
              <span class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Login</span>
              <input v-model="form.demoLoginIdentifier" :disabled="saving || !canManage" type="text" autocomplete="username" placeholder="E-Mail oder Username" class="mt-2 h-12 w-full rounded-2xl border border-violet-200 bg-white px-4 text-sm font-semibold text-slate-800 outline-none transition focus:border-violet-400 focus:ring-4 focus:ring-violet-100 disabled:bg-slate-50 disabled:text-slate-400" />
              <span class="mt-2 block text-xs leading-5 text-slate-500">E-Mail, Username oder dieselbe Kennung wie die Twitch-ID.</span>
            </label>
            <label class="block">
              <span class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Passwort setzen</span>
              <PasswordField
                :model-value="demoPassword"
                :disabled="saving || !canManage"
                autocomplete="new-password"
                placeholder="Leer lassen = behalten"
                root-class="mt-2"
                input-class="h-12 w-full rounded-2xl border border-violet-200 bg-white px-4 text-sm font-semibold text-slate-800 outline-none transition focus:border-violet-400 focus:ring-4 focus:ring-violet-100 disabled:bg-slate-50 disabled:text-slate-400"
                @update:model-value="emit('update:demoPassword', $event)"
              />
              <span class="mt-2 block text-xs leading-5 text-slate-500">{{ demoPasswordHint }}</span>
            </label>
            <label class="block">
              <span class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Twitch-ID</span>
              <input v-model="form.demoLoginTwitchUserId" :disabled="saving || !canManage" type="text" class="mt-2 h-12 w-full rounded-2xl border border-violet-200 bg-white px-4 text-sm font-semibold text-slate-800 outline-none transition focus:border-violet-400 focus:ring-4 focus:ring-violet-100 disabled:bg-slate-50 disabled:text-slate-400" />
            </label>
            <label class="block">
              <span class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Anzeigename</span>
              <input v-model="form.demoLoginDisplayName" :disabled="saving || !canManage" type="text" class="mt-2 h-12 w-full rounded-2xl border border-violet-200 bg-white px-4 text-sm font-semibold text-slate-800 outline-none transition focus:border-violet-400 focus:ring-4 focus:ring-violet-100 disabled:bg-slate-50 disabled:text-slate-400" />
            </label>
          </div>

          <div class="mt-4 flex flex-wrap gap-2 text-xs font-semibold">
            <span class="rounded-full bg-violet-50 px-3 py-1 text-violet-700">{{ demoManagedByDatabase ? 'Quelle: Datenbank' : 'Quelle: Config' }}</span>
            <span class="rounded-full px-3 py-1" :class="demoPasswordSet ? 'bg-emerald-50 text-emerald-700' : 'bg-amber-50 text-amber-700'">
              {{ demoPasswordSet ? 'Passwort vorhanden' : 'Passwort fehlt' }}
            </span>
          </div>
        </section>

        <section class="rounded-[26px] border border-violet-100 bg-white/85 p-5 shadow-[0_18px_46px_rgba(168,145,214,0.08)]">
          <div class="flex gap-3">
            <div class="grid h-12 w-12 shrink-0 place-items-center rounded-2xl bg-violet-100 text-violet-700">
              <Clock3 class="h-5 w-5" />
            </div>
            <div>
              <p class="text-xs font-semibold uppercase tracking-[0.22em] text-violet-500">Session Timeout</p>
              <h3 class="mt-1 text-xl font-bold text-slate-900">Automatischer Logout bei Inaktivitaet</h3>
              <p class="mt-1 text-sm leading-6 text-slate-500">
                Team- und Admin-Sessions werden nach der eingestellten Zeit ohne Aktivitaet automatisch beendet. Minimum sind 3 Stunden.
              </p>
            </div>
          </div>

          <div class="mt-5 grid gap-4 md:grid-cols-[minmax(0,220px)_1fr] md:items-start">
            <label class="block">
              <span class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Inaktiv nach Stunden</span>
              <input
                v-model.number="form.sessionIdleTimeoutHours"
                :disabled="saving || !canManage"
                type="number"
                min="3"
                step="1"
                inputmode="numeric"
                class="mt-2 h-12 w-full rounded-2xl border border-violet-200 bg-white px-4 text-sm font-semibold text-slate-800 outline-none transition focus:border-violet-400 focus:ring-4 focus:ring-violet-100 disabled:bg-slate-50 disabled:text-slate-400"
              />
            </label>
            <div class="rounded-2xl border border-violet-100 bg-violet-50/60 px-4 py-3 text-sm leading-6 text-violet-900">
              Der Logout reagiert auf echte Nutzeraktivität wie Klicks, Tasten, Scrollen oder Touch. Die Session bleibt serverseitig trotzdem autoritativ und läuft spätestens nach 30 Tagen absolut ab.
            </div>
          </div>
        </section>

        <section class="rounded-[26px] border p-5 shadow-[0_18px_46px_rgba(168,145,214,0.08)]" :class="form.maintenanceModeEnabled ? 'border-amber-200 bg-amber-50/70' : 'border-violet-100 bg-white/85'">
          <div class="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
            <div class="flex gap-3">
              <div class="grid h-12 w-12 shrink-0 place-items-center rounded-2xl" :class="form.maintenanceModeEnabled ? 'bg-amber-100 text-amber-700' : 'bg-violet-100 text-violet-700'">
                <Wrench class="h-5 w-5" />
              </div>
              <div>
                <p class="text-xs font-semibold uppercase tracking-[0.22em]" :class="form.maintenanceModeEnabled ? 'text-amber-600' : 'text-violet-500'">Wartungsmodus</p>
                <h3 class="mt-1 text-xl font-bold text-slate-900">Sternenpause anzeigen</h3>
                <p class="mt-1 text-sm leading-6 text-slate-500">
                  Besucher landen auf der Wartungsseite. Login und Admin bleiben erreichbar.
                </p>
              </div>
            </div>

            <AdminSettingsToggle
              v-model="form.maintenanceModeEnabled"
              label="Wartungsmodus aktivieren"
              tone="amber"
              :disabled="saving || !canManage"
            />
          </div>

          <div class="mt-5 space-y-4">
            <label class="block">
              <span class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Titel der Wartungsseite</span>
              <input v-model="form.maintenanceTitle" :disabled="saving || !canManage" type="text" maxlength="120" class="mt-2 h-12 w-full rounded-2xl border border-violet-200 bg-white px-4 text-sm font-semibold text-slate-800 outline-none transition focus:border-violet-400 focus:ring-4 focus:ring-violet-100 disabled:bg-slate-50 disabled:text-slate-400" />
            </label>
            <label class="block">
              <span class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Hinweistext</span>
              <textarea v-model="form.maintenanceMessage" :disabled="saving || !canManage" rows="4" maxlength="600" class="mt-2 w-full resize-none rounded-2xl border border-violet-200 bg-white px-4 py-3 text-sm font-semibold leading-6 text-slate-800 outline-none transition focus:border-violet-400 focus:ring-4 focus:ring-violet-100 disabled:bg-slate-50 disabled:text-slate-400"></textarea>
            </label>
            <RouterLink to="/maintenance?preview=true" class="inline-flex h-11 items-center gap-2 rounded-2xl border border-violet-200 bg-white px-4 text-sm font-semibold text-violet-700 transition hover:bg-violet-50">
              <ShieldCheck class="h-4 w-4" />
              Wartungsseite ansehen
            </RouterLink>
          </div>
        </section>
      </div>

    </div>
  </Card>

  <Modal
    :open="twitchModalOpen"
    title="Twitch OAuth"
    subtitle="Client-Daten aus der Twitch Developer Console. Das Secret wird gespeichert, aber nie wieder angezeigt."
    @close="twitchModalOpen = false"
  >
    <div class="space-y-5">
      <div class="rounded-2xl border border-violet-100 bg-violet-50/60 px-4 py-3 text-sm leading-6 text-violet-900">
        In Twitch muss dieselbe Redirect URI eingetragen sein, die hier gespeichert ist. Ohne eigene Redirect URI nutzt das Backend automatisch den Callback deiner API.
      </div>

      <label class="block">
        <span class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Client-ID</span>
        <input
          v-model="form.twitchClientId"
          :disabled="saving || !canManage"
          type="text"
          autocomplete="off"
          placeholder="Twitch Client-ID"
          class="mt-2 h-12 w-full rounded-2xl border border-violet-200 bg-white px-4 text-sm font-semibold text-slate-800 outline-none transition focus:border-violet-400 focus:ring-4 focus:ring-violet-100 disabled:bg-slate-50 disabled:text-slate-400"
        />
      </label>

      <label class="block">
        <span class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Client Secret</span>
        <PasswordField
          :model-value="twitchClientSecret"
          :disabled="saving || !canManage"
          autocomplete="new-password"
          placeholder="Leer lassen = behalten"
          root-class="mt-2"
          input-class="h-12 w-full rounded-2xl border border-violet-200 bg-white px-4 text-sm font-semibold text-slate-800 outline-none transition focus:border-violet-400 focus:ring-4 focus:ring-violet-100 disabled:bg-slate-50 disabled:text-slate-400"
          @update:model-value="emit('update:twitchClientSecret', $event)"
        />
        <span class="mt-2 block text-xs leading-5 text-slate-500">{{ twitchSecretHint }}</span>
      </label>

      <label class="block">
        <span class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Redirect URI</span>
        <input
          v-model="form.twitchRedirectUri"
          :disabled="saving || !canManage"
          type="url"
          autocomplete="off"
          :placeholder="defaultRedirectUri()"
          class="mt-2 h-12 w-full rounded-2xl border border-violet-200 bg-white px-4 text-sm font-semibold text-slate-800 outline-none transition focus:border-violet-400 focus:ring-4 focus:ring-violet-100 disabled:bg-slate-50 disabled:text-slate-400"
        />
        <span class="mt-2 block text-xs leading-5 text-slate-500">Muss exakt in deiner Twitch-App unter OAuth Redirect URLs eingetragen sein.</span>
      </label>

      <label class="block">
        <span class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Scopes</span>
        <input
          v-model="form.twitchScope"
          :disabled="saving || !canManage"
          type="text"
          autocomplete="off"
          placeholder="Optional, z.B. user:read:email"
          class="mt-2 h-12 w-full rounded-2xl border border-violet-200 bg-white px-4 text-sm font-semibold text-slate-800 outline-none transition focus:border-violet-400 focus:ring-4 focus:ring-violet-100 disabled:bg-slate-50 disabled:text-slate-400"
        />
        <span class="mt-2 block text-xs leading-5 text-slate-500">Für reines Login/Profil bleibt das Feld normalerweise leer.</span>
      </label>

      <p
        v-if="form.twitchClientId && !twitchAuthComplete"
        class="rounded-2xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm font-semibold text-amber-800"
      >
        Zum Aktivieren fehlt noch ein Client Secret.
      </p>

    </div>

    <template #footer>
      <Button type="button" variant="ghost" :disabled="saving" @click="twitchModalOpen = false">Schließen</Button>
      <Button type="button" class="gap-2" :disabled="saving || !canManage" @click="emit('save')">
        <Loader2 v-if="saving" class="h-4 w-4 animate-spin" />
        <Save v-else class="h-4 w-4" />
        {{ saving ? 'Speichert ...' : 'Twitch speichern' }}
      </Button>
    </template>
  </Modal>
</template>
