<script setup>
import { ref, computed } from 'vue'
import { Head, Link, router, useForm } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import {
    ClockIcon,
    PlusIcon,
    TrashIcon,
    XMarkIcon,
    PlayIcon,
    PowerIcon,
    InformationCircleIcon,
} from '@heroicons/vue/24/outline'
import { useConfirm } from '@/composables/useConfirm'

const { ask } = useConfirm()

const props = defineProps({
    schedules: Array,
    destinations: Array,
})

const showForm = ref(false)
const cronMode = ref('preset') // preset | custom

const cronPresets = [
    { label: 'Her gün 02:00', value: '0 2 * * *' },
    { label: 'Her gün 04:00 (önerilen)', value: '0 4 * * *' },
    { label: 'Her Pazar 03:00', value: '0 3 * * 0' },
    { label: 'Her ay 1\'i 03:00', value: '0 3 1 * *' },
    { label: 'Her 6 saatte bir', value: '0 */6 * * *' },
]

const form = useForm({
    name: 'Günlük Tam Yedek',
    cron: '0 4 * * *',
    scope: 'full',
    destination_id: props.destinations[0]?.id || null,
    compression: 'gzip',
    encrypt: false,
    keep_daily: 7,
    keep_weekly: 4,
    keep_monthly: 6,
    keep_yearly: 2,
    is_active: true,
    exclude_paths: ['node_modules', 'tmp', 'cache', '.git'],
})

const newExclude = ref('')

const addExclude = () => {
    if (newExclude.value.trim() && !form.exclude_paths.includes(newExclude.value.trim())) {
        form.exclude_paths.push(newExclude.value.trim())
    }
    newExclude.value = ''
}

const removeExclude = (path) => {
    form.exclude_paths = form.exclude_paths.filter((p) => p !== path)
}

const submit = () => form.post(route('admin.backups.schedules.store'), {
    preserveScroll: true,
    onSuccess: () => { showForm.value = false; form.reset() },
})

const remove = async (s) => {
    const ok = await ask({
        title: 'Onaylayın',
        message: `'${s.name}' profili silinecek?`,
        variant: 'danger',
        confirmText: 'Sil',
        cancelText: 'İptal',
    })
    if (!ok) return
    router.delete(route('admin.backups.schedules.destroy', s.id), { preserveScroll: true })
}

const runNow = async (s) => {
    const ok = await ask({
        title: 'Onaylayın',
        message: `'${s.name}' şimdi çalıştırılsın mı?`,
        variant: 'warning',
        confirmText: 'Onayla',
        cancelText: 'İptal',
    })
    if (!ok) return
    router.post(route('admin.backups.schedules.run', s.id), {}, { preserveScroll: true })
}

const toggleActive = (s) => {
    router.patch(route('admin.backups.schedules.update', s.id), {
        is_active: !s.is_active,
    }, { preserveScroll: true })
}

const statusBadge = (s) => ({
    success: 'bg-emerald-100 text-emerald-700',
    partial: 'bg-amber-100 text-amber-700',
    failed: 'bg-red-100 text-red-700',
}[s] || 'bg-slate-100 text-slate-700')

const scopeLabel = (s) => ({
    full: 'Tam Yedek',
    home_only: 'Sadece /home',
    db_only: 'Sadece DB',
    config_only: 'Sadece Config',
}[s] || s)
</script>

