<script setup>
import { ref, computed } from 'vue'
import { Head, router, usePage, useForm } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import { KeyIcon, PlusIcon, TrashIcon, XMarkIcon, ClipboardDocumentIcon, ExclamationTriangleIcon } from '@heroicons/vue/24/outline'
import { useConfirm } from '@/composables/useConfirm'

const { ask } = useConfirm()

const props = defineProps({
    tokens: Array,
    available_abilities: Array,
    sanctum_missing: { type: Boolean, default: false },
})

const page = usePage()
const newToken = computed(() => page.props.flash?.new_token)

const showForm = ref(false)
const showToken = ref(true)

const form = useForm({
    name: '',
    abilities: ['*'],
    expires_in_days: 365,
})

const submit = () => form.post(route('admin.api-tokens.store'), {
    onSuccess: () => { showForm.value = false; form.reset(); form.abilities = ['*']; form.expires_in_days = 365 },
})

const remove = async (t) => {
    const ok = await ask({
        title: 'Onaylayın',
        message: `'${t.name}' token'ı iptal edilsin mi?`,
        variant: 'danger',
        confirmText: 'Sil',
        cancelText: 'İptal',
    })
    if (ok) router.delete(route('admin.api-tokens.destroy', t.id))
}

const copyToken = (token) => {
    navigator.clipboard.writeText(token)
    alert('Kopyalandı!')
}

const toggleAbility = (ab) => {
    const idx = form.abilities.indexOf(ab)
    if (idx >= 0) form.abilities.splice(idx, 1)
    else form.abilities.push(ab)
}
</script>

