<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { Head, Link, router, useForm } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import {
    ArrowDownTrayIcon,
    CheckCircleIcon,
    ExclamationTriangleIcon,
    ClockIcon,
    XCircleIcon,
    ClipboardDocumentListIcon,
} from '@heroicons/vue/24/outline'
import { useConfirm } from '@/composables/useConfirm'

const { ask } = useConfirm()

const props = defineProps({
    job: Object,
    inspect: Object,
    packages: Array,
})

const liveStatus   = ref(props.job.status)
const liveProgress = ref(props.job.progress_pct)
const liveStep     = ref(props.job.current_step)
const liveWarnings = ref(props.job.warnings || [])
const liveError    = ref(props.job.error_message)
const pollingId    = ref(null)

const isLive = computed(() => liveStatus.value === 'restoring' || liveStatus.value === 'inspecting')

const plan = computed(() => props.inspect?.plan || {})

const stepLabel = (step) => ({
    extract:   'Arşiv çıkarılıyor',
    parse:     'Metadata parse ediliyor',
    account:   'Onoxsoft hesabı oluşturuluyor',
    home:      'Ev dizini kopyalanıyor',
    databases: 'Veritabanları import ediliyor',
    dns:       'DNS kayıtları yazılıyor',
    mail:      'E-posta hesapları oluşturuluyor',
    ssl:       'SSL sertifikaları kopyalanıyor',
    cron:      'Cron görevleri yazılıyor',
    limits:    'Paket limitleri uygulanıyor',
    done:      'Tamamlandı',
}[step] || step)

const statusBadge = (s) => ({
    uploaded:   'bg-blue-100 text-blue-700',
    inspecting: 'bg-amber-100 text-amber-700',
    planned:    'bg-indigo-100 text-indigo-700',
    restoring:  'bg-orange-100 text-orange-700',
    completed:  'bg-emerald-100 text-emerald-700',
    failed:     'bg-red-100 text-red-700',
    cancelled:  'bg-slate-100 text-slate-600',
}[s] || 'bg-slate-100 text-slate-700')

const statusLabel = (s) => ({
    uploaded:   'Yüklendi',
    inspecting: 'İnceleniyor',
    planned:    'Planlandı',
    restoring:  'Geri Yükleniyor',
    completed:  'Tamamlandı',
    failed:     'Hata',
    cancelled:  'İptal Edildi',
}[s] || s)

const poll = async () => {
    try {
        const res = await fetch(route('admin.migration.progress', props.job.id))
        const data = await res.json()
        liveStatus.value   = data.status
        liveProgress.value = data.progress_pct
        liveStep.value     = data.current_step
        liveWarnings.value = data.warnings || []
        liveError.value    = data.error_message

        if (!isLive.value) {
            clearInterval(pollingId.value)
            pollingId.value = null
        }
    } catch {
        // Ignore transient errors
    }
}

onMounted(() => {
    if (isLive.value) {
        pollingId.value = setInterval(poll, 2000)
    }
})

onBeforeUnmount(() => {
    if (pollingId.value) clearInterval(pollingId.value)
})

const doCancel = async () => {
    const ok = await ask({
        title: 'Onaylayın',
        message: 'Bu göç işlemi iptal edilsin mi?',
        variant: 'danger',
        confirmText: 'Sil',
        cancelText: 'İptal',
    })
    if (ok) {
        router.post(route('admin.migration.cancel', props.job.id))
    }
}

const doDelete = async () => {
    const ok = await ask({
        title: 'Onaylayın',
        message: 'Bu göç işlemi ve yüklenen dosya silinsin mi?',
        variant: 'danger',
        confirmText: 'Sil',
        cancelText: 'İptal',
    })
    if (ok) {
        router.delete(route('admin.migration.destroy', props.job.id), {
            onSuccess: () => router.visit(route('admin.migration.index')),
        })
    }
}

const doInspect = () => {
    router.post(route('admin.migration.inspect', props.job.id))
}
</script>

