<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Card, Spin, message, Result } from 'ant-design-vue'
import { apiClient, API } from '../router/api'

const route = useRoute()
const router = useRouter()

const inviteUuid = route.params.inviteUuid as string
const accepting = ref(true)
const accepted = ref(false)
const joinedOrganizationUuid = ref<string | null>(null)

const acceptInvite = async () => {
    try {
        const response = await apiClient.post<{ message?: string; organization?: { uuid?: string } }>(
            API.invites.join(inviteUuid),
        )
        joinedOrganizationUuid.value = response.data?.organization?.uuid || null
        message.success(response.data?.message || 'Successfully joined organization')
        accepted.value = true
        setTimeout(() => {
            router.push(joinedOrganizationUuid.value ? `/organization/${joinedOrganizationUuid.value}` : '/')
        }, 1500)
    } catch {
        router.push('/')
    } finally {
        accepting.value = false
    }
}

onMounted(() => {
    acceptInvite()
})
</script>

<template>
    <div class="page">
        <Spin :spinning="accepting" tip="Accepting invite...">
            <Card class="panel" :bordered="false">
                <Result
                    v-if="accepted"
                    status="success"
                    title="Successfully Joined Organization"
                    sub-title="Redirecting to organization page..."
                />
            </Card>
        </Spin>
    </div>
</template>

<style scoped>
.page {
    max-width: 800px;
    padding: 2rem 1rem;
}

.invite-content {
    text-align: center;
    padding: 2rem;
}

.org-info {
    background: #f8fafc;
    border-radius: 8px;
    padding: 1.5rem;
    margin: 2rem 0;
}

.actions {
    margin-top: 2rem;
}
</style>
