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

const { ask } = useConfirm()

const props = defineProps({ keys: Array })

// ─── Modals ──────────────────────────────────────────────────────────────────
const showGenerate = ref(false)
const showImport   = ref(false)
const viewKey      = ref(null)   // key object currently shown in "View" modal
const copied       = ref(false)

// ─── Forms ───────────────────────────────────────────────────────────────────
const genForm = useForm({
    name:            '',
    email:           '',
    comment:         '',
    key_size:        2048,
    expires_in_days: null,
    never_expires:   true,
})

const importForm = useForm({
    name:       '',
    email:      '',
    public_key: '',
})

// ─── Helpers ─────────────────────────────────────────────────────────────────
/**
 * Format a 40-char hex fingerprint into 5-block × 8-char groups:
 * '1A2B3C4D5E6F7890ABCDEF1234567890ABCDEF12'
 * → '1A2B 3C4D  5E6F 7890  ABCD EF12  3456 7890  ABCD EF12'
 * (cPanel style: 4-char sub-groups, space between pairs, double-space between word-groups)
 */
const formatFingerprint = (fp) => {
    if (!fp || fp.length !== 40) return fp ?? '—'
    // chunk into 4-char pieces
    const chunks = fp.match(/.{1,4}/g) // ['1A2B','3C4D','5E6F','7890', ...]
    // group into pairs: ['1A2B 3C4D', '5E6F 7890', ...]
    const pairs = []
    for (let i = 0; i < chunks.length; i += 2) {
        pairs.push(chunks.slice(i, i + 2).join(' '))
    }
    return pairs.join('  ')
}

const isExpired = (key) => {
    if (!key.expires_at) return false
    return new Date(key.expires_at) < new Date()
}

const copyPublicKey = async () => {
    if (!viewKey.value?.public_key) return
    await navigator.clipboard.writeText(viewKey.value.public_key)
    copied.value = true
    setTimeout(() => { copied.value = false }, 2000)
}

// ─── Actions ─────────────────────────────────────────────────────────────────
const submitGenerate = () => {
    const data = { ...genForm.data() }
    if (data.never_expires) data.expires_in_days = null
    delete data.never_expires

    genForm.transform(() => data).post(route('customer.security.gpg.store'), {
        preserveScroll: true,
        onSuccess: () => {
            showGenerate.value = false
            genForm.reset()
            genForm.key_size      = 2048
            genForm.never_expires = true
        },
    })
}

const submitImport = () => importForm.post(route('customer.security.gpg.import'), {
    preserveScroll: true,
    onSuccess: () => { showImport.value = false; importForm.reset() },
})

const remove = async (key) => {
    const ok = await ask({
        title: 'Onaylayın',
        message: `"${key.name}" (${key.key_id}) anahtarı silinsin mi?`,
        variant: 'danger',
        confirmText: 'Sil',
        cancelText: 'İptal',
    })
    if (!ok) return
    router.delete(route('customer.security.gpg.destroy', key.id), { preserveScroll: true })
}
</script>

