<script setup>
import { ref, computed } from 'vue'
import { Head, router, useForm, usePage } from '@inertiajs/vue3'
import CustomerLayout from '@/Layouts/CustomerLayout.vue'
import {
    KeyIcon,
    PlusIcon,
    TrashIcon,
    XMarkIcon,
    DocumentDuplicateIcon,
    CheckCircleIcon,
    CodeBracketIcon,
    InformationCircleIcon,
    ExclamationTriangleIcon,
} from '@heroicons/vue/24/outline'
import EmptyState from '@/Components/EmptyState.vue'
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 showTokenDisplay = ref(false)
const copied = ref(false)

const form = useForm({
    name: '',
    abilities: ['panel:read', 'domains:read'],
    expires_in_days: 90,
})

const submit = () => form.post(route('customer.api-tokens.store'), {
    preserveScroll: true,
    onSuccess: () => {
        showForm.value = false
        showTokenDisplay.value = true
        form.reset()
        form.abilities = ['panel:read', 'domains:read']
        form.expires_in_days = 90
    },
})

const remove = async (t) => {
    const ok = await ask({
        title: 'Onaylayın',
        message: `'${t.name}' token'ı iptal edilecek. Bu token ile yapılan tüm istekler artık başarısız olacak.`,
        variant: 'danger',
        confirmText: 'Sil',
        cancelText: 'İptal',
    })
    if (!ok) return
    router.delete(route('customer.api-tokens.destroy', t.id), { preserveScroll: true })
}

const copyToken = () => {
    navigator.clipboard.writeText(newToken.value)
    copied.value = true
    setTimeout(() => copied.value = false, 2000)
}

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

const selectAll = () => {
    form.abilities = props.available_abilities.map((a) => a.key)
}

