<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { fetchAdminUserById, type AdminUser } from '@/services/adminUsers'
import { AuthRequestError } from '@/services/authSession'
import { useAppBannersStore } from '@/stores/appBanners'

const route = useRoute()
const router = useRouter()
const appBannersStore = useAppBannersStore()

const isLoading = ref(true)
const errorMessage = ref('')
const user = ref<AdminUser | null>(null)

const routeUserId = computed(() => {
  const value = route.params.userId
  return typeof value === 'string' ? value : ''
})

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

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

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

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

  if (routeUserId.value.length === 0) {
    errorMessage.value = 'Ungültige Benutzer-ID in der Route.'
    isLoading.value = false
    return
  }

  try {
    user.value = await fetchAdminUserById(routeUserId.value)
  } catch (error) {
    if (error instanceof AuthRequestError) {
      errorMessage.value = error.message

      if (error.status === 401) {
        await router.replace({
          name: 'Login',
          query: { redirect: route.fullPath },
        })
        return
      }

      if (error.status === 403) {
        await router.replace({ name: 'Forbidden' })
        return
      }
    } else {
      errorMessage.value = 'Benutzerdetails konnten nicht geladen werden.'
    }

    appBannersStore.pushError(errorMessage.value, 'Benutzerdetails')
  } finally {
    isLoading.value = false
  }
}

async function navigateToList() {
  await router.push({ name: 'AdminUsers' })
}

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

<template>
  <v-container fluid class="admin-user-detail-page hoard-page">
    <header class="admin-user-detail-head hoard-panel hoard-panel-gradient">
      <div class="admin-user-detail-head__copy">
        <p class="hoard-kicker hoard-kicker--wide">Adminbereich</p>
        <h1>Benutzerdetails</h1>
        <p>Read-only Ansicht des ausgewählten Kontos. Änderungen erfolgen aktuell außerhalb der App.</p>
      </div>

      <div class="admin-user-detail-head__actions hoard-action-row">
        <v-btn
          variant="outlined"
          prepend-icon="mdi-arrow-left"
          @click="navigateToList"
        >
          Zurück zur Liste
        </v-btn>
        <v-btn
          variant="elevated"
          prepend-icon="mdi-refresh"
          :loading="isLoading"
          :disabled="isLoading"
          @click="loadUser"
        >
          Neu laden
        </v-btn>
      </div>
    </header>

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

    <p v-else-if="isLoading" class="admin-user-detail-loading">Benutzerdetails werden geladen …</p>

    <article v-else-if="user" class="admin-user-detail-card hoard-panel">
      <header class="admin-user-detail-card__head">
        <span class="admin-user-detail-avatar">{{ userInitials }}</span>
        <div>
          <p class="hoard-kicker hoard-kicker--xs">Konto</p>
          <h2>{{ user.userName || '(ohne Benutzername)' }}</h2>
          <p class="admin-user-detail-card__id">{{ user.id }}</p>
        </div>
        <div class="admin-user-detail-card__pills">
          <span
            :class="[
              'hoard-status',
              user.isActive ? 'hoard-status--success' : 'hoard-status--danger',
            ]"
          >
            {{ user.isActive ? 'Aktiv' : 'Inaktiv' }}
          </span>
          <span
            :class="[
              'hoard-status',
              user.mustChangePassword ? 'hoard-status--warning' : 'hoard-status--info',
            ]"
          >
            {{ user.mustChangePassword ? 'Passwort wechseln' : 'Passwort aktuell' }}
          </span>
        </div>
      </header>

      <hr class="hoard-divider-soft" />

      <dl class="admin-user-detail-grid">
        <div class="admin-user-detail-item">
          <dt>ID</dt>
          <dd class="admin-user-detail-item__mono">{{ user.id }}</dd>
        </div>
        <div class="admin-user-detail-item">
          <dt>Benutzername</dt>
          <dd>{{ user.userName || '(ohne Benutzername)' }}</dd>
        </div>
        <div class="admin-user-detail-item">
          <dt>Rollen</dt>
          <dd>{{ rolesText }}</dd>
        </div>
        <div class="admin-user-detail-item">
          <dt>Konto aktiv</dt>
          <dd>{{ user.isActive ? 'Ja' : 'Nein' }}</dd>
        </div>
        <div class="admin-user-detail-item">
          <dt>Passwortwechsel</dt>
          <dd>{{ user.mustChangePassword ? 'Erforderlich' : 'Nicht erforderlich' }}</dd>
        </div>
      </dl>
    </article>
  </v-container>
</template>