<template>
    <Head title="PGP Anahtarları" />
    <CustomerLayout>
        <template #header>PGP Anahtarları</template>

        <!-- Info banner -->
        <div class="mb-4 rounded-xl border border-violet-200 bg-violet-50 p-4 text-sm text-violet-900">
            <div class="flex gap-3">
                <InformationCircleIcon class="h-5 w-5 flex-shrink-0 text-violet-600" />
                <div>
                    <strong>PGP (Pretty Good Privacy):</strong> E-posta ve dosyalarınızı
                    şifrelemek veya dijital imzalamak için kullanılan açık-anahtar kriptografisi standardı.
                    Oluşturduğunuz anahtarlar Thunderbird, GPG, Kleopatra gibi istemcilerde kullanılabilir.
                </div>
            </div>
        </div>

        <!-- Action buttons -->
        <div class="mb-4 flex flex-wrap gap-2 justify-end">
            <button
                @click="showImport = true"
                class="inline-flex items-center gap-2 rounded-lg border border-slate-300 bg-white px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50"
            >
                <ArrowUpTrayIcon class="h-4 w-4" /> Public Key İçe Aktar
            </button>
            <button
                @click="showGenerate = 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 Anahtar Oluştur
            </button>
        </div>

        <!-- Empty state -->
        <div v-if="keys.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">Henüz PGP anahtarı yok</h3>
            <p class="mt-1 text-sm text-slate-500">E-posta şifreleme veya dijital imza için bir anahtar çifti oluşturun.</p>
        </div>

        <!-- Keys table -->
        <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 text-sm">
                <thead class="bg-slate-50 text-xs uppercase text-slate-500">
                    <tr>
                        <th class="px-4 py-2 text-left">Ad / E-posta</th>
                        <th class="px-4 py-2 text-left">Key ID</th>
                        <th class="px-4 py-2 text-left hidden lg:table-cell">Parmak İzi</th>
                        <th class="px-4 py-2 text-left">Boyut</th>
                        <th class="px-4 py-2 text-left">Son Geçerlilik</th>
                        <th class="px-4 py-2 text-left">Tür</th>
                        <th class="px-4 py-2"></th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100">
                    <tr v-for="k in keys" :key="k.id" class="hover:bg-slate-50">
                        <!-- Name + Email -->
                        <td class="px-4 py-3">
                            <div class="font-medium">{{ k.name }}</div>
                            <div class="text-xs text-slate-500">{{ k.email }}</div>
                            <div v-if="k.comment" class="text-xs text-slate-400 italic">{{ k.comment }}</div>
                        </td>

                        <!-- Key ID -->
                        <td class="px-4 py-3 font-mono text-xs font-semibold text-slate-700">
                            {{ k.key_id ?? '—' }}
                        </td>

                        <!-- Fingerprint (hidden on small screens) -->
                        <td class="px-4 py-3 hidden lg:table-cell">
                            <span class="font-mono text-xs text-slate-500 tracking-wide">
                                {{ formatFingerprint(k.fingerprint) }}
                            </span>
                        </td>

                        <!-- Key size -->
                        <td class="px-4 py-3 text-xs text-slate-600">
                            <span v-if="k.key_size > 0">{{ k.key_size }}-bit</span>
                            <span v-else class="text-slate-400">—</span>
                        </td>

                        <!-- Expiry -->
                        <td class="px-4 py-3 text-xs">
                            <span v-if="!k.expires_at" class="text-slate-400">Asla</span>
                            <span
                                v-else
                                :class="isExpired(k) ? 'rounded bg-red-100 px-2 py-0.5 font-semibold text-red-700' : 'text-slate-600'"
                            >
                                {{ k.expires_at.slice(0, 10) }}
                                <span v-if="isExpired(k)"> (Süresi Doldu)</span>
                            </span>
                        </td>

                        <!-- Type badge -->
                        <td class="px-4 py-3">
                            <span
                                :class="k.has_private
                                    ? 'rounded bg-emerald-100 px-2 py-0.5 text-xs font-semibold text-emerald-700'
                                    : 'rounded bg-slate-100 px-2 py-0.5 text-xs font-semibold text-slate-600'"
                            >
                                {{ k.has_private ? 'Çift' : 'Yalnız Public' }}
                            </span>
                        </td>

                        <!-- Actions -->
                        <td class="px-4 py-3">
                            <div class="flex items-center justify-end gap-1">
                                <!-- View -->
                                <button
                                    @click="viewKey = k"
                                    title="Public key'i görüntüle"
                                    class="rounded p-1.5 text-slate-500 hover:bg-slate-100"
                                >
                                    <ClipboardDocumentIcon class="h-4 w-4" />
                                </button>
                                <!-- Download -->
                                <a
                                    :href="route('customer.security.gpg.download', k.id)"
                                    title="İndir (.asc)"
                                    class="rounded p-1.5 text-indigo-500 hover:bg-indigo-50"
                                >
                                    <ArrowDownTrayIcon class="h-4 w-4" />
                                </a>
                                <!-- Delete -->
                                <button
                                    @click="remove(k)"
                                    title="Sil"
                                    class="rounded p-1.5 text-red-500 hover:bg-red-50"
                                >
                                    <TrashIcon class="h-4 w-4" />
                                </button>
                            </div>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        <!-- ─── Generate Modal ──────────────────────────────────────────────── -->
        <div v-if="showGenerate" class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 p-4">
            <div class="w-full max-w-md rounded-xl bg-white p-6 shadow-xl">
                <div class="mb-4 flex items-center justify-between">
                    <h3 class="text-lg font-semibold">Yeni PGP Anahtarı Oluştur</h3>
                    <button @click="showGenerate = false"><XMarkIcon class="h-5 w-5 text-slate-400" /></button>
                </div>

                <form @submit.prevent="submitGenerate" class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium">Ad Soyad <span class="text-red-500">*</span></label>
                        <input
                            v-model="genForm.name"
                            type="text"
                            placeholder="Ahmet Yılmaz"
                            class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm"
                            required
                        />
                        <p v-if="genForm.errors.name" class="mt-1 text-xs text-red-600">{{ genForm.errors.name }}</p>
                    </div>

                    <div>
                        <label class="block text-sm font-medium">E-posta <span class="text-red-500">*</span></label>
                        <input
                            v-model="genForm.email"
                            type="email"
                            placeholder="ahmet@sirket.com"
                            class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm"
                            required
                        />
                        <p v-if="genForm.errors.email" class="mt-1 text-xs text-red-600">{{ genForm.errors.email }}</p>
                    </div>

                    <div>
                        <label class="block text-sm font-medium">Yorum (opsiyonel)</label>
                        <input
                            v-model="genForm.comment"
                            type="text"
                            placeholder="İş e-postası"
                            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">Anahtar Boyutu</label>
                        <select
                            v-model.number="genForm.key_size"
                            class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm"
                        >
                            <option :value="2048">2048-bit (varsayılan, hızlı)</option>
                            <option :value="4096">4096-bit (daha güçlü)</option>
                        </select>
                    </div>

                    <div>
                        <label class="block text-sm font-medium">Son Geçerlilik</label>
                        <label class="mt-1 flex items-center gap-2 cursor-pointer text-sm">
                            <input v-model="genForm.never_expires" type="checkbox" />
                            <span>Asla sona ermez</span>
                        </label>
                        <input
                            v-if="!genForm.never_expires"
                            v-model.number="genForm.expires_in_days"
                            type="number"
                            min="7"
                            max="3650"
                            placeholder="365 (gün)"
                            class="mt-2 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm"
                        />
                        <p v-if="genForm.errors.expires_in_days" class="mt-1 text-xs text-red-600">{{ genForm.errors.expires_in_days }}</p>
                    </div>

                    <div class="flex justify-end gap-2 border-t pt-3">
                        <button
                            type="button"
                            @click="showGenerate = false"
                            class="rounded-lg border border-slate-300 px-4 py-2 text-sm"
                        >
                            İptal
                        </button>
                        <button
                            type="submit"
                            :disabled="genForm.processing"
                            class="rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700 disabled:opacity-50"
                        >
                            Oluştur
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- ─── Import Modal ────────────────────────────────────────────────── -->
        <div v-if="showImport" 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">Public Key İçe Aktar</h3>
                    <button @click="showImport = false"><XMarkIcon class="h-5 w-5 text-slate-400" /></button>
                </div>

                <form @submit.prevent="submitImport" class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium">Ad Soyad <span class="text-red-500">*</span></label>
                        <input
                            v-model="importForm.name"
                            type="text"
                            placeholder="Alıcının adı"
                            class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm"
                            required
                        />
                        <p v-if="importForm.errors.name" class="mt-1 text-xs text-red-600">{{ importForm.errors.name }}</p>
                    </div>

                    <div>
                        <label class="block text-sm font-medium">E-posta <span class="text-red-500">*</span></label>
                        <input
                            v-model="importForm.email"
                            type="email"
                            placeholder="alici@sirket.com"
                            class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm"
                            required
                        />
                        <p v-if="importForm.errors.email" class="mt-1 text-xs text-red-600">{{ importForm.errors.email }}</p>
                    </div>

                    <div>
                        <label class="block text-sm font-medium">PGP Public Key Bloğu <span class="text-red-500">*</span></label>
                        <textarea
                            v-model="importForm.public_key"
                            rows="8"
                            placeholder="-----BEGIN PGP PUBLIC KEY BLOCK-----&#10;...&#10;-----END PGP PUBLIC KEY BLOCK-----"
                            class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 font-mono text-xs"
                            required
                            minlength="200"
                        ></textarea>
                        <p class="mt-1 text-xs text-slate-500">Sadece public key — private key ASLA paylaşmayın.</p>
                        <p v-if="importForm.errors.public_key" class="mt-1 text-xs text-red-600">{{ importForm.errors.public_key }}</p>
                    </div>

                    <div class="flex justify-end gap-2 border-t pt-3">
                        <button
                            type="button"
                            @click="showImport = false"
                            class="rounded-lg border border-slate-300 px-4 py-2 text-sm"
                        >
                            İptal
                        </button>
                        <button
                            type="submit"
                            :disabled="importForm.processing"
                            class="rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700 disabled:opacity-50"
                        >
                            İçe Aktar
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- ─── View / Copy Modal ───────────────────────────────────────────── -->
        <div v-if="viewKey" 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">
                <div class="mb-4 flex items-center justify-between">
                    <div>
                        <h3 class="text-lg font-semibold">Public Key</h3>
                        <p class="text-xs text-slate-500 font-mono mt-0.5">{{ viewKey.name }} &lt;{{ viewKey.email }}&gt;</p>
                    </div>
                    <button @click="viewKey = null"><XMarkIcon class="h-5 w-5 text-slate-400" /></button>
                </div>

                <div class="mb-3 rounded-lg border border-slate-200 bg-slate-50 p-1">
                    <p class="px-2 py-1 text-xs text-slate-500 font-mono tracking-wide">
                        Parmak izi: {{ formatFingerprint(viewKey.fingerprint) }}
                    </p>
                </div>

                <textarea
                    :value="viewKey.public_key"
                    readonly
                    rows="10"
                    class="w-full rounded-lg border border-slate-200 bg-slate-50 px-3 py-2 font-mono text-xs text-slate-700 focus:outline-none"
                ></textarea>

                <div class="mt-3 flex justify-end gap-2">
                    <button
                        @click="copyPublicKey"
                        class="inline-flex items-center gap-2 rounded-lg border border-slate-300 px-4 py-2 text-sm hover:bg-slate-50"
                    >
                        <ClipboardDocumentIcon class="h-4 w-4" />
                        {{ copied ? 'Kopyalandı!' : 'Kopyala' }}
                    </button>
                    <a
                        :href="route('customer.security.gpg.download', viewKey.id)"
                        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"
                    >
                        <ArrowDownTrayIcon class="h-4 w-4" /> İndir (.asc)
                    </a>
                </div>
            </div>
        </div>

    </CustomerLayout>
</template>