const clearAll = () => {
    form.abilities = []
}
</script>

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

        <div v-if="sanctum_missing" class="mb-6 rounded-xl border-2 border-orange-300 bg-orange-50 p-5">
            <div class="flex items-start gap-3">
                <ExclamationTriangleIcon class="h-6 w-6 flex-shrink-0 text-orange-600" />
                <div class="flex-1">
                    <h3 class="font-bold text-orange-900">API token özelliği geçici olarak devre dışı</h3>
                    <p class="mt-1 text-sm text-orange-800">
                        Sunucu yöneticisinden Laravel Sanctum paketinin etkinleştirilmesini isteyin.
                        Etkinleştirildikten sonra programatik (script, CI/CD, mobil app) erişim için
                        kişisel token oluşturabileceksiniz.
                    </p>
                </div>
            </div>
        </div>

        <div v-if="!sanctum_missing" class="mb-4 rounded-xl border border-indigo-200 bg-indigo-50 p-4 text-sm text-indigo-900">
            <div class="flex gap-3">
                <InformationCircleIcon class="h-5 w-5 flex-shrink-0 text-indigo-600" />
                <div>
                    Programatik (script, CI/CD, mobil app) erişim için kişisel API token oluşturun.
                    Her token belirli izinlere (abilities) sahiptir. Token'lar tek-kullanım için gösterilir,
                    kaybederseniz yenisini oluşturmanız gerekir. Bu token'lar <strong>sadece kendi hesabınıza</strong> erişebilir.
                </div>
            </div>
        </div>

        <!-- New token display -->
        <div v-if="showTokenDisplay && newToken" class="mb-4 rounded-xl border-2 border-emerald-300 bg-emerald-50 p-4">
            <div class="flex items-start justify-between gap-3">
                <div class="flex-1">
                    <h4 class="font-semibold text-emerald-900 flex items-center gap-2">
                        <CheckCircleIcon class="h-5 w-5" />
                        Token Oluşturuldu — Şimdi Kopyalayın!
                    </h4>
                    <p class="mt-1 text-sm text-emerald-700">
                        Bu token bir daha gösterilmez. Şimdi güvenli bir yere kaydedin.
                    </p>
                    <div class="mt-3 flex items-center gap-2">
                        <code class="flex-1 rounded-lg border border-emerald-300 bg-white px-3 py-2 font-mono text-xs break-all select-all">{{ newToken }}</code>
                        <button @click="copyToken" class="rounded-lg bg-emerald-600 px-3 py-2 text-xs font-medium text-white hover:bg-emerald-700">
                            <DocumentDuplicateIcon class="h-4 w-4 inline mr-1" />
                            {{ copied ? 'Kopyalandı!' : 'Kopyala' }}
                        </button>
                    </div>
                </div>
                <button @click="showTokenDisplay = false" class="rounded p-1 text-emerald-700 hover:bg-emerald-100">
                    <XMarkIcon class="h-5 w-5" />
                </button>
            </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>

        <EmptyState
            v-if="tokens.length === 0"
            :icon="KeyIcon"
            title="Henüz token yok"
            description="REST API ile entegrasyon için token oluşturun."
        />

        <div v-else class="space-y-3">
            <div v-for="t in tokens" :key="t.id" class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
                <div class="flex items-start justify-between gap-3">
                    <div class="flex-1 min-w-0">
                        <div class="flex items-center gap-2 flex-wrap">
                            <KeyIcon class="h-5 w-5 text-slate-400" />
                            <h3 class="font-semibold text-slate-900">{{ t.name }}</h3>
                            <span v-if="t.is_expired" class="rounded bg-red-100 px-2 py-0.5 text-xs font-semibold text-red-700">Süresi Doldu</span>
                            <span v-else-if="t.expires_at_diff" class="rounded bg-amber-100 px-2 py-0.5 text-xs font-medium text-amber-700">Bitiş: {{ t.expires_at_diff }}</span>
                            <span v-else class="rounded bg-slate-100 px-2 py-0.5 text-xs text-slate-500">Sınırsız</span>
                        </div>
                        <div class="mt-2 flex flex-wrap gap-1">
                            <span v-for="a in t.abilities" :key="a" class="rounded bg-indigo-100 px-1.5 py-0.5 text-[10px] font-medium text-indigo-700">{{ a }}</span>
                        </div>
                        <div class="mt-2 text-xs text-slate-500">
                            Son kullanım: <strong>{{ t.last_used_at_diff || 'hiç' }}</strong>
                            · Oluşturma: {{ t.created_at }}
                        </div>
                    </div>
                    <button @click="remove(t)" class="rounded p-1.5 text-red-500 hover:bg-red-50" title="İptal et">
                        <TrashIcon class="h-4 w-4" />
                    </button>
                </div>
            </div>
        </div>

        <!-- API doc card -->
        <div class="mt-8 rounded-xl border border-slate-200 bg-slate-900 p-5 text-white">
            <h3 class="font-semibold flex items-center gap-2">
                <CodeBracketIcon class="h-5 w-5 text-indigo-400" />
                API Kullanım Örneği
            </h3>
            <pre class="mt-3 overflow-x-auto rounded bg-black/30 p-3 text-xs font-mono">curl -X GET \
  -H "Authorization: Bearer YOUR_TOKEN_HERE" \
  -H "Accept: application/json" \
  {{ $page.props.ziggy?.url ?? '' }}/api/v1/me</pre>
            <p class="mt-3 text-xs text-slate-400">
                API Dokümantasyonu:
                <a href="/api/v1/openapi.json" class="text-indigo-400 hover:underline font-mono text-[11px]">/api/v1/openapi.json</a>
                · Admin API Docs:
                <a href="/admin/api-docs" class="text-indigo-400 hover:underline">API Dokümantasyon</a>
            </p>
        </div>

        <!-- Create form modal -->
        <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-2xl rounded-xl bg-white p-6 shadow-xl max-h-[90vh] overflow-y-auto">
                <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="CI/CD Deploy Script"
                               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">Ne için kullanıldığını hatırlamak için açıklayıcı isim verin.</p>
                        <p v-if="form.errors.name" class="text-xs text-red-600">{{ form.errors.name }}</p>
                    </div>

                    <div>
                        <label class="block text-sm font-medium">Geçerlilik</label>
                        <select v-model.number="form.expires_in_days" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm">
                            <option :value="null">Sınırsız (önerilmez)</option>
                            <option :value="7">7 gün</option>
                            <option :value="30">30 gün</option>
                            <option :value="90">90 gün (önerilen)</option>
                            <option :value="180">180 gün</option>
                            <option :value="365">1 yıl</option>
                        </select>
                    </div>

                    <div>
                        <div class="flex items-center justify-between mb-2">
                            <label class="block text-sm font-medium">İzinler (Abilities)</label>
                            <div class="flex gap-2 text-xs">
                                <button type="button" @click="selectAll" class="text-indigo-600 hover:underline">Tümü</button>
                                <span class="text-slate-300">|</span>
                                <button type="button" @click="clearAll" class="text-slate-600 hover:underline">Hiçbiri</button>
                            </div>
                        </div>
                        <div class="space-y-1 max-h-72 overflow-y-auto rounded-lg border border-slate-200 p-3">
                            <label v-for="a in available_abilities" :key="a.key"
                                   :class="['flex items-start gap-2 rounded p-1.5 cursor-pointer', a.is_dangerous ? 'bg-red-50 hover:bg-red-100 border border-red-200 mb-2' : 'hover:bg-slate-50']">
                                <input type="checkbox" :checked="form.abilities.includes(a.key)" @change="toggleAbility(a.key)" class="mt-0.5" />
                                <div class="flex-1">
                                    <code :class="['font-mono text-xs', a.is_dangerous ? 'text-red-700 font-bold' : 'text-indigo-700']">{{ a.key }}</code>
                                    <span v-if="a.is_dangerous" class="ml-1 text-[10px] font-bold text-red-600 uppercase">⚠ Dikkat</span>
                                    <p class="text-xs text-slate-500">{{ a.description }}</p>
                                </div>
                            </label>
                        </div>
                        <!-- Tam erişim uyarısı -->
                        <div v-if="form.abilities.includes('*')" class="mt-2 rounded-lg bg-red-50 border border-red-200 p-2 text-xs text-red-800">
                            <ExclamationTriangleIcon class="inline h-3.5 w-3.5 mr-1 text-red-600" />
                            <strong>Tam erişim seçildi!</strong> Bu token hesabınızdaki tüm kaynaklara tam programatik erişim sağlar.
                            Yalnızca güvendiğiniz ortamlarda kullanın.
                        </div>
                        <p v-if="form.errors.abilities" class="mt-1 text-xs text-red-600">{{ form.errors.abilities }}</p>
                    </div>

                    <div class="rounded-lg bg-amber-50 p-3 text-xs text-amber-800">
                        <ExclamationTriangleIcon class="inline h-3.5 w-3.5 mr-1" />
                        Token oluşturulduğunda <strong>sadece bir kez</strong> gösterilecek. Kaybederseniz yenisini oluşturmanız gerekir.
                    </div>

                    <div class="flex justify-end gap-2 border-t pt-3">
                        <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 || form.abilities.length === 0"
                                class="rounded-lg bg-indigo-600 px-6 py-2 text-sm font-medium text-white hover:bg-indigo-700 disabled:opacity-50">
                            Token Oluştur
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </CustomerLayout>
</template>
