<script setup>
import { ref, reactive } from 'vue'
import { router, useForm } from '@inertiajs/vue3'
import {
    ShieldCheckIcon,
    WrenchScrewdriverIcon,
    BugAntIcon,
    WrenchIcon,
    MagnifyingGlassIcon,
    CircleStackIcon,
    ClockIcon,
    CommandLineIcon,
} from '@heroicons/vue/24/outline'
import { useConfirm } from '@/composables/useConfirm'

const { ask } = useConfirm()

const props = defineProps({
    site: Object,
    cron: { type: Array, default: () => [] },
})

// Debug toggle
const toggleDebug = () => router.post(route('customer.wp.debug', props.site.id), {
    enabled: !props.site.wp_debug_enabled,
    debug_log: true,
    debug_display: false,
}, { preserveScroll: true })

// Maintenance toggle
const toggleMaintenance = () => router.post(route('customer.wp.maintenance', props.site.id), {
    enabled: !props.site.wp_maintenance_mode,
}, { preserveScroll: true })

// Harden
const hardenLoading = ref(false)
const harden = async () => {
    const ok = await ask({
        title: 'Onaylayın',
        message: 'Güvenlik sertleştirmesi uygulanacak (DISALLOW_FILE_EDIT, FORCE_SSL_ADMIN, vb.). Devam?',
        variant: 'warning',
        confirmText: 'Onayla',
        cancelText: 'İptal',
    })
    if (!ok) return
    hardenLoading.value = true
    router.post(route('customer.wp.harden', props.site.id), {}, {
        preserveScroll: true,
        onFinish: () => { hardenLoading.value = false },
    })
}

// Search & Replace
const srForm = useForm({ search: '', replace: '', dry_run: true })
const submitSr = () => srForm.post(route('customer.wp.search-replace', props.site.id), { preserveScroll: true })

// DB Export
const dbExport = () => {
    window.location.href = route('customer.wp.db-export', props.site.id)
}

// Cron
const runCron = async (hook = '') => {
    const ok = await ask({
        title: 'Onaylayın',
        message: hook ? `"${hook}" cron çalıştırılacak. Devam?` : 'Tüm bekleyen cron\'lar çalıştırılacak. Devam?',
        variant: 'warning',
        confirmText: 'Onayla',
        cancelText: 'İptal',
    })
    if (!ok) return
    router.post(route('customer.wp.cron.run', props.site.id), { hook }, { preserveScroll: true })
}

const formatCronDate = (isoDate) => {
    if (!isoDate) return '—'
    return new Date(isoDate).toLocaleString('tr-TR')
}
</script>

