<script setup>
import { ref } from 'vue'
import { Head, Link, useForm, router } from '@inertiajs/vue3'
import CustomerLayout from '@/Layouts/CustomerLayout.vue'
import {
    ShieldCheckIcon,
    KeyIcon,
    ArrowPathIcon,
    DocumentDuplicateIcon,
    EyeIcon,
    EyeSlashIcon,
    InformationCircleIcon,
    QrCodeIcon,
    CheckCircleIcon,
    ExclamationTriangleIcon,
} from '@heroicons/vue/24/outline'
import { useConfirm } from '@/composables/useConfirm'

const { ask } = useConfirm()

const props = defineProps({
    is_enabled:     { type: Boolean, default: false },
    is_confirmed:   { type: Boolean, default: false },
    qr_svg:         { type: String,  default: null },
    secret_otp_uri: { type: String,  default: null },
    secret_key:     { type: String,  default: null },
    recovery_codes: { type: Array,   default: () => [] },
})

// ── Enable form — POST /user/two-factor-authentication ────────────────────────
const enableForm = useForm({})
const enable = () => enableForm.post('/user/two-factor-authentication', {
    preserveScroll: true,
})

// ── Confirm form — POST /user/confirmed-two-factor-authentication ─────────────
const confirmForm = useForm({ code: '' })
const confirm = () => confirmForm.post('/user/confirmed-two-factor-authentication', {
    preserveScroll: true,
    onSuccess: () => confirmForm.reset(),
})

// ── Disable form — DELETE /user/two-factor-authentication ─────────────────────
const disableForm = useForm({})
const disable = async () => {
    const ok = await ask({
        title: 'Onaylayın',
        message: '2FA devre dışı bırakılsın mı? Bu işlem geri alınamaz.',
        variant: 'danger',
        confirmText: 'Sil',
        cancelText: 'İptal',
    })
    if (!ok) return
    disableForm.delete('/user/two-factor-authentication', { preserveScroll: true })
}

// ── Regenerate recovery codes — POST /user/two-factor-recovery-codes ──────────
const regenForm = useForm({})
const regenerate = async () => {
    const ok = await ask({
        title: 'Onaylayın',
        message: 'Recovery kodları sıfırlansın mı? Eski kodlar geçersiz olur.',
        variant: 'warning',
        confirmText: 'Onayla',
        cancelText: 'İptal',
    })
    if (!ok) return
    regenForm.post('/user/two-factor-recovery-codes', { preserveScroll: true })
}

// ── UI state ──────────────────────────────────────────────────────────────────
const showCodes    = ref(false)
const copiedAll    = ref(false)

const copyAll = async () => {
    const text = props.recovery_codes.join('\n')
    await navigator.clipboard.writeText(text)
    copiedAll.value = true
    setTimeout(() => { copiedAll.value = false }, 2000)
}
</script>

