<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'

import { AuthRequestError, fetchCurrentUser, type CurrentUser } from '@/services/authSession'

const router = useRouter()
const isLoading = ref(true)
const errorMessage = ref('')
const user = ref<CurrentUser | null>(null)

const prettyUser = computed(() => {
  if (!user.value) {
    return ''
  }

  return JSON.stringify(user.value, null, 2)
})

const userInitials = computed(() => {
  const name = user.value?.userName?.trim() ?? ''
  if (name.length === 0) {
    return 'H'
  }

  const parts = name.split(/[\s._-]+/).filter((part) => part.length > 0)
  if (parts.length === 0) {
    return name.slice(0, 2).toUpperCase()
  }

  if (parts.length === 1) {
    const first = parts[0] as string
    return first.slice(0, 2).toUpperCase()
  }

  const first = parts[0] as string
  const second = parts[1] as string
  return `${first.charAt(0)}${second.charAt(0)}`.toUpperCase()
})

const roleLabel = computed(() => {
  if (!user.value || user.value.roles.length === 0) {
    return 'Keine Rolle'
  }

  return user.value.roles.join(', ')
})

const roleChips = computed(() => {
  if (!user.value || user.value.roles.length === 0) {
    return [] as string[]
  }

  return user.value.roles
})

const accountStatusVariant = computed(() => (user.value?.isActive ? 'success' : 'danger'))
const accountStatusLabel = computed(() => (user.value?.isActive ? 'Aktiv' : 'Inaktiv'))
const passwordStatusVariant = computed(() => (user.value?.mustChangePassword ? 'warning' : 'info'))
const passwordStatusLabel = computed(() =>
  user.value?.mustChangePassword ? 'Wechsel erforderlich' : 'Aktuell',
)

async function loadCurrentUser() {
  isLoading.value = true
  errorMessage.value = ''

  try {
    const currentUser = await fetchCurrentUser({ force: true })
    if (!currentUser) {
      await router.replace({ name: 'Login', query: { redirect: '/' } })
      return
    }

    user.value = currentUser
  } catch (error) {
    if (error instanceof AuthRequestError) {
      errorMessage.value = error.message
    } else {
      errorMessage.value = 'Benutzerdaten konnten nicht geladen werden.'
    }
  } finally {
    isLoading.value = false
  }
}

function goToChangePassword() {
  void router.push({ name: 'ChangePassword' })
}

onMounted(() => {
  void loadCurrentUser()
})
</script>

