<template>
  <UDashboardPanel>
    <template #header>
      <UDashboardNavbar title="Administration" :ui="{ right: 'gap-3' }">
        <template #leading>
          <UDashboardSidebarCollapse />
        </template>

        <template #right />
      </UDashboardNavbar>

      <UDashboardToolbar>
        <template #left />
      </UDashboardToolbar>
    </template>

    <template #body>
      <div class="flex flex-col gap-4 sm:gap-6 lg:gap-12 w-full lg:max-w-2xl mx-auto">
        <UPageCard
          title="Organization Selection"
          description="Choose an organization or create a new one."
          class="mb-6"
        >
          <div class="flex justify-between items-center">
            <USelect
              v-model="selectedOrgId"
              :items="availableOrganizations"
              value-key="value"
              placeholder="Select organization"
              class="w-64"
            />
            <CreateOrganizationModal @organization-created="setOrganization" />
          </div>
        </UPageCard>

        <UPageCard
          title="Organization Overview"
          description="View your current organization and its details."
          class="mb-6"
        >
          <div class="flex gap-4 items-center">
            <UAvatar :src="activeOrganization?.logo || undefined" size="md" alt="Org Logo" class="rounded" />
            <div>
              <p class="font-semibold">{{ activeOrganization?.name }}</p>
              <p class="text-xs text-gray-500">{{ activeOrganization?.members?.length || 1 }} members</p>
            </div>
          </div>

          <div class="flex justify-end mt-4">
            <UButton color="error" icon="i-lucide-trash" @click="deleteOrganization"> Delete Organization </UButton>
          </div>
        </UPageCard>

        <UPageCard title="Members & Invitations" description="Manage team members and pending invites.">
          <div class="flex flex-col md:flex-row gap-8">
            <!-- Members -->
            <div class="flex-1">
              <p class="font-medium mb-2">Members</p>
              <div v-if="activeOrganization?.members" class="space-y-2">
                <div
                  v-for="member in activeOrganization.members"
                  :key="member.id"
                  class="flex justify-between items-center"
                >
                  <div class="flex items-center gap-2">
                    <UAvatar :src="member.user.image || undefined" size="sm" />
                    <div>
                      <p class="text-sm">{{ member.user.name }}</p>
                      <p class="text-xs text-gray-500">{{ member.role }}</p>
                    </div>
                  </div>
                  <div v-if="user && canRemove({ role: 'owner' }, member)">
                    <UButton size="xs" color="error" @click="organization.removeMember({ memberIdOrEmail: member.id })">
                      {{ member.user.id === user.id ? 'Leave' : 'Remove' }}
                    </UButton>
                  </div>
                </div>
                <div v-if="!activeOrganization?.id" class="flex items-center gap-2">
                  <UAvatar :src="user?.image ?? undefined" />
                  <div>
                    <p class="text-sm">{{ user?.name }}</p>
                    <p class="text-xs text-gray-500">Owner</p>
                  </div>
                </div>
              </div>
            </div>

            <!-- Invitations -->
            <div class="flex-1">
              <p class="font-medium mb-2">Invites</p>
              <div class="space-y-2">
                <template v-if="activeOrganization?.invitations">
                  <div
                    v-for="invitation in activeOrganization?.invitations.filter(
                      (i: Invitation) => i.status === 'pending'
                    )"
                    :key="invitation.id"
                    class="flex justify-between items-center"
                  >
                    <div>
                      <p class="text-sm">{{ invitation.email }}</p>
                      <p class="text-xs text-gray-500">{{ invitation.role }}</p>
                    </div>
                    <div class="flex items-center gap-2">
                      <UButton
                        size="xs"
                        color="error"
                        :loading="isRevoking.includes(invitation.id)"
                        @click="() => handleRevokeInvitation(invitation.id)"
                      >
                        Revoke
                      </UButton>
                      <UButton icon="i-lucide-copy" size="xs" @click="copy(getInviteLink(invitation.id))">
                        {{ copied ? 'Copied!' : 'Copy' }}
                      </UButton>
                    </div>
                  </div>
                </template>
                <p v-if="!activeOrganization?.invitations?.length" class="text-sm text-gray-500">
                  No active invitations
                </p>
                <p v-if="!activeOrganization?.id" class="text-xs text-gray-500">
                  You can't invite members to your personal workspace.
                </p>
              </div>
            </div>
          </div>

          <div class="flex justify-end mt-6">
            <InviteMemberModal
              v-if="activeOrganization?.id"
              :organization="activeOrganization"
              @update="activeOrganization = $event"
            />
          </div>
        </UPageCard>
      </div>
    </template>
  </UDashboardPanel>
</template>

<script setup lang="ts">
import { useClipboard } from '@vueuse/core'
import type { Invitation } from 'better-auth/plugins'

const { copy, copied } = useClipboard()
const toast = useToast()

const { organization } = useAuth()
const { deleteOrganization: betterAuthDeleteOrganization, activeOrganization, selectedOrgId } = useBetterAuth()

const organizations = ref<
  Array<{ id: string; name: string; slug: string; createdAt: Date; logo?: string | null; metadata?: unknown }>
>([])
const availableOrganizations = computed(() => organizations.value.map((org) => ({ label: org.name, value: org.id })))

const { user } = await useAuth()

const isRevoking = ref<string[]>([])

watch(selectedOrgId, async (newId) => {
  const { data } = await organization.setActive({ organizationId: newId || null })
  activeOrganization.value = data
})

await loadOrganizations()

async function loadOrganizations() {
  try {
    const response = await organization.list()
    organizations.value = response.data || []
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : 'Failed to load organizations'
    toast.add({ title: 'Error', description: errorMessage, color: 'error' })
  }
}

async function setOrganization(id: string | undefined) {
  await loadOrganizations()
  selectedOrgId.value = id
}

function isAdminOrOwner(member: { role: string }) {
  return member.role === 'owner' || member.role === 'admin'
}

function canRemove(current: { role: string }, target: { role: string }) {
  return target.role !== 'owner' && isAdminOrOwner(current)
}

async function handleRevokeInvitation(invitationId: string) {
  isRevoking.value.push(invitationId)
  await organization.cancelInvitation(
    { invitationId },
    {
      onSuccess: () => {
        toast.add({ title: 'Success', description: 'Invitation revoked', color: 'success' })
        isRevoking.value = isRevoking.value.filter((id) => id !== invitationId)
        if (activeOrganization.value) {
          activeOrganization.value.invitations = activeOrganization.value.invitations.filter(
            (invitation: Invitation) => invitation.id !== invitationId
          )
        }
      },
      onError: (ctx) => {
        toast.add({ title: 'Error', description: ctx.error.message, color: 'error' })
        isRevoking.value = isRevoking.value.filter((id) => id !== invitationId)
      }
    }
  )
}

function getInviteLink(inviteId: string): string {
  return `${window.location.origin}/accept-invitation/${inviteId}`
}

async function deleteOrganization() {
  if (!activeOrganization.value?.id) return

  const confirmed = confirm(
    `Are you sure you want to delete the organization "${activeOrganization.value.name}"? This cannot be undone.`
  )

  if (!confirmed) return

  await betterAuthDeleteOrganization()
}
</script>