<template>
    <Head title="API Token'ları" />
    <AdminLayout>
        <template #header>API Token'ları</template>

        <div v-if="sanctum_missing" class="mb-6 rounded-xl border-2 border-orange-300 bg-orange-50 p-5 dark:border-orange-700 dark:bg-orange-950">
            <div class="flex items-start gap-3">
                <ExclamationTriangleIcon class="h-6 w-6 flex-shrink-0 text-orange-600 dark:text-orange-400" />
                <div class="flex-1">
                    <h3 class="font-bold text-orange-900 dark:text-orange-200">Laravel Sanctum kurulu değil</h3>
                    <p class="mt-1 text-sm text-orange-800 dark:text-orange-300">
                        API token özelliği <strong>laravel/sanctum</strong> paketine bağımlıdır. Sunucuda şu komutu çalıştırın:
                    </p>
                    <pre class="mt-3 rounded-lg bg-slate-900 px-4 py-3 text-xs text-slate-100"><code>composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate</code></pre>
                    <p class="mt-3 text-xs text-orange-700 dark:text-orange-400">
                        Sonrasında User modeline <code class="rounded bg-orange-100 px-1 dark:bg-orange-900">use HasApiTokens;</code> trait'ini ekleyin.
                    </p>
                </div>
            </div>
        </div>

        <div v-if="newToken && showToken" class="mb-4 rounded-xl border-2 border-amber-300 bg-amber-50 p-4">
            <div class="flex items-start gap-3">
                <ExclamationTriangleIcon class="h-6 w-6 text-amber-600 flex-shrink-0" />
                <div class="flex-1">
                    <h3 class="font-bold text-amber-900">Token'ı şimdi kopyalayın — bir daha gösterilmez!</h3>
                    <div class="mt-2 flex items-center gap-2">
                        <code class="flex-1 rounded bg-white px-3 py-2 font-mono text-xs break-all">{{ newToken }}</code>
                        <button @click="copyToken(newToken)" class="rounded-lg bg-amber-600 px-3 py-2 text-sm font-medium text-white hover:bg-amber-700">
                            <ClipboardDocumentIcon class="h-4 w-4" />
                        </button>
                    </div>
                    <button @click="showToken = false" class="mt-2 text-xs text-amber-700 underline">Anladım, gizle</button>
                </div>
            </div>
        </div>

        <div class="mb-4 flex justify-end">
            <button @click="showForm = true" class="inline-flex items-center gap-2 rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700">
                <PlusIcon class="h-4 w-4" /> Yeni Token
            </button>
        </div>

        <div v-if="tokens.length === 0" class="rounded-xl border border-dashed border-slate-300 bg-white p-12 text-center">
            <KeyIcon class="mx-auto h-14 w-14 text-slate-300" />
            <h3 class="mt-3 text-lg font-semibold">API token yok</h3>
            <p class="mt-1 text-sm text-slate-500">WHMCS webhook ve harici entegrasyonlar için token oluşturun.</p>
        </div>

        <div v-else class="overflow-hidden rounded-xl border border-slate-200 bg-white shadow-sm">
            <table class="min-w-full divide-y divide-slate-200">
                <thead class="bg-slate-50">
                    <tr>
                        <th class="px-4 py-3 text-left text-xs font-semibold uppercase text-slate-500">Ad</th>
                        <th class="px-4 py-3 text-left text-xs font-semibold uppercase text-slate-500">Yetkiler</th>
                        <th class="px-4 py-3 text-left text-xs font-semibold uppercase text-slate-500">Son Kullanım</th>
                        <th class="px-4 py-3 text-left text-xs font-semibold uppercase text-slate-500">Bitiş</th>
                        <th class="px-4 py-3"></th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100">
                    <tr v-for="t in tokens" :key="t.id" class="hover:bg-slate-50">
                        <td class="px-4 py-2 font-semibold">{{ t.name }}</td>
                        <td class="px-4 py-2">
                            <div class="flex flex-wrap gap-1">
                                <span v-for="ab in t.abilities" :key="ab" class="rounded bg-slate-100 px-2 py-0.5 text-xs font-mono">{{ ab }}</span>
                            </div>
                        </td>
                        <td class="px-4 py-2 text-xs">{{ t.last_used_at || 'Hiç' }}</td>
                        <td class="px-4 py-2 text-xs">{{ t.expires_at || 'Yok' }}</td>
                        <td class="px-4 py-2 text-right">
                            <button @click="remove(t)" class="rounded p-1.5 text-red-500 hover:bg-red-50"><TrashIcon class="h-4 w-4" /></button>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        <div v-if="showForm" class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 p-4">
            <div class="w-full max-w-lg rounded-xl bg-white p-6 shadow-xl">
                <div class="mb-4 flex items-center justify-between">
                    <h3 class="text-lg font-semibold">Yeni API Token</h3>
                    <button @click="showForm = false"><XMarkIcon class="h-5 w-5 text-slate-400" /></button>
                </div>
                <form @submit.prevent="submit" class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium">Token Adı</label>
                        <input v-model="form.name" type="text" placeholder="WHMCS Integration" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm" />
                    </div>
                    <div>
                        <label class="block text-sm font-medium mb-2">Yetkiler</label>
                        <div class="flex flex-wrap gap-2">
                            <button v-for="ab in available_abilities" :key="ab" type="button" @click="toggleAbility(ab)"
                                :class="['rounded-full px-3 py-1 text-xs font-mono', form.abilities.includes(ab) ? 'bg-indigo-600 text-white' : 'bg-slate-100 text-slate-700']">
                                {{ ab }}
                            </button>
                        </div>
                    </div>
                    <div>
                        <label class="block text-sm font-medium">Geçerlilik (gün)</label>
                        <input v-model.number="form.expires_in_days" type="number" min="1" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm" />
                        <p class="mt-1 text-xs text-slate-500">Boş bırakılırsa süresiz.</p>
                    </div>
                    <div class="flex justify-end gap-2">
                        <button type="button" @click="showForm = false" class="rounded-lg border border-slate-300 px-4 py-2 text-sm">İptal</button>
                        <button type="submit" :disabled="form.processing" class="rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700">Oluştur</button>
                    </div>
                </form>
            </div>
        </div>
    </AdminLayout>
</template>
