<script lang="ts" setup>
import type { FactorRouter, FactorUser } from '@factor/api'
import { useService, vue } from '@factor/api'
import type { TableCell } from './ElTable.vue'
import ElTable from './ElTable.vue'

const { factorRouter, factorUser } = useService<{
  factorRouter: FactorRouter
  factorUser: FactorUser
}>()

const activeOrganizations = factorUser.activeOrganizations
const formattedData = vue.computed(() => {
  if (!activeOrganizations.value)
    return []
  const rows = activeOrganizations.value.map((org) => {
    const memberAccess = org.relation?.memberAccess
    const canManage = factorUser.priv.userCan({
      capability: 'canManage',
      memberAccess,
    })
    return [
      org.organizationId,
      org.organizationName,
      canManage ? org.members.length : '-',
      memberAccess,
      canManage
        ? ({
            type: 'link',
            text: 'Settings',
            path: (organizationId: string) =>
              factorRouter.link('orgSettings', { organizationId }).value || '',
          } as const)
        : ({
            type: 'callback',
            text: 'Leave',
            callback: (_organizationId: string) => {
              const _confirmed = confirm(
                'Are you sure you want to leave this organization?',
              )
              // TODO
            },
          } as const),
    ]
  })
  const r = [['', 'Name', 'Members', 'Relation', ''], ...rows] as TableCell[][]

  return r
})

async function handleRowClick(organizationId: string) {
  const makeActive = activeOrganizations.value.find(
    o => organizationId === o.organizationId,
  )
  if (makeActive)
    await factorRouter.goto('dashboard', { organizationId })
}
</script>

<template>
  <ElTable
    :table="formattedData"
    :on-row-click="handleRowClick"
    :empty="{
      title: 'No organizations found',
      description: 'Create one to get started',
    }"
  />
</template>
