<script setup lang="ts">
import type { AdminTenant, AdminUser } from "~/composables/useAdmin"

const auth = useAuthStore()
const route = useRoute()
const router = useRouter()
const toast = useToast()
const admin = useAdmin()

const tenantId = Number(route.params.id)
const loading = ref(true)
const saving = ref(false)
const creatingUser = ref(false)
const createUserModalOpen = ref(false)
const createdUserPassword = ref("")

const tenantForm = ref<AdminTenant | null>(null)
const assignedUsers = ref<AdminUser[]>([])
const createUserForm = ref({
  email: "",
  password: "",
  first_name: "",
  last_name: "",
  is_admin: false,
  multiTenant: false,
})

const fetchTenant = async () => {
  loading.value = true

  try {
    const overview = await admin.getOverview()
    const tenant = overview.tenants.find((entry) => entry.id === tenantId)

    if (!tenant) {
      toast.add({ title: "Tenant nicht gefunden", color: "red" })
      await router.push("/administration/tenants")
      return
    }

    tenantForm.value = { ...tenant }
    assignedUsers.value = overview.users.filter((user) => user.tenant_ids.includes(tenantId))
  } catch (err: any) {
    console.error("[administration/tenants/show]", err)
    toast.add({
      title: "Tenant konnte nicht geladen werden",
      description: err?.data?.error || err?.message || "Unbekannter Fehler",
      color: "red",
    })
  } finally {
    loading.value = false
  }
}

const saveTenant = async () => {
  if (!tenantForm.value || saving.value) return

  saving.value = true

  try {
    await admin.updateTenant(tenantForm.value.id, {
      name: tenantForm.value.name,
      short: tenantForm.value.short,
    })

    await fetchTenant()
    await auth.fetchMe()

    toast.add({ title: "Tenant gespeichert", color: "green" })
  } catch (err: any) {
    console.error("[administration/tenants/save]", err)
    toast.add({
      title: "Tenant konnte nicht gespeichert werden",
      description: err?.data?.error || err?.message || "Unbekannter Fehler",
      color: "red",
    })
  } finally {
    saving.value = false
  }
}

const createTenantUser = async () => {
  if (!tenantForm.value || creatingUser.value) return

  creatingUser.value = true

  try {
    const response = await admin.createUser(createUserForm.value)
    const createdUserId = response?.user?.id

    if (!createdUserId) {
      throw new Error("Benutzer konnte nach dem Anlegen nicht zugeordnet werden.")
    }

    await admin.updateUserAccess(createdUserId, {
      tenant_ids: [tenantForm.value.id],
      role_assignments: [],
      profile_defaults: {
        first_name: createUserForm.value.first_name,
        last_name: createUserForm.value.last_name,
      },
      profile_assignments: [
        {
          tenant_id: tenantForm.value.id,
          profile_id: null,
        },
      ],
    })

    createdUserPassword.value = response.initialPassword || ""
    createUserModalOpen.value = false
    createUserForm.value = {
      email: "",
      password: "",
      first_name: "",
      last_name: "",
      is_admin: false,
      multiTenant: false,
    }

    await fetchTenant()

    toast.add({
      title: "Benutzer angelegt",
      description: "Der Benutzer wurde direkt diesem Tenant zugeordnet und das Profil wurde erstellt.",
      color: "green",
    })
  } catch (err: any) {
    console.error("[administration/tenants/create-user]", err)
    toast.add({
      title: "Benutzer konnte nicht angelegt werden",
      description: err?.data?.error || err?.message || "Unbekannter Fehler",
      color: "red",
    })
  } finally {
    creatingUser.value = false
  }
}

onMounted(async () => {
  if (!auth.user?.is_admin) {
    await router.push("/")
    return
  }

  await fetchTenant()
})
</script>

