<script setup>
import { ref, computed } from 'vue'
import { Head, router, useForm } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import {
    CheckCircleIcon,
    ArrowRightIcon,
    ArrowLeftIcon,
    ServerStackIcon,
    GlobeAltIcon,
    LockClosedIcon,
    EnvelopeIcon,
    SwatchIcon,
    ServerIcon,
    CloudIcon,
    SparklesIcon,
    InformationCircleIcon,
    CheckIcon,
} from '@heroicons/vue/24/outline'
import { useConfirm } from '@/composables/useConfirm'

const { ask } = useConfirm()

const props = defineProps({
    completed: Boolean,
    current_settings: Object,
    system_info: Object,
    recommendations: Object,
})

const step = ref(1)
const totalSteps = 6

// Mail mode: 'local' (varsayılan — sunucu Postfix'i) | 'relay' (harici SMTP)
const form = useForm({
    license_accepted:     false,
    hostname:             props.current_settings.hostname || props.recommendations.hostname,
    primary_ip:          props.current_settings.primary_ip || props.recommendations.primary_ip,
    support_email:       props.current_settings.support_email || 'destek@example.com',
    mail_from_address:   props.current_settings.mail_from_address || 'noreply@example.com',
    mail_mode:           props.current_settings.mail_mode || 'local',
    smtp_host:           props.current_settings.smtp_host || '127.0.0.1',
    smtp_port:           parseInt(props.current_settings.smtp_port || 25),
    smtp_username:       props.current_settings.smtp_username || '',
    smtp_password:       '',
    panel_brand_name:    props.current_settings.panel_brand_name || 'Onoxsoft Panel',
    cluster_mode:        props.current_settings.cluster_mode || 'single',
    kvkk_data_controller: props.current_settings.kvkk_data_controller || '',
    enable_panel_ssl:    true,
    enable_fail2ban:     true,
    require_2fa_admin:   false,
})

function switchMailMode(mode) {
    form.mail_mode = mode
    if (mode === 'local') {
        form.smtp_host = '127.0.0.1'
        form.smtp_port = 25
        form.smtp_username = ''
        form.smtp_password = ''
    } else {
        form.smtp_host = ''
        form.smtp_port = 587
    }
    smtpTestStatus.value = null
}

const smtpTestStatus = ref(null) // null | 'testing' | 'ok' | 'fail'

async function testSmtp() {
    smtpTestStatus.value = 'testing'
    try {
        const res = await fetch('/api/admin/test-smtp', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') ?? '',
            },
            body: JSON.stringify({
                host: form.smtp_host,
                port: form.smtp_port,
                username: form.smtp_username,
                password: form.smtp_password,
                from: form.mail_from_address,
                to: form.support_email,
            }),
        })
        smtpTestStatus.value = res.ok ? 'ok' : 'fail'
    } catch {
        smtpTestStatus.value = 'fail'
    }
}

const next = () => { if (step.value < totalSteps) step.value++ }
const prev = () => { if (step.value > 1) step.value-- }

const canNext = computed(() => {
    if (step.value === 1) return form.license_accepted
    return true
})

const submit = () => form.post(route('admin.setup.save'))

const skip = async () => {
    const ok = await ask({
        title: 'Onaylayın',
        message: 'Kurulum atlanacak. Daha sonra Sistem Ayarlarından düzenleyebilirsin. Devam?',
        variant: 'warning',
        confirmText: 'Onayla',
        cancelText: 'İptal',
    })
    if (ok) {
        router.post(route('admin.setup.skip'))
    }
}

const steps = [
    { num: 1, label: 'Hoş Geldiniz',    icon: SparklesIcon },
    { num: 2, label: 'Admin Hesabı',    icon: LockClosedIcon },
    { num: 3, label: 'E-posta (SMTP)',  icon: EnvelopeIcon },
    { num: 4, label: 'Markalama',       icon: SwatchIcon },
    { num: 5, label: 'Sunucu Modu',     icon: ServerIcon },
    { num: 6, label: 'Tamamla',         icon: CheckCircleIcon },
]
</script>

