<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 roleLabel = computed(() => {
  if (!user.value || user.value.roles.length === 0) {
    return 'Keine Rolle'
  }

  return user.value.roles.join(', ')
})
const accountStateLabel = computed(() => (user.value?.isActive ? 'Aktiv' : 'Inaktiv'))
const passwordStateLabel = computed(() =>
  user.value?.mustChangePassword ? '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
  }
}

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

<template>
  <v-container fluid class="dashboard-page hoard-page">
    <section class="dashboard-shell hoard-panel">
      <header class="dashboard-head">
        <p class="hoard-kicker">Geschützter Bereich</p>
        <h1>Dashboard</h1>
        <p>Hier siehst du aktuell direkt die Antwort von <code>/auth/me</code>.</p>
      </header>

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

      <article v-else class="dashboard-user">
        <template v-if="isLoading">
          <p class="dashboard-loading">Benutzerdaten werden geladen...</p>
        </template>
        <template v-else>
          <div class="dashboard-summary-grid">
            <article class="dashboard-summary-card">
              <span class="dashboard-summary-icon">
                <v-icon icon="mdi-account-outline" size="20" />
              </span>
              <div>
                <p class="dashboard-summary-label">Konto</p>
                <p class="dashboard-summary-value">{{ user?.userName || 'Unbekannt' }}</p>
              </div>
            </article>

            <article class="dashboard-summary-card">
              <span class="dashboard-summary-icon">
                <v-icon icon="mdi-shield-account-outline" size="20" />
              </span>
              <div>
                <p class="dashboard-summary-label">Rollen</p>
                <p class="dashboard-summary-value">{{ roleLabel }}</p>
              </div>
            </article>

            <article class="dashboard-summary-card">
              <span class="dashboard-summary-icon">
                <v-icon icon="mdi-lock-check-outline" size="20" />
              </span>
              <div>
                <p class="dashboard-summary-label">Status</p>
                <p class="dashboard-summary-value">
                  {{ accountStateLabel }} · Passwort {{ passwordStateLabel }}
                </p>
              </div>
            </article>
          </div>

          <p class="dashboard-label">Antwort von <code>GET /auth/me</code>:</p>
          <pre class="dashboard-json">{{ prettyUser }}</pre>
        </template>
      </article>

      <div class="dashboard-actions">
        <v-btn
          variant="outlined"
          prepend-icon="mdi-refresh"
          :loading="isLoading"
          :disabled="isLoading"
          @click="loadCurrentUser"
        >
          Neu laden
        </v-btn>
      </div>
    </section>
  </v-container>
</template>

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

.dashboard-shell {
  display: grid;
  gap: var(--space-4);
  padding: var(--space-6);
}

.dashboard-head h1,
.dashboard-head p,
.dashboard-label,
.dashboard-loading {
  margin: 0;
}

.dashboard-head h1 {
  margin-top: var(--space-2);
  margin-bottom: var(--space-2);
}

.dashboard-head p {
  color: var(--color-text-secondary);
}

.dashboard-user {
  padding: var(--space-4);
  border: 1px solid color-mix(in srgb, var(--color-border) 82%, var(--color-surface) 18%);
  border-radius: var(--radius-md);
  background-color: color-mix(in srgb, var(--color-surface-alt) 58%, var(--color-surface) 42%);
}

.dashboard-label {
  margin-bottom: var(--space-2);
  color: var(--color-text-secondary);
  font-size: var(--font-size-sm);
}

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

.dashboard-summary-card {
  display: grid;
  grid-template-columns: auto 1fr;
  gap: var(--space-3);
  min-width: 0;
  padding: var(--space-3);
  border: 1px solid color-mix(in srgb, var(--color-border) 78%, var(--color-surface) 22%);
  border-radius: var(--radius-md);
  background-color: var(--color-surface);
}

.dashboard-summary-icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 36px;
  height: 36px;
  border-radius: var(--radius-md);
  color: var(--color-primary-700);
  background-color: color-mix(in srgb, var(--color-primary-100) 82%, var(--color-surface) 18%);
}

.dashboard-summary-label,
.dashboard-summary-value {
  margin: 0;
}

.dashboard-summary-label {
  color: var(--color-text-muted);
  font-size: var(--font-size-xs);
  font-weight: 600;
  letter-spacing: 0.04em;
  text-transform: uppercase;
}

.dashboard-summary-value {
  color: var(--color-text);
  font-weight: 600;
  line-height: 1.35;
  overflow-wrap: anywhere;
}

.dashboard-loading {
  color: var(--color-text-secondary);
}

.dashboard-json {
  margin: 0;
  overflow: auto;
  padding: var(--space-4);
  border-radius: var(--radius-md);
  color: var(--color-text);
  background-color: var(--color-surface-alt);
  font-size: 0.88rem;
  line-height: 1.5;
}

.dashboard-actions {
  display: flex;
  justify-content: flex-end;
}

@media (prefers-reduced-motion: no-preference) {
  .dashboard-shell {
    animation: hoard-soft-enter 260ms both;
  }
}

@media (width <= 600px) {
  .dashboard-page,
  .dashboard-shell,
  .dashboard-user,
  .dashboard-summary-grid,
  .dashboard-summary-card {
    min-width: 0;
    max-width: 100%;
  }

  .dashboard-shell {
    padding: var(--space-4);
    overflow: hidden;
  }

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

  .dashboard-user {
    padding: var(--space-3);
    overflow: hidden;
  }

  .dashboard-summary-card {
    grid-template-columns: auto minmax(0, 1fr);
  }

  .dashboard-head p,
  .dashboard-label {
    overflow-wrap: anywhere;
  }

  .dashboard-json {
    max-width: 100%;
    overflow-x: hidden;
    padding: var(--space-3);
    white-space: pre-wrap;
    overflow-wrap: anywhere;
    word-break: break-word;
    font-size: var(--font-size-xs);
  }

  .dashboard-actions {
    justify-content: stretch;
  }

  :deep(.dashboard-actions .v-btn) {
    width: 100%;
    min-height: 44px;
  }
}
</style>