<template>
    <Head :title="`Migration #${job.id}`" />
    <AdminLayout>
        <template #header>
            <div class="flex items-center gap-2">
                <Link :href="route('admin.migration.index')" class="text-slate-400 hover:text-indigo-600">Migration</Link>
                <span class="text-slate-400">/</span>
                <span>Göç #{{ job.id }}</span>
            </div>
        </template>

        <!-- Header card -->
        <div class="mb-4 rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
            <div class="flex flex-wrap items-start justify-between gap-4">
                <div>
                    <div class="flex items-center gap-2">
                        <span :class="['rounded px-2 py-0.5 text-xs font-semibold', statusBadge(liveStatus)]">
                            {{ statusLabel(liveStatus) }}
                        </span>
                        <span class="font-mono text-sm">{{ job.source_username || '?' }}</span>
                        <span class="text-slate-400">→</span>
                        <span class="font-mono text-sm font-semibold">{{ job.target_username || '—' }}</span>
                    </div>
                    <p class="mt-1 text-xs text-slate-500">
                        Yükleyen: {{ job.initiated_by_name }} &bull; {{ job.created_at }}
                        <span v-if="job.duration_seconds"> &bull; {{ job.duration_seconds }}s</span>
                    </p>
                </div>
                <div class="flex gap-2">
                    <Link v-if="liveStatus === 'planned'"
                          :href="route('admin.migration.plan', job.id)"
                          class="inline-flex items-center gap-1.5 rounded-lg border border-indigo-300 bg-indigo-50 px-3 py-1.5 text-xs font-medium text-indigo-700 hover:bg-indigo-100">
                        <ClipboardDocumentListIcon class="h-4 w-4" /> Göç Planı
                    </Link>
                    <button v-if="liveStatus === 'uploaded'" @click="doInspect"
                            class="inline-flex items-center gap-1.5 rounded-lg border border-amber-300 bg-amber-50 px-3 py-1.5 text-xs font-medium text-amber-700 hover:bg-amber-100">
                        İncele
                    </button>
                    <button v-if="['uploaded','planned','restoring'].includes(liveStatus)"
                            @click="doCancel"
                            class="inline-flex items-center gap-1.5 rounded-lg border border-orange-300 bg-orange-50 px-3 py-1.5 text-xs font-medium text-orange-700 hover:bg-orange-100">
                        <XCircleIcon class="h-4 w-4" /> İptal
                    </button>
                    <button v-if="liveStatus !== 'restoring'" @click="doDelete"
                            class="inline-flex items-center gap-1.5 rounded-lg border border-red-200 bg-red-50 px-3 py-1.5 text-xs font-medium text-red-600 hover:bg-red-100">
                        Sil
                    </button>
                </div>
            </div>
        </div>

        <!-- Progress bar (while restoring) -->
        <div v-if="liveStatus === 'restoring'" class="mb-4 rounded-xl border border-indigo-200 bg-indigo-50 p-5">
            <div class="mb-2 flex items-center justify-between text-sm">
                <span class="font-medium text-indigo-800">
                    {{ liveStep ? stepLabel(liveStep) : 'İşleniyor...' }}
                </span>
                <span class="font-mono text-indigo-700">{{ liveProgress }}%</span>
            </div>
            <div class="h-3 w-full rounded-full bg-indigo-200">
                <div class="h-3 rounded-full bg-indigo-600 transition-all duration-500"
                     :style="{ width: liveProgress + '%' }"></div>
            </div>
            <p class="mt-2 text-xs text-indigo-700 animate-pulse">Canlı güncelleme aktif (2s)...</p>
        </div>

        <!-- Completed -->
        <div v-if="liveStatus === 'completed'" class="mb-4 rounded-xl border border-emerald-200 bg-emerald-50 p-4">
            <div class="flex items-center gap-2 text-emerald-800">
                <CheckCircleIcon class="h-5 w-5 text-emerald-600" />
                <span class="font-semibold">Göç başarıyla tamamlandı.</span>
            </div>
        </div>

        <!-- Failed -->
        <div v-if="liveStatus === 'failed' && liveError" class="mb-4 rounded-xl border border-red-200 bg-red-50 p-4">
            <div class="flex items-start gap-2">
                <XCircleIcon class="mt-0.5 h-5 w-5 flex-shrink-0 text-red-600" />
                <div class="flex-1">
                    <p class="font-semibold text-red-800">Göç başarısız</p>
                    <p class="mt-1 font-mono text-xs text-red-700">{{ liveError }}</p>
                    <p v-if="job.last_completed_step" class="mt-2 text-xs text-red-700">
                        Son tamamlanan step: <code class="rounded bg-red-100 px-1.5 py-0.5 font-mono">{{ job.last_completed_step }}</code>
                        — Plan sayfasından "Kaldığı yerden devam et" seçeneğiyle retry edebilirsiniz.
                    </p>
                    <Link v-if="job.last_completed_step"
                          :href="route('admin.migration.plan', job.id)"
                          class="mt-2 inline-flex items-center gap-1 rounded-lg bg-cyan-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-cyan-700">
                        Kaldığı Yerden Devam Et
                    </Link>
                </div>
            </div>
        </div>

        <!-- Warnings -->
        <div v-if="liveWarnings.length > 0" class="mb-4 rounded-xl border border-amber-200 bg-amber-50 p-4">
            <div class="flex gap-2">
                <ExclamationTriangleIcon class="mt-0.5 h-5 w-5 flex-shrink-0 text-amber-600" />
                <div>
                    <p class="mb-1 text-sm font-semibold text-amber-800">Uyarılar</p>
                    <ul class="space-y-0.5">
                        <li v-for="(w, i) in liveWarnings" :key="i" class="text-xs text-amber-800">• {{ w }}</li>
                    </ul>
                </div>
            </div>
        </div>

        <!-- Job details -->
        <div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
            <div class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                <h4 class="mb-3 text-xs font-semibold uppercase text-slate-500">Dosya Bilgisi</h4>
                <dl class="space-y-2 text-sm">
                    <div>
                        <dt class="text-xs text-slate-500">Dosya Adı</dt>
                        <dd class="font-mono text-xs break-all">{{ job.tar_filename }}</dd>
                    </div>
                    <div>
                        <dt class="text-xs text-slate-500">Boyut</dt>
                        <dd class="font-mono">{{ job.tar_size_human }}</dd>
                    </div>
                </dl>
            </div>

            <div class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                <h4 class="mb-3 text-xs font-semibold uppercase text-slate-500">Kaynak Hesap</h4>
                <dl class="space-y-2 text-sm">
                    <div>
                        <dt class="text-xs text-slate-500">Kullanıcı</dt>
                        <dd class="font-mono">{{ job.source_username || '—' }}</dd>
                    </div>
                    <div v-if="inspect?.plan?.primary_domain">
                        <dt class="text-xs text-slate-500">Birincil Domain</dt>
                        <dd class="font-mono">{{ inspect.plan.primary_domain }}</dd>
                    </div>
                </dl>
            </div>

            <div class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                <h4 class="mb-3 text-xs font-semibold uppercase text-slate-500">Hedef Hesap</h4>
                <dl class="space-y-2 text-sm">
                    <div>
                        <dt class="text-xs text-slate-500">Kullanıcı</dt>
                        <dd class="font-mono font-semibold">{{ job.target_username || '—' }}</dd>
                    </div>
                    <div v-if="job.target_package_id">
                        <dt class="text-xs text-slate-500">Paket</dt>
                        <dd>{{ packages.find(p => p.id === job.target_package_id)?.name || job.target_package_id }}</dd>
                    </div>
                </dl>
            </div>

            <div v-if="job.options && Object.keys(job.options).length > 0"
                 class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm sm:col-span-2">
                <h4 class="mb-3 text-xs font-semibold uppercase text-slate-500">Seçenekler</h4>
                <div class="flex flex-wrap gap-2">
                    <template v-for="(val, key) in job.options" :key="key">
                        <span v-if="val" :class="[
                            'rounded px-2 py-0.5 text-xs font-medium',
                            key === 'overwrite_existing' ? 'bg-orange-100 text-orange-700' : 'bg-emerald-100 text-emerald-700'
                        ]">
                            {{ key.replace('restore_', '').replace('_', ' ') }}
                        </span>
                        <span v-else class="rounded bg-slate-100 px-2 py-0.5 text-xs text-slate-400 line-through">
                            {{ key.replace('restore_', '').replace('_', ' ') }}
                        </span>
                    </template>
                </div>
            </div>
        </div>
    </AdminLayout>
</template>