<template>
    <Head title="İki Adımlı Doğrulama" />
    <CustomerLayout>
        <template #header>Hesap Güvenliği</template>

        <!-- Tab nav -->
        <div class="mb-4 flex flex-wrap gap-1 border-b border-slate-200 text-sm">
            <Link :href="route('customer.account.show')" class="px-4 py-2 text-slate-600 hover:text-slate-900">Hesap Bilgileri</Link>
            <span class="px-4 py-2 font-medium border-b-2 border-indigo-600 text-indigo-700">İki Adımlı Doğrulama</span>
        </div>

        <!-- ═══════════════════════════════════════════════════════════════════
             STATE A: 2FA Disabled
        ════════════════════════════════════════════════════════════════════ -->
        <div v-if="!is_enabled" class="rounded-xl border border-slate-200 bg-white p-8 shadow-sm text-center max-w-xl mx-auto">
            <ShieldCheckIcon class="mx-auto h-16 w-16 text-slate-300" />
            <h2 class="mt-4 text-xl font-semibold text-slate-800">İki Adımlı Doğrulama Etkin Değil</h2>
            <p class="mt-2 text-sm text-slate-500">
                Hesabınızı ekstra bir güvenlik katmanıyla koruyun. Giriş yaparken telefon
                uygulamanızdan (Google Authenticator, Authy vb.) bir kod girmeniz istenir.
            </p>

            <div class="mt-5 rounded-xl border border-indigo-100 bg-indigo-50 p-4 text-left text-sm text-indigo-900">
                <div class="flex gap-3">
                    <InformationCircleIcon class="h-5 w-5 flex-shrink-0 text-indigo-500 mt-0.5" />
                    <ul class="space-y-1">
                        <li>Google Authenticator veya Authy gibi bir TOTP uygulaması gerekir.</li>
                        <li>Bir QR kodu taratacaksınız (yaklaşık 1 dakika).</li>
                        <li>Kurtarma kodlarını güvenli bir yere kaydedin.</li>
                    </ul>
                </div>
            </div>

            <button
                type="button"
                :disabled="enableForm.processing"
                @click="enable"
                class="mt-6 inline-flex items-center gap-2 rounded-lg bg-indigo-600 px-6 py-2.5 text-sm font-medium text-white hover:bg-indigo-700 disabled:opacity-50"
            >
                <ShieldCheckIcon class="h-4 w-4" />
                2FA'yı Etkinleştir
            </button>
        </div>

        <!-- ═══════════════════════════════════════════════════════════════════
             STATE B: Enabled but not confirmed
        ════════════════════════════════════════════════════════════════════ -->
        <div v-else-if="is_enabled && !is_confirmed" class="max-w-xl mx-auto space-y-4">
            <!-- Warning banner -->
            <div class="rounded-xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-900">
                <div class="flex gap-3">
                    <ExclamationTriangleIcon class="h-5 w-5 flex-shrink-0 text-amber-600 mt-0.5" />
                    <div>
                        <strong>Onay Gerekiyor</strong> — Kimlik doğrulama uygulamanızla QR kodu taratın,
                        ardından üretilen 6 haneli kodu girin.
                    </div>
                </div>
            </div>

            <!-- QR code card -->
            <div class="rounded-xl border border-slate-200 bg-white p-6 shadow-sm">
                <h3 class="mb-4 flex items-center gap-2 text-base font-semibold text-slate-800">
                    <QrCodeIcon class="h-5 w-5 text-indigo-500" />
                    1. Adım — QR Kodu Tarat
                </h3>

                <div class="flex justify-center mb-4">
                    <!-- eslint-disable-next-line vue/no-v-html -->
                    <div v-if="qr_svg" class="rounded-lg border border-slate-200 p-3" v-html="qr_svg" />
                    <div v-else class="flex h-40 w-40 items-center justify-center rounded-lg border border-dashed border-slate-300 bg-slate-50 text-xs text-slate-400">
                        QR yükleniyor…
                    </div>
                </div>

                <p class="text-xs text-slate-500 text-center mb-2">
                    QR okutamıyorsanız kodu manuel girin:
                </p>
                <p class="text-center font-mono text-sm font-semibold tracking-widest text-slate-700 bg-slate-50 border border-slate-200 rounded-lg py-2 px-4 select-all">
                    {{ secret_key ?? '••••••••••••••••' }}
                </p>
            </div>

            <!-- Confirm code card -->
            <div class="rounded-xl border border-slate-200 bg-white p-6 shadow-sm">
                <h3 class="mb-4 flex items-center gap-2 text-base font-semibold text-slate-800">
                    <KeyIcon class="h-5 w-5 text-indigo-500" />
                    2. Adım — Kodu Onayla
                </h3>

                <form @submit.prevent="confirm" class="flex flex-col gap-3">
                    <div>
                        <label class="block text-sm font-medium text-slate-700 mb-1">6 Haneli Doğrulama Kodu</label>
                        <input
                            v-model="confirmForm.code"
                            type="text"
                            inputmode="numeric"
                            autocomplete="one-time-code"
                            maxlength="6"
                            placeholder="000000"
                            class="w-full rounded-lg border border-slate-300 px-4 py-2.5 text-center font-mono text-2xl tracking-widest focus:border-indigo-400 focus:ring-1 focus:ring-indigo-300"
                        />
                        <p v-if="confirmForm.errors.code" class="mt-1 text-xs text-red-600">{{ confirmForm.errors.code }}</p>
                    </div>

                    <button
                        type="submit"
                        :disabled="confirmForm.processing || confirmForm.code.length < 6"
                        class="w-full rounded-lg bg-emerald-600 py-2.5 text-sm font-medium text-white hover:bg-emerald-700 disabled:opacity-50"
                    >
                        Onayla ve Etkinleştir
                    </button>

                    <button
                        type="button"
                        @click="disable"
                        class="w-full rounded-lg border border-slate-200 py-2 text-sm text-slate-600 hover:bg-slate-50"
                    >
                        İptal — 2FA'yı Devre Dışı Bırak
                    </button>
                </form>
            </div>
        </div>

        <!-- ═══════════════════════════════════════════════════════════════════
             STATE C: Enabled + Confirmed
        ════════════════════════════════════════════════════════════════════ -->
        <div v-else-if="is_enabled && is_confirmed" class="max-w-xl mx-auto space-y-4">
            <!-- Success card -->
            <div class="rounded-xl border border-emerald-200 bg-emerald-50 p-5 shadow-sm">
                <div class="flex items-start gap-3">
                    <CheckCircleIcon class="h-7 w-7 flex-shrink-0 text-emerald-600 mt-0.5" />
                    <div>
                        <h2 class="text-base font-semibold text-emerald-900">
                            İki Adımlı Doğrulama Etkin ve Onaylandı
                        </h2>
                        <p class="mt-1 text-sm text-emerald-800">
                            Hesabınız ek güvenlik katmanıyla korunuyor. Giriş yaparken
                            kimlik doğrulama uygulamanızdan kod girmeniz istenecek.
                        </p>
                    </div>
                </div>
            </div>

            <!-- Recovery codes card -->
            <div class="rounded-xl border border-slate-200 bg-white p-6 shadow-sm">
                <div class="mb-4 flex items-center justify-between">
                    <h3 class="flex items-center gap-2 text-base font-semibold text-slate-800">
                        <KeyIcon class="h-5 w-5 text-indigo-500" />
                        Kurtarma Kodları
                    </h3>
                    <div class="flex items-center gap-2">
                        <button
                            type="button"
                            @click="showCodes = !showCodes"
                            class="inline-flex items-center gap-1.5 rounded-lg border border-slate-300 bg-white px-3 py-1.5 text-xs font-medium text-slate-700 hover:bg-slate-50"
                        >
                            <component :is="showCodes ? EyeSlashIcon : EyeIcon" class="h-3.5 w-3.5" />
                            {{ showCodes ? 'Gizle' : 'Göster' }}
                        </button>
                        <button
                            v-if="showCodes && recovery_codes.length"
                            type="button"
                            @click="copyAll"
                            class="inline-flex items-center gap-1.5 rounded-lg border border-slate-300 bg-white px-3 py-1.5 text-xs font-medium text-slate-700 hover:bg-slate-50"
                        >
                            <DocumentDuplicateIcon class="h-3.5 w-3.5" />
                            {{ copiedAll ? 'Kopyalandı!' : 'Tümünü Kopyala' }}
                        </button>
                    </div>
                </div>

                <div v-if="showCodes && recovery_codes.length">
                    <div class="rounded-lg bg-slate-50 border border-slate-200 p-4">
                        <div class="grid grid-cols-2 gap-2">
                            <code
                                v-for="code in recovery_codes"
                                :key="code"
                                class="rounded-md bg-white border border-slate-200 px-3 py-1.5 text-center font-mono text-sm text-slate-800 tracking-widest"
                            >{{ code }}</code>
                        </div>
                    </div>
                    <p class="mt-2 text-xs text-slate-500">
                        Her kod yalnızca bir kez kullanılabilir. Bunları güvenli bir yerde saklayın.
                    </p>
                </div>
                <div v-else-if="showCodes && !recovery_codes.length" class="text-sm text-slate-500 italic">
                    Kurtarma kodu bulunamadı. Yenile butonunu kullanın.
                </div>
                <div v-else class="text-sm text-slate-500">
                    Kurtarma kodlarınız gizli. Görmek için "Göster" butonuna basın.
                </div>

                <div class="mt-4 border-t border-slate-100 pt-4">
                    <button
                        type="button"
                        :disabled="regenForm.processing"
                        @click="regenerate"
                        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 disabled:opacity-50"
                    >
                        <ArrowPathIcon class="h-4 w-4" />
                        Recovery Codes Yenile
                    </button>
                    <p class="mt-1 text-xs text-slate-400">Eski kodlar anında geçersiz olur.</p>
                </div>
            </div>

            <!-- Disable 2FA -->
            <div class="rounded-xl border border-red-100 bg-white p-5 shadow-sm">
                <h3 class="mb-2 text-sm font-semibold text-slate-800">Tehlike Bölgesi</h3>
                <p class="mb-3 text-sm text-slate-500">
                    2FA devre dışı bırakılırsa hesabınız yalnızca parola korumasına döner.
                </p>
                <button
                    type="button"
                    :disabled="disableForm.processing"
                    @click="disable"
                    class="inline-flex items-center gap-2 rounded-lg border border-red-300 bg-white px-4 py-2 text-sm font-medium text-red-600 hover:bg-red-50 disabled:opacity-50"
                >
                    <ExclamationTriangleIcon class="h-4 w-4" />
                    2FA'yı Devre Dışı Bırak
                </button>
            </div>
        </div>
    </CustomerLayout>
</template>
