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

const { ask } = useConfirm()

const props = defineProps({ jobs: Array, home: String })

const showForm = ref(false)
const editingJob = ref(null)

const form = useForm({
    label: '',
    expression: '*/5 * * * *',
    command: '',
    email_output: '',
    is_active: true,
})

const presets = [
    { value: '* * * * *', label: 'Her dakika' },
    { value: '*/5 * * * *', label: 'Her 5 dakikada bir' },
    { value: '*/15 * * * *', label: 'Her 15 dakikada bir' },
    { value: '0 * * * *', label: 'Her saat başı' },
    { value: '0 */6 * * *', label: 'Her 6 saatte bir' },
    { value: '0 3 * * *', label: 'Her gün saat 03:00' },
    { value: '0 0 * * 0', label: 'Her Pazar gece yarısı' },
    { value: '0 0 1 * *', label: 'Her ayın 1\'inde' },
]

const openCreate = () => {
    editingJob.value = null
    form.reset()
    form.expression = '*/5 * * * *'
    form.is_active = true
    showForm.value = true
}

const openEdit = (j) => {
    editingJob.value = j
    form.label = j.label || ''
    form.expression = j.expression
    form.command = j.command
    form.email_output = j.email_output || ''
    form.is_active = j.is_active
    showForm.value = true
}

const submit = () => {
    const action = editingJob.value
        ? form.patch(route('customer.cron.update', editingJob.value.id), { onSuccess: () => { showForm.value = false; form.reset() } })
        : form.post(route('customer.cron.store'), { onSuccess: () => { showForm.value = false; form.reset() } })
}

const remove = async (j) => {
    const ok = await ask({
        title: 'Onaylayın',
        message: `'${j.label || j.expression}' cron görevi silinsin mi?`,
        variant: 'danger',
        confirmText: 'Sil',
        cancelText: 'İptal',
    })
    if (!ok) return
    router.delete(route('customer.cron.destroy', j.id))
}
</script>

<template>
    <Head title="Cron Görevleri" />

    <CustomerLayout>
        <template #header>Zamanlanmış Görevler (Cron)</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>Cron expression formatı:</strong>
                    <code class="rounded bg-white px-1.5 py-0.5 font-mono">dakika saat ayın_günü ay haftanın_günü</code>
                    <br />
                    Komutlarınız <code class="rounded bg-white px-1.5 py-0.5 font-mono">{{ home }}</code> klasöründen çalışır.
                </div>
            </div>
        </div>

        <div class="mb-4 flex justify-end">
            <button @click="openCreate" 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">
                <PlusIcon class="h-4 w-4" /> Yeni Cron Görevi
            </button>
        </div>

        <EmptyState
            v-if="jobs.length === 0"
            :icon="ClockIcon"
            title="Henüz cron görevi yok"
            description="Düzenli yedek, WordPress wp-cron, sitemap güncelleme gibi periyodik komutlar ekleyin."
        />

        <div v-else class="space-y-3">
            <div v-for="j in jobs" :key="j.id" class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
                <div class="flex items-start justify-between gap-4">
                    <div class="flex items-start gap-3">
                        <div :class="['flex h-10 w-10 items-center justify-center rounded-lg', j.is_active ? 'bg-emerald-100' : 'bg-slate-100']">
                            <ClockIcon :class="['h-5 w-5', j.is_active ? 'text-emerald-600' : 'text-slate-400']" />
                        </div>
                        <div class="flex-1">
                            <div class="flex items-center gap-2">
                                <span class="font-semibold text-slate-900">{{ j.label || j.human_readable }}</span>
                                <span v-if="!j.is_active" class="rounded bg-slate-100 px-2 py-0.5 text-xs text-slate-500">Pasif</span>
                            </div>
                            <p class="mt-1 text-xs text-slate-500">
                                <code class="rounded bg-slate-100 px-1.5 py-0.5 font-mono">{{ j.expression }}</code>
                                <span class="ml-2">{{ j.human_readable }}</span>
                            </p>
                            <p class="mt-1 font-mono text-xs text-slate-700 break-all">
                                <CommandLineIcon class="inline h-3 w-3" /> {{ j.command }}
                            </p>
                            <p v-if="j.email_output" class="mt-1 text-xs text-slate-500">
                                📧 Çıktı: {{ j.email_output }}
                            </p>
                            <p v-if="j.last_run_at" class="mt-1 text-xs text-slate-500">
                                Son çalışma: {{ j.last_run_at }} (exit: {{ j.last_exit_code ?? '—' }})
                            </p>
                        </div>
                    </div>
                    <div class="flex gap-1">
                        <button @click="openEdit(j)" class="rounded p-2 text-indigo-500 hover:bg-indigo-50">
                            <PencilSquareIcon class="h-4 w-4" />
                        </button>
                        <button @click="remove(j)" class="rounded p-2 text-red-500 hover:bg-red-50">
                            <TrashIcon class="h-4 w-4" />
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <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">
                <div class="mb-4 flex items-center justify-between">
                    <h3 class="text-lg font-semibold">{{ editingJob ? 'Cron Görevini Düzenle' : 'Yeni Cron Görevi' }}</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>
                        <label class="block text-sm font-medium">Etiket (opsiyonel)</label>
                        <input v-model="form.label" type="text" placeholder="WordPress cache temizle" 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">Zamanlama</label>
                        <input v-model="form.expression" type="text" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 font-mono text-sm" />
                        <div class="mt-2 flex flex-wrap gap-1">
                            <button
                                v-for="p in presets"
                                :key="p.value"
                                type="button"
                                @click="form.expression = p.value"
                                :class="['rounded-full px-2.5 py-1 text-xs', form.expression === p.value ? 'bg-indigo-600 text-white' : 'bg-slate-100 text-slate-700 hover:bg-slate-200']"
                            >
                                {{ p.label }}
                            </button>
                        </div>
                    </div>

                    <div>
                        <label class="block text-sm font-medium">Komut</label>
                        <textarea v-model="form.command" rows="3" placeholder="cd /home/user && wp cron event run --due-now" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 font-mono text-sm"></textarea>
                        <p class="mt-1 text-xs text-slate-500">Bash komut. Çıktı varsa e-posta opsiyonu ile gönderilir.</p>
                    </div>

                    <div>
                        <label class="block text-sm font-medium">Çıktı E-postası (opsiyonel)</label>
                        <input v-model="form.email_output" type="email" placeholder="admin@example.com" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm" />
                    </div>

                    <label class="flex items-center gap-2 text-sm">
                        <input v-model="form.is_active" type="checkbox" class="rounded" />
                        Aktif
                    </label>

                    <div class="flex justify-end gap-2">
                        <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">
                            {{ editingJob ? 'Güncelle' : 'Oluştur' }}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </CustomerLayout>
</template>
