<script setup>
import { ref } from 'vue'
import { router, useForm } from '@inertiajs/vue3'
import {
    PlusIcon,
    DocumentDuplicateIcon,
    ArrowUpCircleIcon,
    TrashIcon,
    InformationCircleIcon,
} from '@heroicons/vue/24/outline'
import { useConfirm } from '@/composables/useConfirm'

const { ask } = useConfirm()

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

const showCreateModal = ref(false)
const showPushModal = ref(false)
const selectedStaging = ref(null)

const createForm = useForm({ staging_label: 'staging' })
const pushForm = useForm({ include_db: true, include_files: true, exclude_uploads: true })

const submitCreate = () => createForm.post(route('customer.wp.staging.create', props.site.id), {
    preserveScroll: true,
    onSuccess: () => { showCreateModal.value = false; createForm.reset(); createForm.staging_label = 'staging' },
})

const openPushModal = (staging) => {
    selectedStaging.value = staging
    pushForm.reset()
    pushForm.include_db = true
    pushForm.include_files = true
    pushForm.exclude_uploads = true
    showPushModal.value = true
}

const submitPush = async () => {
    const ok = await ask({
        title: 'Onaylayın',
        message: `UYARI: Bu işlem production'ı staging ile ÜZERINE YAZACAK. Devam?`,
        variant: 'warning',
        confirmText: 'Onayla',
        cancelText: 'İptal',
    })
    if (!ok) return
    pushForm.post(route('customer.wp.staging.push', selectedStaging.value.id), {
        preserveScroll: true,
        onSuccess: () => { showPushModal.value = false },
    })
}

const deleteStaging = async (staging) => {
    const ok = await ask({
        title: 'Onaylayın',
        message: `"${staging.staging_label}" staging'i kalıcı olarak silinecek. Emin misiniz?`,
        variant: 'danger',
        confirmText: 'Sil',
        cancelText: 'İptal',
    })
    if (!ok) return
    router.delete(route('customer.wp.staging.delete', staging.id), { preserveScroll: true })
}

const statusLabel = (s) => ({ active: 'Aktif', installing: 'Kuruluyor...', failed: 'Hata', pending: 'Bekliyor' })[s] ?? s
const statusClass = (s) => ({
    active:     'bg-emerald-100 text-emerald-700',
    installing: 'bg-blue-100 text-blue-700 animate-pulse',
    failed:     'bg-red-100 text-red-700',
    pending:    'bg-slate-100 text-slate-500',
})[s] ?? 'bg-slate-100 text-slate-500'
</script>

