<script setup>
import { ref } from 'vue'
import { Head, router, useForm } from '@inertiajs/vue3'
import CustomerLayout from '@/Layouts/CustomerLayout.vue'
import {
    ArchiveBoxArrowDownIcon,
    PlusIcon,
    TrashIcon,
    XMarkIcon,
    ArrowUturnLeftIcon,
    ArrowDownTrayIcon,
    InformationCircleIcon,
    ExclamationTriangleIcon,
    CheckCircleIcon,
} from '@heroicons/vue/24/outline'
import EmptyState from '@/Components/EmptyState.vue'
import { useConfirm } from '@/composables/useConfirm'

const { ask } = useConfirm()

const props = defineProps({ snapshots: Array, limits: Object })

const showForm = ref(false)

const form = useForm({
    includes_files: true,
    includes_databases: true,
    includes_email: true,
    includes_dns: true,
    notes: '',
})

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

const remove = async (s) => {
    const ok = await ask({
        title: 'Onaylayın',
        message: `${s.snapshot_number} silinecek (geri alınamaz). Devam?`,
        variant: 'danger',
        confirmText: 'Sil',
        cancelText: 'İptal',
    })
    if (!ok) return
    router.delete(route('customer.snapshots.destroy', s.id), { preserveScroll: true })
}

const restore = async (s) => {
    const ok = await ask({
        title: 'Onaylayın',
        message: `${s.snapshot_number} restore edilecek. ⚠️ MEVCUT VERİLERİN ÜZERİNE YAZILACAK. Önce mevcut durumu yedeklemek istemez misin? Devam?`,
        variant: 'info',
        confirmText: 'Onayla',
        cancelText: 'İptal',
    })
    if (!ok) return
    router.post(route('customer.snapshots.restore', s.id), {}, { preserveScroll: true })
}

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

const expiryColor = (days) => {
    if (days === null) return 'text-slate-500'
    if (days <= 3) return 'text-red-600 font-semibold'
    if (days <= 7) return 'text-amber-600'
    return 'text-slate-500'
}

const atLimit = props.limits.active_count >= props.limits.max_active
const monthlyAtLimit = props.limits.monthly_count >= props.limits.max_per_month
</script>