<template>
    <Head title="Yedek Profilleri" />
    <AdminLayout>
        <template #header>Yedek Profilleri</template>

        <!-- Sub nav -->
        <div class="mb-4 flex flex-wrap gap-1 border-b border-slate-200">
            <Link :href="route('admin.backups.dashboard')" class="px-4 py-2 text-sm font-medium text-slate-600 hover:text-slate-900">Dashboard</Link>
            <span class="px-4 py-2 text-sm font-medium border-b-2 border-indigo-600 text-indigo-700">Yedek Profilleri</span>
            <Link :href="route('admin.backups.destinations')" class="px-4 py-2 text-sm font-medium text-slate-600 hover:text-slate-900">Hedefler</Link>
            <Link :href="route('admin.backups.history')" class="px-4 py-2 text-sm font-medium text-slate-600 hover:text-slate-900">Tarihçe</Link>
        </div>

        <div 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>
                    <strong>Yedek Profili:</strong> Belirli bir kapsamı (tam/home/db) belirli bir hedefe (local/S3/restic) düzenli aralıklarla yedekleyen tanım.
                    Birden fazla profil oluşturup farklı ihtiyaçlar için kullanabilirsin (örn: "günlük tam local" + "haftalık DB S3").
                </div>
            </div>
        </div>

        <div class="mb-4 flex justify-end">
            <button @click="showForm = true" :disabled="destinations.length === 0"
                    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 disabled:opacity-50">
                <PlusIcon class="h-4 w-4" /> Yeni Profil
            </button>
        </div>

        <div v-if="destinations.length === 0" class="rounded-xl border border-amber-200 bg-amber-50 p-6 text-center text-sm text-amber-900">
            ⚠️ Önce en az bir yedek hedefi tanımlamalısın.
            <Link :href="route('admin.backups.destinations')" class="font-medium underline">Hedef ekle</Link>
        </div>

        <div v-else-if="schedules.length === 0" class="rounded-xl border border-dashed border-slate-300 bg-white p-12 text-center">
            <ClockIcon class="mx-auto h-14 w-14 text-slate-300" />
            <h3 class="mt-3 text-lg font-semibold">Henüz yedek profili yok</h3>
            <p class="mt-1 text-sm text-slate-500">İlk yedek profilini oluştur — günlük yedek = veri kaybına karşı sigorta.</p>
        </div>

        <div v-else class="space-y-3">
            <div v-for="s in schedules" :key="s.id" class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                <div class="flex items-start justify-between gap-3">
                    <div class="flex-1">
                        <div class="flex items-center gap-2 flex-wrap">
                            <span :class="['h-2 w-2 rounded-full', s.is_active ? 'bg-emerald-500 animate-pulse' : 'bg-slate-300']"></span>
                            <h3 class="font-semibold text-slate-900">{{ s.name }}</h3>
                            <span class="rounded bg-indigo-100 px-2 py-0.5 text-xs font-medium text-indigo-700">{{ scopeLabel(s.scope) }}</span>
                            <span v-if="s.encrypt" class="rounded bg-purple-100 px-2 py-0.5 text-xs font-medium text-purple-700">🔐 Şifreli</span>
                        </div>
                        <div class="mt-2 grid grid-cols-2 gap-3 text-xs md:grid-cols-4">
                            <div>
                                <div class="text-slate-500">Zamanlama</div>
                                <div class="font-medium">{{ s.human_cron }}</div>
                                <code class="font-mono text-[10px] text-slate-400">{{ s.cron }}</code>
                            </div>
                            <div>
                                <div class="text-slate-500">Hedef</div>
                                <div class="font-medium">{{ s.destination?.name }}</div>
                                <span class="font-mono text-[10px] text-slate-400">{{ s.destination?.driver }}</span>
                            </div>
                            <div>
                                <div class="text-slate-500">Retention</div>
                                <div class="font-mono text-xs">{{ s.keep_daily }}d / {{ s.keep_weekly }}w / {{ s.keep_monthly }}m / {{ s.keep_yearly }}y</div>
                            </div>
                            <div>
                                <div class="text-slate-500">Son Çalışma</div>
                                <div v-if="s.last_run_at">
                                    <span :class="['rounded px-1.5 py-0.5 text-[10px] font-semibold', statusBadge(s.last_run_status)]">{{ s.last_run_status }}</span>
                                    <div class="text-[10px] text-slate-400 mt-0.5">{{ s.last_run_at }}</div>
                                </div>
                                <span v-else class="text-slate-400">Hiç çalışmadı</span>
                            </div>
                        </div>
                    </div>
                    <div class="flex flex-col gap-1">
                        <button @click="runNow(s)" class="inline-flex items-center gap-1 rounded border border-indigo-300 bg-indigo-50 px-3 py-1.5 text-xs font-medium text-indigo-700 hover:bg-indigo-100">
                            <PlayIcon class="h-3 w-3" /> Şimdi
                        </button>
                        <button @click="toggleActive(s)" :class="['inline-flex items-center gap-1 rounded border px-3 py-1.5 text-xs font-medium', s.is_active ? 'border-amber-300 bg-white text-amber-700 hover:bg-amber-50' : 'border-emerald-300 bg-emerald-50 text-emerald-700 hover:bg-emerald-100']">
                            <PowerIcon class="h-3 w-3" /> {{ s.is_active ? 'Durdur' : 'Aç' }}
                        </button>
                        <button @click="remove(s)" class="inline-flex items-center gap-1 rounded border border-red-300 bg-white px-3 py-1.5 text-xs font-medium text-red-700 hover:bg-red-50">
                            <TrashIcon class="h-3 w-3" /> Sil
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Create 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 Yedek Profili</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 class="grid grid-cols-2 gap-3">
                        <div class="col-span-2">
                            <label class="block text-sm font-medium">Profil Adı</label>
                            <input v-model="form.name" 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">Kapsam</label>
                            <select v-model="form.scope" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm">
                                <option value="full">Tam Yedek (home + DB + config)</option>
                                <option value="home_only">Sadece /home dizinleri</option>
                                <option value="db_only">Sadece MySQL DB'ler</option>
                                <option value="config_only">Sadece config (Apache/FPM)</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm font-medium">Hedef</label>
                            <select v-model="form.destination_id" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm">
                                <option v-for="d in destinations" :key="d.id" :value="d.id">{{ d.name }} ({{ d.driver }})</option>
                            </select>
                        </div>
                    </div>

                    <div>
                        <label class="block text-sm font-medium">Zamanlama (cron)</label>
                        <div class="mt-1 flex gap-2 mb-2">
                            <button type="button" @click="cronMode = 'preset'" :class="['rounded px-3 py-1 text-xs', cronMode === 'preset' ? 'bg-indigo-600 text-white' : 'bg-slate-100']">Hazır Şablon</button>
                            <button type="button" @click="cronMode = 'custom'" :class="['rounded px-3 py-1 text-xs', cronMode === 'custom' ? 'bg-indigo-600 text-white' : 'bg-slate-100']">Custom Cron</button>
                        </div>
                        <select v-if="cronMode === 'preset'" v-model="form.cron" class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm">
                            <option v-for="p in cronPresets" :key="p.value" :value="p.value">{{ p.label }} — <code>{{ p.value }}</code></option>
                        </select>
                        <input v-else v-model="form.cron" type="text" placeholder="0 4 * * *" class="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">5-field cron: <code>dakika saat ay-günü ay hafta-günü</code></p>
                    </div>

                    <div class="grid grid-cols-2 gap-3">
                        <div>
                            <label class="block text-sm font-medium">Sıkıştırma</label>
                            <select v-model="form.compression" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm">
                                <option value="none">Yok (en hızlı)</option>
                                <option value="gzip">gzip (önerilen)</option>
                                <option value="zstd">zstd (modern)</option>
                                <option value="xz">xz (en küçük, en yavaş)</option>
                            </select>
                        </div>
                        <div class="flex items-end">
                            <label class="flex items-center gap-2 cursor-pointer">
                                <input v-model="form.encrypt" type="checkbox" />
                                <span class="text-sm">🔐 Şifrele (AES-256)</span>
                            </label>
                        </div>
                    </div>

                    <!-- Retention -->
                    <div class="rounded-lg border border-slate-200 p-3">
                        <div class="text-xs font-semibold uppercase text-slate-500 mb-2">Retention Politikası</div>
                        <div class="grid grid-cols-4 gap-3">
                            <div>
                                <label class="text-xs">Günlük</label>
                                <input v-model.number="form.keep_daily" type="number" min="0" max="90" class="w-full rounded border border-slate-300 px-2 py-1 text-sm font-mono" />
                            </div>
                            <div>
                                <label class="text-xs">Haftalık</label>
                                <input v-model.number="form.keep_weekly" type="number" min="0" max="52" class="w-full rounded border border-slate-300 px-2 py-1 text-sm font-mono" />
                            </div>
                            <div>
                                <label class="text-xs">Aylık</label>
                                <input v-model.number="form.keep_monthly" type="number" min="0" max="36" class="w-full rounded border border-slate-300 px-2 py-1 text-sm font-mono" />
                            </div>
                            <div>
                                <label class="text-xs">Yıllık</label>
                                <input v-model.number="form.keep_yearly" type="number" min="0" max="10" class="w-full rounded border border-slate-300 px-2 py-1 text-sm font-mono" />
                            </div>
                        </div>
                        <p class="mt-1 text-xs text-slate-500">Örn: 7d/4w/6m/2y = son 7 günlük + 4 haftalık + 6 aylık + 2 yıllık</p>
                    </div>

                    <!-- Exclude paths -->
                    <div>
                        <label class="block text-sm font-medium">Hariç Tutulan Yollar</label>
                        <div class="mt-1 flex gap-1 flex-wrap">
                            <span v-for="p in form.exclude_paths" :key="p" class="inline-flex items-center gap-1 rounded bg-slate-100 px-2 py-1 text-xs">
                                {{ p }}
                                <button type="button" @click="removeExclude(p)" class="text-slate-400 hover:text-red-500">×</button>
                            </span>
                        </div>
                        <div class="mt-2 flex gap-2">
                            <input v-model="newExclude" @keyup.enter.prevent="addExclude" type="text" placeholder="node_modules" class="flex-1 rounded border border-slate-300 px-2 py-1 font-mono text-xs" />
                            <button type="button" @click="addExclude" class="rounded bg-slate-200 px-3 text-xs">Ekle</button>
                        </div>
                    </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" class="rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700">Profil Oluştur</button>
                    </div>
                </form>
            </div>
        </div>
    </AdminLayout>
</template>
