<template>
  <div class="space-y-4">
    <div class="flex items-center gap-2">
      <UAvatar
        :src="user.avatarUrl || undefined"
        :alt="user.name"
        size="lg"
      />
      <div>
        <p class="text-sm font-bold">
          {{ user.name }}
        </p>
        <p class="text-sm text-neutral-500">
          {{ user.email }}
        </p>
      </div>
    </div>
    <div class="space-y-4 rounded-md bg-neutral-100 p-4 dark:bg-neutral-950">
      <p class="text-sm text-neutral-500">
        {{ $t('superAdmin.deleteUser.description', { name: user.name }) }}
      </p>
      <div
        v-for="teamMember in user.teamMembers"
        :key="teamMember.id"
        class="flex items-center gap-3"
      >
        <UAvatar
          :src="teamMember.team.logo || undefined"
          size="sm"
          :alt="teamMember.team.name + ' logo'"
        />
        <div>
          <p class="text-sm font-medium">
            {{ teamMember.team.name }}
          </p>
          <p class="text-xs text-neutral-500">
            <span class="capitalize">{{ teamMember.role }}</span>
            {{
              teamMember.role === 'owner'
                ? ''
                : $t('superAdmin.deleteUser.ownerLabel', { ownerName: getTeamOwnerName(teamMember.team.ownerId) })
            }}
          </p>
        </div>
      </div>
    </div>

    <div class="flex w-full justify-end gap-2">
      <UButton
        variant="soft"
        color="neutral"
        :label="$t('superAdmin.deleteUser.cancelButton')"
        @click="$emit('cancel')"
      />
      <UButton
        variant="soft"
        color="error"
        :label="$t('superAdmin.deleteUser.deleteButton')"
        :loading="loading"
        @click="deleteUser"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
/* eslint-disable @stylistic/member-delimiter-style */
import type { User } from '~/types/database'

interface TeamMember {
  id: string;
  teamId: string;
  userId: string;
  role: string;
  createdAt: string;
  updatedAt: string;
  team: {
    id: string;
    name: string;
    ownerId: string;
    logo: string;
    slug: string;
    createdAt: string;
    updatedAt: string;
  };
}

type OAuthAccountLite = { providerId?: string, accountId?: string }
interface ExtendedUser extends User {
  avatarUrl?: string
  oauthAccounts?: OAuthAccountLite[]
  teamMembers?: TeamMember[]
}

const props = defineProps<{
  user: ExtendedUser
  users?: User[]
}>()

const emit = defineEmits(['user-deleted', 'cancel'])
const loading = ref(false)
const toast = useToast()
const { t } = useI18n()
const log = useLogger('Delete User')

function getTeamOwnerName(ownerId: string): string {
  if (!ownerId || !props.users?.length) return t('superAdmin.deleteUser.unknown')
  const owner = props.users.find(user => user.id === ownerId)
  return owner?.name || t('superAdmin.deleteUser.unknown')
}

const deleteUser = async () => {
  loading.value = true
  try {
    const apiCall = useApiCall()
    await apiCall('/api/super-admin/users', {
      method: 'DELETE',
      body: { userId: props.user.id }
    })
    toast.add({
      title: t('superAdmin.deleteUser.messages.success'),
      description: t('superAdmin.deleteUser.messages.successDescription'),
      color: 'success'
    })
    emit('user-deleted')
  } catch (error) {
    log.error('Failed to delete user:', error)
    toast.add({
      title: t('superAdmin.deleteUser.messages.errorTitle'),
      description: t('superAdmin.deleteUser.messages.error'),
      color: 'error'
    })
  } finally {
    loading.value = false
  }
}
</script>
