<template>
  <UModal v-model:open="open" title="Invite Member" description="Invite a member to your organization">
    <UButton icon="i-lucide-mail-plus" variant="outline" size="sm" @click="open = true"> Invite Member </UButton>

    <template #body>
      <UForm :state="form" class="space-y-4" @submit="handleSubmit">
        <UFormField label="Email" name="email">
          <UInput v-model="form.email" type="email" placeholder="Email" class="w-full" />
        </UFormField>

        <UFormField label="Role" name="role">
          <USelect
            v-model="form.role"
            :items="roleOptions"
            placeholder="Select a role"
            value-key="value"
            class="w-full"
          />
        </UFormField>

        <div class="flex justify-end">
          <UButton type="submit" :loading="loading">
            {{ loading ? 'Inviting...' : 'Invite' }}
          </UButton>
        </div>
      </UForm>
    </template>
  </UModal>
</template>

<script setup lang="ts">
defineProps<{
  organization: ActiveOrganization
}>()

const { inviteMember } = useBetterAuth()

const open = ref(false)
const loading = ref(false)

const form = ref({
  email: '',
  role: 'member'
})

const roleOptions = [
  { label: 'Admin', value: 'admin' },
  { label: 'Member', value: 'member' }
]

watch(open, (val) => {
  if (val) {
    form.value = { email: '', role: 'member' }
  }
})

async function handleSubmit() {
  loading.value = true
  try {
    await inviteMember(form.value.email, form.value.role as 'member' | 'admin')
    open.value = false
    useToast().add({ title: 'Invitation sent', color: 'success' })
  } finally {
    loading.value = false
  }
}
</script>