<template>
    <Head title="Kurulum Sihirbazı" />
    <AdminLayout>
        <template #header>Kurulum Sihirbazı</template>

        <div v-if="completed" class="rounded-xl border border-emerald-200 bg-emerald-50 p-6 text-center">
            <CheckCircleIcon class="mx-auto h-14 w-14 text-emerald-500" />
            <h3 class="mt-3 text-xl font-bold text-emerald-900">Kurulum Daha Önce Tamamlandı</h3>
            <p class="mt-2 text-sm text-emerald-700">
                Ayarları değiştirmek için <a href="/admin/settings" class="font-semibold underline">Sistem Ayarları</a>'na git.
            </p>
        </div>

        <div v-else>
            <!-- Step indicator -->
            <div class="mb-6 flex items-center justify-between overflow-x-auto pb-1">
                <div v-for="s in steps" :key="s.num" class="flex items-center flex-1 last:flex-none min-w-0">
                    <div
                        :class="[
                            'flex h-10 w-10 shrink-0 items-center justify-center rounded-full text-sm font-bold transition',
                            step > s.num ? 'bg-emerald-500 text-white' : step === s.num ? 'bg-indigo-600 text-white' : 'bg-slate-200 text-slate-500',
                        ]"
                    >
                        <CheckIcon v-if="step > s.num" class="h-5 w-5" />
                        <component v-else :is="s.icon" class="h-5 w-5" />
                    </div>
                    <div v-if="s.num < totalSteps" :class="['flex-1 h-0.5 mx-2 transition min-w-4', step > s.num ? 'bg-emerald-500' : 'bg-slate-200']"></div>
                </div>
            </div>
            <div class="mb-6 text-center">
                <h2 class="text-2xl font-bold text-slate-900">{{ steps[step-1].label }}</h2>
                <p class="text-sm text-slate-500">Adım {{ step }} / {{ totalSteps }}</p>
            </div>

            <div class="mx-auto max-w-2xl rounded-xl border border-slate-200 bg-white p-6 shadow-sm">

                <!-- STEP 1: Welcome + License Accept -->
                <div v-if="step === 1" class="space-y-5">
                    <div class="text-center">
                        <SparklesIcon class="mx-auto h-14 w-14 text-indigo-500" />
                        <h3 class="mt-3 text-xl font-bold text-slate-900">Onoxsoft Panel'e Hoş Geldiniz!</h3>
                        <p class="mt-2 text-sm text-slate-600">
                            Bu sihirbaz sunucunuzu yapılandırmanıza yardımcı olacak. Tüm adımlar yaklaşık 5 dakika sürer.
                        </p>
                    </div>

                    <div class="rounded-lg bg-slate-50 p-3 text-xs">
                        <strong>Algılanan sistem:</strong>
                        <ul class="mt-1 space-y-0.5 text-slate-600">
                            <li>OS: <code>{{ system_info.os }}</code></li>
                            <li>PHP: <code>{{ system_info.php_version }}</code></li>
                            <li>Panel URL: <code>{{ system_info.panel_url }}</code></li>
                            <li>DB: <code>{{ system_info.database_connection }}</code></li>
                        </ul>
                    </div>

                    <label
                        class="flex items-start gap-3 rounded-lg border p-4 cursor-pointer hover:bg-indigo-50 transition"
                        :class="form.license_accepted ? 'border-indigo-400 bg-indigo-50/50' : 'border-slate-300'"
                    >
                        <input v-model="form.license_accepted" type="checkbox" class="mt-0.5" />
                        <div class="text-sm">
                            <p class="font-medium text-slate-900">Lisans Sözleşmesini Kabul Ediyorum</p>
                            <p class="text-slate-500 mt-0.5">
                                Onoxsoft Panel kullanım koşullarını ve KVKK aydınlatma metnini okudum, kabul ediyorum.
                            </p>
                        </div>
                    </label>
                    <p v-if="!form.license_accepted" class="text-xs text-amber-600">
                        Devam etmek için lisansı kabul etmeniz gerekiyor.
                    </p>
                </div>

                <!-- STEP 2: Admin User Setup (hostname + IP + 2FA + fail2ban) -->
                <div v-if="step === 2" class="space-y-4">
                    <div class="rounded-lg bg-indigo-50 p-3 text-sm text-indigo-900">
                        <InformationCircleIcon class="inline h-4 w-4 mr-1" />
                        Sunucunun FQDN ve IP'si — SSL + Apache + DNS zone'ları için kritik.
                    </div>
                    <div>
                        <label class="block text-sm font-medium">Sunucu Hostname (FQDN)</label>
                        <input v-model="form.hostname" type="text" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 font-mono text-sm" />
                        <p class="mt-1 text-xs text-slate-500">Örnek: <code>panel.example.com</code> · Önerilen: <code>{{ recommendations.hostname }}</code></p>
                        <p v-if="form.errors.hostname" class="text-xs text-red-600">{{ form.errors.hostname }}</p>
                    </div>
                    <div>
                        <label class="block text-sm font-medium">Birincil IP</label>
                        <input v-model="form.primary_ip" type="text" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 font-mono text-sm" />
                        <p class="mt-1 text-xs text-slate-500">Algılanan: <code>{{ system_info.detected_ip }}</code></p>
                        <p v-if="form.errors.primary_ip" class="text-xs text-red-600">{{ form.errors.primary_ip }}</p>
                    </div>
                    <div>
                        <label class="block text-sm font-medium">KVKK Veri Sorumlusu (opsiyonel)</label>
                        <input v-model="form.kvkk_data_controller" type="text" placeholder="ÖRNEK BİLİŞİM LTD. ŞTİ." class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm" />
                    </div>
                    <label class="flex items-start gap-3 rounded-lg border p-3 cursor-pointer hover:bg-slate-50"
                           :class="form.enable_panel_ssl ? 'border-emerald-300 bg-emerald-50/30' : 'border-slate-200'">
                        <input v-model="form.enable_panel_ssl" type="checkbox" class="mt-1" />
                        <div>
                            <div class="font-medium text-sm">Panel SSL (Let's Encrypt)</div>
                            <p class="text-xs text-slate-500">Panel HTTPS üzerinden çalışır.</p>
                        </div>
                    </label>
                    <label class="flex items-start gap-3 rounded-lg border p-3 cursor-pointer hover:bg-slate-50"
                           :class="form.enable_fail2ban ? 'border-emerald-300 bg-emerald-50/30' : 'border-slate-200'">
                        <input v-model="form.enable_fail2ban" type="checkbox" class="mt-1" />
                        <div>
                            <div class="font-medium text-sm">fail2ban Aktif</div>
                            <p class="text-xs text-slate-500">SSH + panel login + FTP brute force koruması.</p>
                        </div>
                    </label>
                    <label class="flex items-start gap-3 rounded-lg border p-3 cursor-pointer hover:bg-slate-50"
                           :class="form.require_2fa_admin ? 'border-emerald-300 bg-emerald-50/30' : 'border-slate-200'">
                        <input v-model="form.require_2fa_admin" type="checkbox" class="mt-1" />
                        <div>
                            <div class="font-medium text-sm">Admin için 2FA Zorunlu</div>
                            <p class="text-xs text-slate-500">Tüm adminler TOTP kurmadan giriş yapamaz.</p>
                        </div>
                    </label>
                </div>

                <!-- STEP 3: Mail Server Config — local Postfix (default) vs external relay -->
                <div v-if="step === 3" class="space-y-4">
                    <!-- Mode toggle -->
                    <div class="grid grid-cols-2 gap-3">
                        <button type="button" @click="switchMailMode('local')"
                                :class="['rounded-lg border-2 p-4 text-left transition', form.mail_mode === 'local' ? 'border-emerald-500 bg-emerald-50' : 'border-slate-200 bg-white hover:border-slate-300']">
                            <div class="flex items-center gap-2">
                                <ServerIcon class="h-5 w-5 text-emerald-600" />
                                <span class="font-semibold">Yerel Postfix</span>
                                <span class="ml-auto rounded-full bg-emerald-100 px-2 py-0.5 text-[10px] font-semibold text-emerald-800">Önerilen</span>
                            </div>
                            <p class="mt-2 text-xs text-slate-600">
                                Sunucunun kendi Postfix'i kullanılır. install.sh tarafından otomatik kurulur.
                                Ek yapılandırma gerektirmez.
                            </p>
                        </button>
                        <button type="button" @click="switchMailMode('relay')"
                                :class="['rounded-lg border-2 p-4 text-left transition', form.mail_mode === 'relay' ? 'border-indigo-500 bg-indigo-50' : 'border-slate-200 bg-white hover:border-slate-300']">
                            <div class="flex items-center gap-2">
                                <CloudIcon class="h-5 w-5 text-indigo-600" />
                                <span class="font-semibold">Harici Relay</span>
                            </div>
                            <p class="mt-2 text-xs text-slate-600">
                                Mailgun, AWS SES, SendGrid, Postmark. Yüksek teslim oranı (deliverability),
                                IP reputasyonu yönetimi.
                            </p>
                        </button>
                    </div>

                    <div>
                        <label class="block text-sm font-medium">Destek E-postası</label>
                        <input v-model="form.support_email" type="email" 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">Sistem E-posta Adresi (From)</label>
                        <input v-model="form.mail_from_address" type="email" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm" />
                        <p v-if="form.mail_mode === 'local'" class="mt-1 text-xs text-slate-500">
                            Yerel modda: bu adresi <code class="font-mono">noreply@{{ form.hostname || 'sunucu' }}</code> olarak ayarlamak SPF/DKIM için ideal.
                        </p>
                    </div>

                    <!-- Sadece harici relay seçildiyse SMTP ayarları görünür -->
                    <div v-if="form.mail_mode === 'relay'" class="space-y-3 rounded-lg bg-indigo-50 p-4">
                        <div class="grid grid-cols-2 gap-3">
                            <div>
                                <label class="block text-sm font-medium">SMTP Host</label>
                                <input v-model="form.smtp_host" type="text" placeholder="smtp.mailgun.org" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 font-mono text-sm" />
                            </div>
                            <div>
                                <label class="block text-sm font-medium">SMTP Port</label>
                                <input v-model.number="form.smtp_port" type="number" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 font-mono text-sm" />
                            </div>
                        </div>
                        <div class="grid grid-cols-2 gap-3">
                            <div>
                                <label class="block text-sm font-medium">SMTP Kullanıcı Adı</label>
                                <input v-model="form.smtp_username" type="text" 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">SMTP Şifre</label>
                                <input v-model="form.smtp_password" type="password" autocomplete="new-password" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm" />
                            </div>
                        </div>
                    </div>

                    <div v-if="form.mail_mode === 'local'" class="rounded-lg border border-emerald-200 bg-emerald-50 p-3 text-xs text-emerald-900">
                        <strong>✓ Yerel Postfix:</strong> Host=<code>127.0.0.1</code>, Port=<code>25</code>, auth yok. Sistem servisi otomatik başlatılır.
                        Üretim öncesi <em>reverse DNS (PTR)</em> kaydının sunucu hostname'ine işaret ettiğinden emin ol.
                    </div>

                    <button
                        type="button"
                        :disabled="smtpTestStatus === 'testing'"
                        @click="testSmtp"
                        :class="[
                            'inline-flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-medium',
                            smtpTestStatus === 'ok' ? 'bg-emerald-100 text-emerald-800' :
                            smtpTestStatus === 'fail' ? 'bg-red-100 text-red-800' :
                            'bg-slate-100 text-slate-700 hover:bg-slate-200',
                        ]"
                    >
                        <span v-if="smtpTestStatus === 'testing'">Test ediliyor…</span>
                        <span v-else-if="smtpTestStatus === 'ok'">✓ Test başarılı</span>
                        <span v-else-if="smtpTestStatus === 'fail'">✗ Test başarısız</span>
                        <span v-else>Test Mail Gönder</span>
                    </button>
                    <p class="text-xs text-slate-500">Test e-postası destek adresine ({{ form.support_email }}) gönderilecek.</p>
                </div>

                <!-- STEP 4: Default Branding -->
                <div v-if="step === 4" class="space-y-4">
                    <div class="rounded-lg bg-indigo-50 p-3 text-sm text-indigo-900">
                        Panel marka adı e-posta şablonları ve giriş ekranında gösterilir.
                    </div>
                    <div>
                        <label class="block text-sm font-medium">Panel Marka Adı</label>
                        <input v-model="form.panel_brand_name" type="text" placeholder="Onoxsoft Panel" 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">Daha sonra Markalama sayfasından logo yükleyebilirsiniz.</p>
                    </div>
                    <div class="rounded-lg border border-dashed border-slate-300 bg-slate-50 p-6 text-center text-sm text-slate-500">
                        Logo yükleme <span class="font-medium">Markalama → Logo Yükle</span> sayfasından kurulum sonrası yapılabilir.
                    </div>
                </div>

                <!-- STEP 5: Cluster Setup -->
                <div v-if="step === 5" class="space-y-4">
                    <div class="rounded-lg bg-indigo-50 p-3 text-sm text-indigo-900">
                        Sunucu topolojinizi seçin. Çoğu kurulum için tek sunucu yeterlidir. Çoklu sunucu (Multi-server+) sonradan Cluster menüsünden yapılandırılabilir.
                    </div>
                    <label
                        class="flex items-start gap-3 rounded-lg border p-4 cursor-pointer transition"
                        :class="form.cluster_mode === 'single' ? 'border-indigo-400 bg-indigo-50/40' : 'border-slate-200 hover:bg-slate-50'"
                    >
                        <input v-model="form.cluster_mode" type="radio" value="single" class="mt-0.5" />
                        <div>
                            <p class="font-medium text-sm">Tek Sunucu (Önerilen)</p>
                            <p class="text-xs text-slate-500 mt-0.5">Tüm servisler bu sunucuda çalışır. Yeni kurulumlar için en kolay seçenek.</p>
                        </div>
                    </label>
                    <label
                        class="flex items-start gap-3 rounded-lg border p-4 cursor-pointer transition"
                        :class="form.cluster_mode === 'multi' ? 'border-indigo-400 bg-indigo-50/40' : 'border-slate-200 hover:bg-slate-50'"
                    >
                        <input v-model="form.cluster_mode" type="radio" value="multi" class="mt-0.5" />
                        <div>
                            <p class="font-medium text-sm">Çoklu Sunucu (Cluster)</p>
                            <p class="text-xs text-slate-500 mt-0.5">Yük dengeleme ve yüksek erişilebilirlik için. Kurulum sonrası Cluster menüsünden node ekleyebilirsiniz. </p>
                        </div>
                    </label>
                </div>

                <!-- STEP 6: Recap + Finalize -->
                <div v-if="step === 6" class="space-y-4">
                    <div class="text-center">
                        <SparklesIcon class="mx-auto h-16 w-16 text-amber-500" />
                        <h3 class="mt-3 text-xl font-bold">Kuruluma Hazırsın!</h3>
                        <p class="mt-2 text-sm text-slate-600">Aşağıdaki ayarlar uygulanacak. Sonra her sayfadan değiştirebilirsin.</p>
                    </div>
                    <div class="rounded-lg border border-slate-200 p-4 text-sm">
                        <dl class="space-y-2">
                            <div class="flex justify-between"><dt class="text-slate-500">Hostname</dt><dd class="font-mono">{{ form.hostname }}</dd></div>
                            <div class="flex justify-between"><dt class="text-slate-500">IP</dt><dd class="font-mono">{{ form.primary_ip }}</dd></div>
                            <div class="flex justify-between"><dt class="text-slate-500">Marka Adı</dt><dd>{{ form.panel_brand_name }}</dd></div>
                            <div class="flex justify-between"><dt class="text-slate-500">Destek E-postası</dt><dd>{{ form.support_email }}</dd></div>
                            <div class="flex justify-between"><dt class="text-slate-500">SMTP</dt><dd class="font-mono text-xs">{{ form.smtp_host || '—' }}:{{ form.smtp_port }}</dd></div>
                            <div class="flex justify-between"><dt class="text-slate-500">SSL</dt><dd>{{ form.enable_panel_ssl ? '✓ Aktif' : '✗ Kapalı' }}</dd></div>
                            <div class="flex justify-between"><dt class="text-slate-500">fail2ban</dt><dd>{{ form.enable_fail2ban ? '✓ Aktif' : '✗ Kapalı' }}</dd></div>
                            <div class="flex justify-between"><dt class="text-slate-500">Admin 2FA Zorunlu</dt><dd>{{ form.require_2fa_admin ? '✓ Açık' : '✗ Kapalı' }}</dd></div>
                            <div class="flex justify-between"><dt class="text-slate-500">Sunucu Modu</dt><dd class="capitalize">{{ form.cluster_mode === 'single' ? 'Tek Sunucu' : 'Çoklu Sunucu (Cluster)' }}</dd></div>
                        </dl>
                    </div>
                </div>

                <!-- Navigation -->
                <div class="mt-6 flex justify-between items-center border-t pt-4">
                    <button v-if="step > 1" @click="prev" class="inline-flex items-center gap-1 rounded-lg border border-slate-300 px-4 py-2 text-sm">
                        <ArrowLeftIcon class="h-4 w-4" /> Geri
                    </button>
                    <button v-else @click="skip" class="text-xs text-slate-500 hover:underline">Bu sihirbazı atla</button>

                    <button
                        v-if="step < totalSteps"
                        @click="next"
                        :disabled="!canNext"
                        :class="[
                            'inline-flex items-center gap-1 rounded-lg px-6 py-2 text-sm font-semibold',
                            canNext ? 'bg-indigo-600 text-white hover:bg-indigo-700' : 'bg-slate-300 text-slate-500 cursor-not-allowed',
                        ]"
                    >
                        Sonraki <ArrowRightIcon class="h-4 w-4" />
                    </button>
                    <button
                        v-else
                        @click="submit"
                        :disabled="form.processing"
                        class="inline-flex items-center gap-2 rounded-lg bg-gradient-to-r from-rose-500 to-rose-600 px-6 py-2 text-sm font-semibold text-white hover:from-rose-600 hover:to-rose-700 disabled:opacity-60"
                    >
                        <SparklesIcon class="h-5 w-5" />
                        {{ form.processing ? 'Kaydediliyor...' : 'Kurulumu Tamamla' }}
                    </button>
                </div>
            </div>
        </div>
    </AdminLayout>
</template>
