<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 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">
    <section class="admin-user-detail-shell hoard-panel">
      <header class="admin-user-detail-head">
        <p class="hoard-kicker">Adminbereich</p>
        <h1>Benutzerdetails</h1>
        <p>Read-only Ansicht des ausgewählten Kontos.</p>
      </header>

      <v-alert
        v-if="errorMessage"
        type="error"
        variant="tonal"
        border="start"
      >
        {{ 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">
        <div class="admin-user-detail-profile">
          <span class="admin-user-detail-avatar">
            <v-icon icon="mdi-account-outline" size="24" />
          </span>
          <div>
            <p class="admin-user-detail-profile-label">Ausgewähltes Konto</p>
            <h2>{{ user.userName || '(ohne Benutzername)' }}</h2>
          </div>
        </div>

        <dl class="admin-user-detail-grid">
          <div class="admin-user-detail-item">
            <dt>ID</dt>
            <dd>{{ 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>Aktiv</dt>
            <dd>
              <span
                :class="[
                  'hoard-status',
                  user.isActive ? 'hoard-status--success' : 'hoard-status--danger',
                ]"
              >
                {{ user.isActive ? 'Aktiv' : 'Inaktiv' }}
              </span>
            </dd>
          </div>
          <div class="admin-user-detail-item">
            <dt>Passwortwechsel</dt>
            <dd>
              <span
                :class="[
                  'hoard-status',
                  user.mustChangePassword ? 'hoard-status--warning' : 'hoard-status--info',
                ]"
              >
                {{ user.mustChangePassword ? 'Erforderlich' : 'Nicht erforderlich' }}
              </span>
            </dd>
          </div>
        </dl>
      </article>

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

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

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

.admin-user-detail-head h1,
.admin-user-detail-head p,
.admin-user-detail-loading {
  margin: 0;
}

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

.admin-user-detail-head p,
.admin-user-detail-loading {
  color: var(--color-text-secondary);
}

.admin-user-detail-card {
  display: grid;
  gap: var(--space-4);
  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) 54%, var(--color-surface) 46%);
}

.admin-user-detail-profile {
  display: grid;
  grid-template-columns: auto 1fr;
  gap: var(--space-3);
  align-items: center;
  min-width: 0;
}

.admin-user-detail-avatar {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 48px;
  height: 48px;
  border-radius: var(--radius-lg);
  color: var(--color-primary-700);
  background-color: color-mix(in srgb, var(--color-primary-100) 82%, var(--color-surface) 18%);
}

.admin-user-detail-profile-label {
  margin: 0;
  color: var(--color-text-muted);
  font-size: var(--font-size-xs);
  font-weight: 600;
  letter-spacing: 0.04em;
  text-transform: uppercase;
}

.admin-user-detail-profile h2 {
  margin: var(--space-1) 0 0;
  color: var(--color-text);
  font-size: 1.35rem;
  overflow-wrap: anywhere;
}

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

.admin-user-detail-item {
  display: grid;
  gap: var(--space-1);
}

.admin-user-detail-item dt {
  color: var(--color-text-muted);
  font-size: var(--font-size-sm);
  font-weight: 600;
}

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

.admin-user-detail-actions {
  justify-content: flex-end;
}

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

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

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

  .admin-user-detail-actions {
    justify-content: stretch;
  }
}
</style>