<template>
    <Head title="Snapshot'larım" />
    <CustomerLayout>
        <template #header>Snapshot'larım (Hızlı Yedek)</template>

        <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>Snapshot:</strong> Hesabınızın anlık yedeğidir. Yeni WordPress güncellemesi öncesi,
                    büyük değişiklikten önce snapshot alıp gerekirse 1 saniyede geri dönebilirsiniz.
                    Sistem yedekleri (panel yöneticisi) ayrı tutulur.
                </div>
            </div>
        </div>

        <!-- Limits -->
        <div class="mb-4 grid grid-cols-3 gap-3">
            <div class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
                <div class="text-xs text-slate-500">Aktif Snapshot</div>
                <div class="mt-1 text-2xl font-bold">
                    {{ limits.active_count }} <span class="text-sm text-slate-400">/ {{ limits.max_active }}</span>
                </div>
                <div class="mt-2 h-1.5 overflow-hidden rounded-full bg-slate-200">
                    <div :class="['h-full', atLimit ? 'bg-red-500' : 'bg-emerald-500']"
                         :style="{ width: (limits.active_count / limits.max_active * 100) + '%' }"></div>
                </div>
            </div>
            <div class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
                <div class="text-xs text-slate-500">Bu Ay Oluşturulan</div>
                <div class="mt-1 text-2xl font-bold">
                    {{ limits.monthly_count }} <span class="text-sm text-slate-400">/ {{ limits.max_per_month }}</span>
                </div>
                <div class="mt-2 h-1.5 overflow-hidden rounded-full bg-slate-200">
                    <div :class="['h-full', monthlyAtLimit ? 'bg-red-500' : 'bg-blue-500']"
                         :style="{ width: (limits.monthly_count / limits.max_per_month * 100) + '%' }"></div>
                </div>
            </div>
            <div class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
                <div class="text-xs text-slate-500">Saklama Süresi</div>
                <div class="mt-1 text-2xl font-bold">{{ limits.retention_days }} <span class="text-sm text-slate-400">gün</span></div>
                <p class="text-xs text-slate-500 mt-1">Otomatik silinir</p>
            </div>
        </div>

        <div class="mb-4 flex justify-end">
            <button @click="showForm = true" :disabled="atLimit || monthlyAtLimit"
                    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 Snapshot Al
            </button>
        </div>

        <EmptyState
            v-if="snapshots.length === 0"
            :icon="ArchiveBoxArrowDownIcon"
            title="Henüz snapshot yok"
            description="İlk snapshot'ını al — risk almadan deneme yap, gerekirse geri dön."
        />

        <div v-else class="space-y-3">
            <div v-for="s in snapshots" :key="s.id" class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm hover:shadow-md transition">
                <div class="flex items-start justify-between gap-3 flex-wrap">
                    <div class="flex-1">
                        <div class="flex items-center gap-2 flex-wrap">
                            <h3 class="font-mono font-semibold">{{ s.snapshot_number }}</h3>
                            <span :class="['rounded px-2 py-0.5 text-xs font-semibold', statusBadge(s.status)]">{{ s.status }}</span>
                            <span class="text-xs text-slate-500">· {{ s.size_human }}</span>
                            <span class="text-xs text-slate-500">· {{ s.completed_at || s.created_at }}</span>
                            <span v-if="s.duration_seconds" class="text-xs text-slate-400">· {{ s.duration_seconds }}s</span>
                        </div>
                        <p v-if="s.notes" class="mt-1 text-sm text-slate-600 italic">"{{ s.notes }}"</p>
                        <div class="mt-2 flex flex-wrap gap-1">
                            <span v-if="s.includes_files" class="rounded bg-blue-100 px-1.5 py-0.5 text-[10px] font-medium text-blue-700">📁 Dosyalar</span>
                            <span v-if="s.includes_databases" class="rounded bg-cyan-100 px-1.5 py-0.5 text-[10px] font-medium text-cyan-700">💾 DB</span>
                            <span v-if="s.includes_email" class="rounded bg-rose-100 px-1.5 py-0.5 text-[10px] font-medium text-rose-700">📧 E-posta</span>
                        </div>
                        <p v-if="s.expires_at" :class="['mt-2 text-xs', expiryColor(s.expires_in_days)]">
                            <ExclamationTriangleIcon v-if="s.expires_in_days <= 7" class="inline h-3 w-3" />
                            Geçerlilik: {{ s.expires_at }} ({{ Math.abs(s.expires_in_days) }} gün)
                        </p>
                    </div>
                    <div class="flex gap-1">
                        <button v-if="s.can_restore" @click="restore(s)" class="inline-flex items-center gap-1 rounded-lg border border-purple-300 bg-purple-50 px-3 py-1.5 text-xs font-medium text-purple-700 hover:bg-purple-100">
                            <ArrowUturnLeftIcon class="h-3.5 w-3.5" /> Geri Yükle
                        </button>
                        <a v-if="s.can_restore" :href="route('customer.snapshots.download', s.id)" class="rounded p-1.5 text-blue-500 hover:bg-blue-50" title="İndir">
                            <ArrowDownTrayIcon class="h-4 w-4" />
                        </a>
                        <button @click="remove(s)" class="rounded p-1.5 text-red-500 hover:bg-red-50" title="Sil">
                            <TrashIcon class="h-4 w-4" />
                        </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-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 Snapshot Al</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="space-y-2">
                        <label class="flex items-center gap-2 rounded-lg border p-3 cursor-pointer hover:bg-slate-50"
                               :class="form.includes_files ? 'border-emerald-300 bg-emerald-50/30' : 'border-slate-200'">
                            <input v-model="form.includes_files" type="checkbox" />
                            <span class="text-sm">📁 Tüm Dosyalar (public_html, private)</span>
                        </label>
                        <label class="flex items-center gap-2 rounded-lg border p-3 cursor-pointer hover:bg-slate-50"
                               :class="form.includes_databases ? 'border-emerald-300 bg-emerald-50/30' : 'border-slate-200'">
                            <input v-model="form.includes_databases" type="checkbox" />
                            <span class="text-sm">💾 MySQL Veritabanları</span>
                        </label>
                        <label class="flex items-center gap-2 rounded-lg border p-3 cursor-pointer hover:bg-slate-50"
                               :class="form.includes_email ? 'border-emerald-300 bg-emerald-50/30' : 'border-slate-200'">
                            <input v-model="form.includes_email" type="checkbox" />
                            <span class="text-sm">📧 E-posta Kutuları</span>
                        </label>
                        <label class="flex items-center gap-2 rounded-lg border p-3 cursor-pointer hover:bg-slate-50"
                               :class="form.includes_dns ? 'border-emerald-300 bg-emerald-50/30' : 'border-slate-200'">
                            <input v-model="form.includes_dns" type="checkbox" />
                            <span class="text-sm">🌐 DNS Kayıtları</span>
                        </label>
                    </div>
                    <div>
                        <label class="block text-sm font-medium">Not (opsiyonel)</label>
                        <input v-model="form.notes" type="text" maxlength="500" placeholder="örn: WordPress 6.5 upgrade öncesi"
                               class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm" />
                    </div>
                    <div class="rounded-lg bg-amber-50 p-3 text-xs text-amber-800">
                        💡 Snapshot oluşturma 30 saniye - 5 dk sürebilir (boyuta göre). 30 gün sonra otomatik silinir.
                    </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">
                            <ArchiveBoxArrowDownIcon class="inline h-4 w-4 mr-1" /> Snapshot Al
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </CustomerLayout>
</template>
