<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="selectedOrganizationId"
              :items="labeledOrganizations"
              value-key="value"
              placeholder="Select organization"
              class="w-64"
            />
            <CreateOrganizationModal />
          </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="invitations.length > 0">
                  <div
                    v-for="invitation in 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="() => handleInvitationCancellation(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-else 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 { organization, user } = useAuth()
const organizationStore = useOrganizationStore()
const { deleteOrganization: betterAuthDeleteOrganization, loadOrganizations } = organizationStore
const { activeOrganization, organizations, invitations } = storeToRefs(organizationStore)

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

onMounted(async () => {
  await loadOrganizations()
})

const labeledOrganizations = computed(() => organizations.value.map((org) => ({ label: org.name, value: org.id })))
const selectedOrganizationId = computed({
  get() {
    return activeOrganization.value?.id
  },
  set(id: string) {
    organizationStore.setActiveOrganization(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 handleInvitationCancellation(invitationId: string) {
  isRevoking.value.push(invitationId)
  await organizationStore.cancelSentInvitation(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>