<template>
    <div>
        <!-- Header -->
        <div class="mb-3 flex items-center justify-between">
            <span class="text-sm text-slate-500">{{ stagings.length }} staging ortam</span>
            <button @click="showCreateModal = true"
                    class="inline-flex items-center gap-1 rounded-lg bg-purple-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-purple-700">
                <PlusIcon class="h-3.5 w-3.5" /> Yeni Staging Oluştur
            </button>
        </div>

        <!-- Info banner -->
        <div class="mb-4 rounded-lg bg-indigo-50 px-4 py-3 text-xs text-indigo-800 flex items-start gap-2">
            <InformationCircleIcon class="h-4 w-4 mt-0.5 shrink-0" />
            <span>Staging, production sitenizin tam kopyasıdır. Değişikliklerinizi burada test edin, ardından "Production'a Gönder" butonu ile yayına alın.</span>
        </div>

        <!-- Staging list -->
        <div v-if="stagings.length" class="space-y-3">
            <div v-for="s in stagings" :key="s.id"
                 class="flex items-center justify-between gap-4 rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
                <div class="flex items-center gap-3">
                    <div class="flex h-10 w-10 items-center justify-center rounded-lg bg-purple-100 text-xl">
                        🧪
                    </div>
                    <div>
                        <div class="flex items-center gap-2">
                            <p class="font-semibold text-slate-900">{{ s.staging_label }}</p>
                            <span :class="['rounded px-1.5 py-0.5 text-[10px] font-semibold', statusClass(s.status)]">
                                {{ statusLabel(s.status) }}
                            </span>
                        </div>
                        <a :href="s.install_url" target="_blank" class="font-mono text-xs text-indigo-600 hover:underline">{{ s.install_url }}</a>
                        <p class="text-xs text-slate-400 mt-0.5">{{ s.installed_at }}</p>
                    </div>
                </div>
                <div class="flex items-center gap-2 shrink-0">
                    <button v-if="s.status === 'active'" @click="openPushModal(s)"
                            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">
                        <ArrowUpCircleIcon class="h-3.5 w-3.5" /> Production'a Gönder
                    </button>
                    <a :href="s.install_url + '/wp-admin/'" target="_blank"
                       class="rounded-lg border border-slate-300 px-3 py-1.5 text-xs font-medium text-slate-700 hover:bg-slate-50">
                        wp-admin
                    </a>
                    <button @click="deleteStaging(s)"
                            class="rounded-lg border border-red-200 px-2 py-1.5 text-xs text-red-500 hover:bg-red-50">
                        <TrashIcon class="h-3.5 w-3.5" />
                    </button>
                </div>
            </div>
        </div>

        <div v-else class="rounded-xl border-2 border-dashed border-slate-200 py-12 text-center">
            <DocumentDuplicateIcon class="mx-auto h-10 w-10 text-slate-300 mb-3" />
            <p class="text-sm font-medium text-slate-600">Henüz staging yok</p>
            <p class="text-xs text-slate-400 mt-1">Yukarıdan yeni bir staging ortamı oluşturun.</p>
        </div>

        <!-- Create modal -->
        <div v-if="showCreateModal" 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">
                <h3 class="mb-2 text-base font-semibold">Staging Oluştur</h3>
                <p class="mb-4 text-xs text-slate-500">
                    <strong>{{ site.domain_name }}</strong> için kopyalama başlatılacak. Bu işlem birkaç dakika sürebilir.
                </p>
                <form @submit.prevent="submitCreate" class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium mb-1">Staging Etiketi</label>
                        <div class="flex">
                            <input v-model="createForm.staging_label" type="text" placeholder="staging"
                                   class="flex-1 rounded-l-lg border border-slate-300 px-3 py-2 font-mono text-sm" />
                            <span class="rounded-r-lg border border-l-0 border-slate-300 bg-slate-50 px-3 py-2 font-mono text-sm text-slate-500">.{{ site.domain_name }}</span>
                        </div>
                        <p v-if="createForm.errors.staging_label" class="mt-1 text-xs text-red-600">{{ createForm.errors.staging_label }}</p>
                    </div>
                    <div class="flex justify-end gap-2">
                        <button type="button" @click="showCreateModal = false" class="rounded-lg border border-slate-300 px-4 py-2 text-sm">İptal</button>
                        <button type="submit" :disabled="createForm.processing" class="rounded-lg bg-purple-600 px-4 py-2 text-sm font-medium text-white hover:bg-purple-700 disabled:opacity-60">
                            {{ createForm.processing ? 'Oluşturuluyor...' : 'Oluştur' }}
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Push modal -->
        <div v-if="showPushModal" 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">
                <h3 class="mb-2 text-base font-semibold">Production'a Gönder</h3>
                <div class="mb-4 rounded-lg bg-red-50 px-3 py-2 text-xs text-red-800 flex items-start gap-2">
                    <InformationCircleIcon class="h-4 w-4 shrink-0 mt-0.5" />
                    <span>Bu işlem <strong>production {{ site.domain_name }}</strong>'ı staging ile üzerine yazacak. Geri alınamaz. Devam etmeden önce yedek alın.</span>
                </div>
                <form @submit.prevent="submitPush" class="space-y-3">
                    <label class="flex items-center gap-2 text-sm">
                        <input v-model="pushForm.include_files" type="checkbox" class="rounded" /> Dosyaları gönder
                    </label>
                    <label class="flex items-center gap-2 text-sm">
                        <input v-model="pushForm.include_db" type="checkbox" class="rounded" /> Veritabanını gönder
                    </label>
                    <label class="flex items-center gap-2 text-sm">
                        <input v-model="pushForm.exclude_uploads" type="checkbox" class="rounded" /> wp-content/uploads'u hariç tut
                    </label>
                    <div class="flex justify-end gap-2 pt-2">
                        <button type="button" @click="showPushModal = false" class="rounded-lg border border-slate-300 px-4 py-2 text-sm">İptal</button>
                        <button type="submit" :disabled="pushForm.processing" class="rounded-lg bg-red-600 px-4 py-2 text-sm font-medium text-white hover:bg-red-700 disabled:opacity-60">
                            {{ pushForm.processing ? 'Gönderiliyor...' : 'Production\'a Gönder' }}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</template>