<template>
    <div class="space-y-6">

        <!-- Toggles row -->
        <div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
            <!-- Debug mode -->
            <div class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                <div class="flex items-center justify-between">
                    <div class="flex items-center gap-3">
                        <div class="flex h-9 w-9 items-center justify-center rounded-lg bg-amber-100">
                            <BugAntIcon class="h-5 w-5 text-amber-600" />
                        </div>
                        <div>
                            <p class="text-sm font-semibold">Debug Modu</p>
                            <p class="text-xs text-slate-500">WP_DEBUG sabitini kontrol eder</p>
                        </div>
                    </div>
                    <button @click="toggleDebug"
                            :class="['relative inline-flex h-6 w-11 items-center rounded-full transition',
                                     site.wp_debug_enabled ? 'bg-amber-500' : 'bg-slate-300']">
                        <span :class="['inline-block h-4 w-4 transform rounded-full bg-white transition',
                                       site.wp_debug_enabled ? 'translate-x-6' : 'translate-x-1']"></span>
                    </button>
                </div>
                <p v-if="site.wp_debug_enabled" class="mt-3 rounded bg-amber-50 px-3 py-1.5 text-xs text-amber-800">
                    Debug açık. WP_DEBUG_LOG=true, WP_DEBUG_DISPLAY=false
                </p>
            </div>

            <!-- Maintenance mode -->
            <div class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                <div class="flex items-center justify-between">
                    <div class="flex items-center gap-3">
                        <div class="flex h-9 w-9 items-center justify-center rounded-lg bg-orange-100">
                            <WrenchIcon class="h-5 w-5 text-orange-600" />
                        </div>
                        <div>
                            <p class="text-sm font-semibold">Bakım Modu</p>
                            <p class="text-xs text-slate-500">Ziyaretçilere bakım sayfası gösterir</p>
                        </div>
                    </div>
                    <button @click="toggleMaintenance"
                            :class="['relative inline-flex h-6 w-11 items-center rounded-full transition',
                                     site.wp_maintenance_mode ? 'bg-orange-500' : 'bg-slate-300']">
                        <span :class="['inline-block h-4 w-4 transform rounded-full bg-white transition',
                                       site.wp_maintenance_mode ? 'translate-x-6' : 'translate-x-1']"></span>
                    </button>
                </div>
                <p v-if="site.wp_maintenance_mode" class="mt-3 rounded bg-orange-50 px-3 py-1.5 text-xs text-orange-800">
                    Site şu an bakım modunda.
                </p>
            </div>
        </div>

        <!-- Security hardening -->
        <div class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
            <div class="flex items-start justify-between gap-4">
                <div class="flex items-center gap-3">
                    <div class="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-emerald-100">
                        <ShieldCheckIcon class="h-5 w-5 text-emerald-600" />
                    </div>
                    <div>
                        <p class="text-sm font-semibold">Güvenlik Sertleştirme</p>
                        <p class="text-xs text-slate-500">DISALLOW_FILE_EDIT, FORCE_SSL_ADMIN, WP_AUTO_UPDATE_CORE=minor</p>
                    </div>
                </div>
                <div class="flex items-center gap-3 shrink-0">
                    <span v-if="site.security_hardened" class="rounded-full bg-emerald-100 px-2.5 py-0.5 text-xs font-semibold text-emerald-700">
                        Uygulandı
                    </span>
                    <button @click="harden" :disabled="hardenLoading"
                            class="inline-flex items-center gap-1 rounded-lg border border-emerald-300 bg-emerald-50 px-3 py-1.5 text-xs font-medium text-emerald-700 hover:bg-emerald-100 disabled:opacity-60">
                        <WrenchScrewdriverIcon class="h-3.5 w-3.5" />
                        {{ site.security_hardened ? 'Yeniden Uygula' : 'Uygula' }}
                    </button>
                </div>
            </div>
        </div>

        <!-- Search & Replace -->
        <div class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
            <div class="mb-4 flex items-center gap-3">
                <div class="flex h-9 w-9 items-center justify-center rounded-lg bg-blue-100">
                    <MagnifyingGlassIcon class="h-5 w-5 text-blue-600" />
                </div>
                <h3 class="text-sm font-semibold">Ara & Değiştir (DB)</h3>
            </div>
            <form @submit.prevent="submitSr" class="space-y-3">
                <div class="grid grid-cols-2 gap-3">
                    <div>
                        <label class="block text-xs font-medium mb-1">Aranan</label>
                        <input v-model="srForm.search" type="text" placeholder="https://eski-site.com"
                               class="w-full rounded border border-slate-300 px-3 py-2 text-sm font-mono" />
                    </div>
                    <div>
                        <label class="block text-xs font-medium mb-1">Yeni Değer</label>
                        <input v-model="srForm.replace" type="text" placeholder="https://yeni-site.com"
                               class="w-full rounded border border-slate-300 px-3 py-2 text-sm font-mono" />
                    </div>
                </div>
                <label class="flex items-center gap-2 text-xs">
                    <input v-model="srForm.dry_run" type="checkbox" class="rounded" />
                    Kuru çalıştırma (değiştirmeden önce say)
                </label>
                <button type="submit" :disabled="srForm.processing"
                        class="inline-flex items-center gap-1 rounded-lg bg-blue-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-blue-700 disabled:opacity-60">
                    <MagnifyingGlassIcon class="h-3.5 w-3.5" />
                    {{ srForm.dry_run ? 'Kuru Çalıştır' : 'Değiştir' }}
                </button>
            </form>
        </div>

        <!-- DB Export + Cron row -->
        <div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
            <!-- DB Export -->
            <div class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                <div class="flex items-center gap-3 mb-3">
                    <div class="flex h-9 w-9 items-center justify-center rounded-lg bg-violet-100">
                        <CircleStackIcon class="h-5 w-5 text-violet-600" />
                    </div>
                    <h3 class="text-sm font-semibold">DB Export</h3>
                </div>
                <p class="mb-3 text-xs text-slate-500">wp db export — tam veritabanı yedeği indir.</p>
                <button @click="dbExport"
                        class="inline-flex items-center gap-1 rounded-lg border border-violet-300 bg-violet-50 px-3 py-1.5 text-xs font-medium text-violet-700 hover:bg-violet-100">
                    <CircleStackIcon class="h-3.5 w-3.5" /> SQL İndir
                </button>
            </div>

            <!-- Cron -->
            <div class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                <div class="flex items-center justify-between mb-3">
                    <div class="flex items-center gap-3">
                        <div class="flex h-9 w-9 items-center justify-center rounded-lg bg-teal-100">
                            <ClockIcon class="h-5 w-5 text-teal-600" />
                        </div>
                        <h3 class="text-sm font-semibold">WP-Cron</h3>
                    </div>
                    <button @click="runCron()"
                            class="text-xs text-teal-600 hover:underline font-medium">Tümünü Çalıştır</button>
                </div>
                <div v-if="cron.length" class="space-y-1.5 max-h-36 overflow-y-auto">
                    <div v-for="job in cron" :key="job.hook"
                         class="flex items-center justify-between text-xs rounded bg-slate-50 px-2 py-1.5">
                        <span class="font-mono text-slate-700 truncate max-w-[140px]">{{ job.hook }}</span>
                        <div class="flex items-center gap-2 shrink-0">
                            <span class="text-slate-400">{{ formatCronDate(job.next_run_gmt) }}</span>
                            <button @click="runCron(job.hook)" class="text-teal-600 hover:text-teal-800">
                                <CommandLineIcon class="h-3.5 w-3.5" />
                            </button>
                        </div>
                    </div>
                </div>
                <p v-else class="text-xs text-slate-400">Bekleyen cron job'u yok.</p>
            </div>
        </div>

    </div>
</template>
