<template>
  <PageHeader :title="profile.name" :editing-metadata="profile" />

  <div class="tw-flex tw-gap-6 tw-items-start tw-flex-wrap">
    <ASection :title="t('profile.singular')" class="tw-w-fit tw-flex-none">
      <template #header>
        <AProfileDeletionFlow :profile="profile" standalone class="tw-ml-auto" />
      </template>

      <AFieldset class="md:tw-min-w-[500px] tw-max-w-2xl" :title="t('profileDetails.data')">
        <AProfileEditor :profile="profile" admin-mode />
      </AFieldset>
    </ASection>

    <ASection
      v-if="owners.value.length > 0"
      :title="t('profileDetails.assignedAccounts')"
      class="tw-flex-1 md:tw-flex-none tw-w-fit"
    >
      <div class="tw-flex tw-gap-6 tw-items-start tw-flex-wrap">
        <template v-for="user in owners.value" :key="user.id">
          <AUserIdentity v-slot="{ identity }" :user="user">
            <AFieldset
              as="form"
              title-tag="h3"
              :title="identity.name || identity.username"
              class="md:tw-min-w-[380px] tw-max-w-lg tw-flex-1"
            >
              <AUserEditor :user="user" />
            </AFieldset>
          </AUserIdentity>
        </template>
      </div>
    </ASection>
  </div>
</template>

<script setup lang="ts">
import { useRelationList } from '@/form'
import { useI18n } from '@/i18n'
import { useProfileStore, useUserStore } from '@/stores'
import { useBreadcrumbs } from '@/stores/nav'
import { Profile } from '@/types'

import PageHeader from '@/components/PageHeader.vue'
import AUserIdentity from '@/components/identities/AUserIdentity.vue'
import AUserEditor from '@/components/identities/AUserEditor.vue'
import AProfileEditor from '@/components/identities/AProfileEditor.vue'
import AFieldset from '@/components/generic/AFieldset.vue'
import ASection from '@/components/generic/ASection.vue'
import AProfileDeletionFlow from '@/components/identities/AProfileDeletionFlow.vue'

const props = defineProps<{
  profile: Profile
}>()

const { t } = useI18n()
const profileStore = useProfileStore()
const userStore = useUserStore()

const owners = useRelationList(profileStore, () => props.profile, 'ownerIds', userStore)

useBreadcrumbs(() => [
  { title: t('navigation.profiles'), route: { name: 'profiles' } },
  {
    title: props.profile.name,
    route: { name: 'profile', params: { profileId: props.profile.id.toString() } },
  },
])
</script>