<template>
  <UDashboardNavbar title="Administration: Tenants">
    <template #left>
      <UButton icon="i-heroicons-chevron-left" variant="outline" @click="router.push('/administration/tenants')">
        Tenants
      </UButton>
    </template>
    <template #right>
      <UButton icon="i-heroicons-user-plus" variant="soft" @click="createUserModalOpen = true">
        Benutzer anlegen
      </UButton>
      <UButton color="primary" :loading="saving" @click="saveTenant">
        Speichern
      </UButton>
    </template>
  </UDashboardNavbar>

  <UDashboardPanelContent>
    <UCard v-if="!loading && tenantForm">
      <div class="flex items-start justify-between gap-4 mb-6">
        <div>
          <h2 class="text-xl font-semibold">{{ tenantForm.name }}</h2>
          <p class="text-sm text-gray-500">Tenant-ID {{ tenantForm.id }}</p>
        </div>
      </div>

      <USeparator label="Tenant" />

      <UForm :state="tenantForm" class="grid grid-cols-1 md:grid-cols-2 gap-6 mt-4">
        <UFormField label="Name">
          <UInput v-model="tenantForm.name" />
        </UFormField>

        <UFormField label="Kürzel">
          <UInput v-model="tenantForm.short" />
        </UFormField>
      </UForm>
    </UCard>

    <UCard v-if="!loading && tenantForm" class="mt-3">
      <USeparator label="Zugeordnete Benutzer" />

      <UTable
        :data="assignedUsers"
        :columns="normalizeTableColumns([
          { key: 'display_name', label: 'Benutzer' },
          { key: 'email', label: 'E-Mail' }
        ])"
        :on-select="(row) => router.push(`/administration/users/${row.original?.id || row.id}`)"
        class="mt-4"
      />
    </UCard>

    <USkeleton v-if="loading" class="h-80" />
  </UDashboardPanelContent>

  <UModal v-model:open="createUserModalOpen">
    <template #content>
      <UCard>
        <template #header>
          <div class="text-lg font-semibold">Benutzer in Tenant anlegen</div>
        </template>

        <UForm :state="createUserForm" class="space-y-4" @submit.prevent="createTenantUser">
          <UFormField label="Tenant">
            <UInput :model-value="tenantForm?.name || ''" readonly />
          </UFormField>

          <UFormField label="E-Mail">
            <UInput v-model="createUserForm.email" type="email" />
          </UFormField>

          <UFormField label="Initialpasswort">
            <UInput v-model="createUserForm.password" placeholder="Leer lassen für automatisches Passwort" />
          </UFormField>

          <UFormField label="Vorname für Profil">
            <UInput v-model="createUserForm.first_name" />
          </UFormField>

          <UFormField label="Nachname für Profil">
            <UInput v-model="createUserForm.last_name" />
          </UFormField>

          <UFormField label="Administrative Freigabe">
            <div class="flex items-center gap-3 h-10">
              <USwitch v-model="createUserForm.is_admin" />
              <span class="text-sm text-gray-600">Benutzer darf die Administration öffnen</span>
            </div>
          </UFormField>

          <UFormField label="Multi-Tenant">
            <div class="flex items-center gap-3 h-10">
              <USwitch v-model="createUserForm.multiTenant" />
              <span class="text-sm text-gray-600">Weitere Tenant-Zuordnungen sind erlaubt</span>
            </div>
          </UFormField>

          <UAlert
            title="Automatische Zuordnung"
            description="Der Benutzer wird nach dem Anlegen direkt diesem Tenant zugeordnet und bekommt dort automatisch ein Profil mit den angegebenen Stammdaten."
            color="primary"
            variant="soft"
          />

          <div class="flex justify-end gap-3 pt-2">
            <UButton color="gray" variant="soft" @click="createUserModalOpen = false">
              Abbrechen
            </UButton>
            <UButton type="submit" color="primary" :loading="creatingUser">
              Benutzer anlegen
            </UButton>
          </div>
        </UForm>
      </UCard>
    </template>
  </UModal>

  <div class="mx-5 mb-5">
    <UAlert
      v-if="createdUserPassword"
      title="Initialpasswort für neuen Benutzer"
      :description="createdUserPassword"
      color="amber"
      variant="soft"
      close-button
      @close="createdUserPassword = ''"
    />
  </div>
</template>