<template>
  <v-container fluid class="dashboard-page hoard-page">
    <header class="dashboard-greeting hoard-panel hoard-panel-gradient hoard-spotlight">
      <div class="dashboard-greeting__copy">
        <p class="hoard-kicker hoard-kicker--wide">Geschützter Bereich</p>
        <h1>
          <template v-if="user">Hallo, {{ user.userName || 'willkommen' }}.</template>
          <template v-else>Dashboard</template>
        </h1>
        <p>
          Hier siehst du den aktuellen Status deines Kontos. Sobald die Datei- und Markdown-Module live
          gehen, wird dieser Bereich dein Startpunkt in den Workspace.
        </p>

        <div class="dashboard-greeting__chips">
          <span v-for="role in roleChips" :key="role" class="hoard-chip hoard-chip--brand">
            <v-icon icon="mdi-shield-account-outline" size="14" />
            {{ role }}
          </span>
          <span v-if="roleChips.length === 0" class="hoard-chip">
            <v-icon icon="mdi-account-outline" size="14" /> Keine Rollen
          </span>
        </div>
      </div>

      <div v-if="user" class="dashboard-greeting__avatar">
        <span class="dashboard-avatar">{{ userInitials }}</span>
        <p class="dashboard-avatar__caption">{{ user.userName }}</p>
      </div>
    </header>

    <v-alert
      v-if="errorMessage"
      type="error"
      density="comfortable"
    >
      {{ errorMessage }}
    </v-alert>

    <section v-else class="dashboard-grid">
      <article class="dashboard-stat hoard-panel">
        <div class="dashboard-stat__head">
          <span class="hoard-icon-tile">
            <v-icon icon="mdi-account-outline" size="20" />
          </span>
          <p class="dashboard-stat__label">Konto</p>
        </div>
        <p class="dashboard-stat__value">{{ user?.userName || '—' }}</p>
        <p class="dashboard-stat__hint">Angemeldet als interner Benutzer</p>
      </article>

      <article class="dashboard-stat hoard-panel">
        <div class="dashboard-stat__head">
          <span class="hoard-icon-tile">
            <v-icon icon="mdi-shield-account-outline" size="20" />
          </span>
          <p class="dashboard-stat__label">Rollen</p>
        </div>
        <p class="dashboard-stat__value">{{ roleLabel }}</p>
        <p class="dashboard-stat__hint">Definiert deine sichtbaren Bereiche</p>
      </article>

      <article class="dashboard-stat hoard-panel">
        <div class="dashboard-stat__head">
          <span class="hoard-icon-tile">
            <v-icon icon="mdi-pulse" size="20" />
          </span>
          <p class="dashboard-stat__label">Status</p>
        </div>
        <div class="dashboard-stat__pill-row">
          <span :class="['hoard-status', `hoard-status--${accountStatusVariant}`]">
            {{ accountStatusLabel }}
          </span>
          <span :class="['hoard-status', `hoard-status--${passwordStatusVariant}`]">
            {{ passwordStatusLabel }}
          </span>
        </div>
        <p class="dashboard-stat__hint">Konto- und Passwortzustand</p>
      </article>
    </section>

    <section v-if="!errorMessage" class="dashboard-detail hoard-panel">
      <header class="dashboard-detail__head">
        <div>
          <p class="hoard-kicker">Auth-Antwort</p>
          <h2>Aktueller Session-Snapshot</h2>
          <p>Direkt aus <code>GET /auth/me</code> – nützlich zum Debuggen und für Plausibilitätschecks.</p>
        </div>

        <div class="dashboard-detail__actions hoard-action-row">
          <v-btn
            variant="outlined"
            prepend-icon="mdi-lock-reset"
            @click="goToChangePassword"
          >
            Passwort ändern
          </v-btn>
          <v-btn
            variant="elevated"
            prepend-icon="mdi-refresh"
            :loading="isLoading"
            :disabled="isLoading"
            @click="loadCurrentUser"
          >
            Neu laden
          </v-btn>
        </div>
      </header>

      <p v-if="isLoading" class="dashboard-detail__loading">Benutzerdaten werden geladen …</p>
      <pre v-else class="dashboard-detail__json">{{ prettyUser }}</pre>
    </section>
  </v-container>
</template>

<style scoped>
.dashboard-page {
  --hoard-page-width: 1120px;
}

/* ---------- Greeting ---------- */
.dashboard-greeting {
  --hoard-gradient-angle: 120deg;
  --hoard-gradient-start: color-mix(in srgb, var(--color-primary-100) 60%, var(--color-surface) 40%);
  --hoard-gradient-end: var(--color-surface);
  --hoard-gradient-end-stop: 65%;

  display: grid;
  grid-template-columns: minmax(0, 1fr) auto;
  gap: var(--space-6);
  align-items: center;
  padding: var(--space-8);
  border-radius: var(--radius-xl);
  overflow: hidden;
}

.dashboard-greeting__copy {
  position: relative;
  z-index: 1;
}

h1 {
  margin: 0 0 var(--space-3);
  font-size: clamp(1.8rem, 1.4rem + 1vw, 2.4rem);
  letter-spacing: -0.02em;
}

.dashboard-greeting__copy p {
  margin: 0;
  color: var(--color-text-secondary);
  font-size: var(--font-size-md);
  max-width: 64ch;
}

.dashboard-greeting__chips {
  display: flex;
  flex-wrap: wrap;
  gap: var(--space-2);
  margin-top: var(--space-4);
}

.dashboard-greeting__avatar {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: var(--space-2);
  z-index: 1;
}

.dashboard-avatar {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 84px;
  height: 84px;
  border-radius: var(--radius-full);
  background:
    linear-gradient(135deg, var(--color-primary-600), var(--color-primary-800));
  color: var(--color-text-on-primary);
  font-size: 28px;
  font-weight: 700;
  letter-spacing: -0.01em;
  box-shadow:
    var(--shadow-glow),
    inset 0 0 0 2px color-mix(in srgb, var(--color-accent-lime) 25%, transparent);
}