<style scoped>
.admin-user-detail-page {
  --hoard-page-width: 1080px;
}

.admin-user-detail-head {
  --hoard-gradient-angle: 120deg;
  --hoard-gradient-start: color-mix(in srgb, var(--color-primary-100) 55%, var(--color-surface) 45%);
  --hoard-gradient-end: var(--color-surface);
  --hoard-gradient-end-stop: 65%;

  display: grid;
  grid-template-columns: minmax(0, 1.1fr) auto;
  gap: var(--space-5);
  align-items: end;
  padding: var(--space-7) var(--space-8);
  border-radius: var(--radius-xl);
}

.admin-user-detail-head__copy h1 {
  margin: 0 0 var(--space-2);
  font-size: var(--font-size-2xl);
  letter-spacing: -0.015em;
}

.admin-user-detail-head__copy p {
  margin: 0;
  color: var(--color-text-secondary);
}

.admin-user-detail-loading {
  margin: 0;
  color: var(--color-text-secondary);
}

.admin-user-detail-card {
  display: flex;
  flex-direction: column;
  gap: var(--space-5);
  padding: var(--space-6);
}

.admin-user-detail-card__head {
  display: grid;
  grid-template-columns: auto 1fr auto;
  gap: var(--space-4);
  align-items: center;
}

.admin-user-detail-avatar {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 64px;
  height: 64px;
  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: 22px;
  font-weight: 700;
  letter-spacing: 0.02em;
  box-shadow:
    var(--shadow-sm),
    inset 0 0 0 2px color-mix(in srgb, var(--color-accent-lime) 22%, transparent);
}

.admin-user-detail-card__head h2 {
  margin: var(--space-1) 0;
  font-size: var(--font-size-xl);
  letter-spacing: -0.01em;
  overflow-wrap: anywhere;
}

.admin-user-detail-card__id {
  margin: 0;
  color: var(--color-text-muted);
  font-family: var(--font-family-mono);
  font-size: var(--font-size-xs);
  overflow-wrap: anywhere;
}

.admin-user-detail-card__pills {
  display: flex;
  flex-direction: column;
  gap: var(--space-2);
  align-items: flex-end;
}

.admin-user-detail-grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(220px, 1fr));
  gap: var(--space-4) var(--space-6);
  margin: 0;
}

.admin-user-detail-item {
  display: grid;
  gap: var(--space-1);
  padding-bottom: var(--space-3);
  border-bottom: 1px solid var(--color-border-subtle);
}

.admin-user-detail-item:nth-last-child(-n + 2) {
  border-bottom: none;
  padding-bottom: 0;
}

.admin-user-detail-item dt {
  color: var(--color-text-muted);
  font-size: var(--font-size-2xs);
  font-weight: 600;
  letter-spacing: 0.06em;
  text-transform: uppercase;
}

.admin-user-detail-item dd {
  margin: 0;
  color: var(--color-text);
  font-size: var(--font-size-md);
  word-break: break-word;
}

.admin-user-detail-item__mono {
  font-family: var(--font-family-mono);
  font-size: var(--font-size-sm) !important;
}

@media (prefers-reduced-motion: no-preference) {
  .admin-user-detail-head,
  .admin-user-detail-card {
    animation: hoard-soft-enter 280ms both;
  }

  .admin-user-detail-card {
    animation-delay: 80ms;
  }
}

@media (width <= 960px) {
  .admin-user-detail-head {
    grid-template-columns: 1fr;
    align-items: flex-start;
    padding: var(--space-6);
  }

  .admin-user-detail-head__actions {
    width: 100%;
    justify-content: flex-start;
  }

  .admin-user-detail-card__head {
    grid-template-columns: auto 1fr;
  }

  .admin-user-detail-card__pills {
    grid-column: 1 / -1;
    flex-direction: row;
    align-items: flex-start;
    flex-wrap: wrap;
  }
}

@media (width <= 600px) {
  .admin-user-detail-head {
    padding: var(--space-5);
  }

  .admin-user-detail-card {
    padding: var(--space-5);
  }

  .admin-user-detail-card__head {
    grid-template-columns: auto 1fr;
    gap: var(--space-3);
  }

  .admin-user-detail-grid {
    grid-template-columns: 1fr;
  }

  .admin-user-detail-item:nth-last-child(-n + 2) {
    border-bottom: 1px solid var(--color-border-subtle);
    padding-bottom: var(--space-3);
  }

  .admin-user-detail-item:last-child {
    border-bottom: none;
    padding-bottom: 0;
  }
}
</style>