.dashboard-avatar__caption {
  margin: 0;
  color: var(--color-text-secondary);
  font-size: var(--font-size-xs);
  font-weight: 500;
  letter-spacing: 0.04em;
  text-transform: uppercase;
  max-width: 160px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* ---------- Stats grid ---------- */
.dashboard-grid {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: var(--space-4);
}

.dashboard-stat {
  display: flex;
  flex-direction: column;
  gap: var(--space-3);
  padding: var(--space-5);
}

.dashboard-stat__head {
  display: inline-flex;
  align-items: center;
  gap: var(--space-3);
}

.dashboard-stat__label {
  margin: 0;
  color: var(--color-text-muted);
  font-size: var(--font-size-2xs);
  font-weight: 600;
  letter-spacing: 0.06em;
  text-transform: uppercase;
}

.dashboard-stat__value {
  margin: 0;
  color: var(--color-text);
  font-size: var(--font-size-xl);
  font-weight: 600;
  letter-spacing: -0.01em;
  overflow-wrap: anywhere;
}

.dashboard-stat__hint {
  margin: 0;
  color: var(--color-text-muted);
  font-size: var(--font-size-xs);
}

.dashboard-stat__pill-row {
  display: flex;
  flex-wrap: wrap;
  gap: var(--space-2);
}

/* ---------- Detail panel ---------- */
.dashboard-detail {
  display: flex;
  flex-direction: column;
  gap: var(--space-4);
  padding: var(--space-6);
}

.dashboard-detail__head {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: var(--space-4);
  flex-wrap: wrap;
}

.dashboard-detail__head h2 {
  margin: 0 0 var(--space-1);
  font-size: var(--font-size-xl);
  letter-spacing: -0.01em;
}

.dashboard-detail__head p {
  margin: 0;
  color: var(--color-text-secondary);
  font-size: var(--font-size-sm);
}

.dashboard-detail__loading {
  margin: 0;
  color: var(--color-text-secondary);
}

.dashboard-detail__json {
  margin: 0;
  overflow: auto;
  padding: var(--space-4);
  border: 1px solid var(--color-border-subtle);
  border-radius: var(--radius-md);
  background-color: color-mix(in srgb, var(--color-surface-alt) 70%, var(--color-surface) 30%);
  color: var(--color-text);
  font-family: var(--font-family-mono);
  font-size: var(--font-size-xs);
  line-height: 1.55;
}

@media (prefers-reduced-motion: no-preference) {
  .dashboard-greeting,
  .dashboard-stat,
  .dashboard-detail {
    animation: hoard-soft-enter 280ms both;
  }

  .dashboard-stat:nth-child(2) {
    animation-delay: 60ms;
  }

  .dashboard-stat:nth-child(3) {
    animation-delay: 120ms;
  }

  .dashboard-detail {
    animation-delay: 160ms;
  }
}

@media (width <= 960px) {
  .dashboard-greeting {
    grid-template-columns: 1fr;
    text-align: left;
    padding: var(--space-6);
  }

  .dashboard-greeting__avatar {
    align-items: flex-start;
  }

  .dashboard-grid {
    grid-template-columns: 1fr;
  }

  .dashboard-detail {
    padding: var(--space-5);
  }
}

@media (width <= 600px) {
  .dashboard-greeting {
    padding: var(--space-5);
  }

  .dashboard-stat,
  .dashboard-detail {
    padding: var(--space-4);
  }

  .dashboard-detail__head {
    flex-direction: column;
    align-items: stretch;
  }

  .dashboard-detail__actions {
    width: 100%;
  }

  :deep(.dashboard-detail__actions .v-btn) {
    width: 100%;
    min-height: 44px;
  }

  .dashboard-detail__json {
    max-width: 100%;
    overflow-x: hidden;
    padding: var(--space-3);
    white-space: pre-wrap;
    overflow-wrap: anywhere;
    word-break: break-word;
  }
}
</style>
