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

const { ask } = useConfirm()

const props = defineProps({ responders: Array, emails: Array })

const showForm = ref(false)

const form = useForm({
    email_account_id: null,
    subject: 'Otomatik Yanıt',
    body: 'Merhaba,\n\nMesajınız için teşekkür ederim. Şu anda ofisten uzaktayım ve mesajları okuyamıyorum. En kısa sürede size geri döneceğim.\n\nSaygılarımla',
    from_name: '',
    start_at: '',
    stop_at: '',
    interval_hours: 24,
    is_active: true,
})

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

const remove = async (r) => {
    const ok = await ask({
        title: 'Onaylayın',
        message: 'Otomatik yanıtlayıcı silinecek?',
        variant: 'danger',
        confirmText: 'Sil',
        cancelText: 'İptal',
    })
    if (!ok) return
    router.delete(route('customer.email.autoresponders.destroy', r.id), { preserveScroll: true })
}

const toggle = (r) => router.post(route('customer.email.autoresponders.toggle', r.id), {}, { preserveScroll: true })
</script>

<template>
    <Head title="Otomatik Yanıtlayıcı" />
    <CustomerLayout>
        <template #header>Otomatik Yanıtlayıcılar</template>

        <div class="mb-4 flex gap-2 text-sm">
            <Link :href="route('customer.email.index')" class="text-slate-600 hover:text-indigo-700">E-posta Hesapları</Link>
            <span class="text-slate-300">/</span>
            <Link :href="route('customer.email.filters.index')" class="text-slate-600 hover:text-indigo-700">Filtreler</Link>
            <span class="text-slate-300">/</span>
            <span class="font-medium text-indigo-700">Otomatik Yanıtlayıcılar</span>
        </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>
                    Tatil veya yoğun dönemlerde otomatik yanıt gönderin. Aynı kişiye <code>interval_hours</code>
                    saatte bir yanıt gönderilir (spam loop koruması).
                </div>
            </div>
        </div>

        <div class="mb-4 flex justify-end">
            <button @click="showForm = true" :disabled="emails.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 Otomatik Yanıtlayıcı
            </button>
        </div>

        <div v-if="emails.length === 0" class="rounded-xl border border-amber-200 bg-amber-50 p-6 text-sm text-amber-900">
            Önce bir e-posta hesabı oluşturmalısınız.
            <Link :href="route('customer.email.index')" class="font-medium underline">E-posta Hesapları</Link>
        </div>

        <EmptyState
            v-else-if="responders.length === 0"
            :icon="ChatBubbleLeftRightIcon"
            title="Henüz otomatik yanıtlayıcı yok"
            description="Tatil/iş dışı durumlarda otomatik yanıt göndermek için yeni bir kural ekleyin."
        />

        <div v-else class="space-y-3">
            <div v-for="r in responders" :key="r.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">
                            <EnvelopeIcon class="h-4 w-4 text-indigo-500" />
                            <span class="font-mono text-sm font-semibold">{{ r.email }}</span>
                            <span v-if="r.is_active" class="rounded bg-emerald-100 px-1.5 py-0.5 text-[10px] font-semibold uppercase text-emerald-700">Aktif</span>
                            <span v-else class="rounded bg-slate-100 px-1.5 py-0.5 text-[10px] font-semibold uppercase text-slate-500">Pasif</span>
                        </div>
                        <div class="mt-1 text-sm text-slate-700">
                            <strong>Konu:</strong> {{ r.subject }}
                        </div>
                        <div class="mt-2 max-h-24 overflow-hidden rounded bg-slate-50 p-2 font-mono text-xs text-slate-600 whitespace-pre-wrap">{{ r.body }}</div>
                        <div class="mt-2 flex flex-wrap gap-3 text-xs text-slate-500">
                            <span v-if="r.start_at"><ClockIcon class="h-3 w-3 inline" /> Başlangıç: {{ r.start_at }}</span>
                            <span v-if="r.stop_at"><ClockIcon class="h-3 w-3 inline" /> Bitiş: {{ r.stop_at }}</span>
                            <span>Aralık: her {{ r.interval_hours }} saat</span>
                        </div>
                    </div>
                    <div class="flex gap-1">
                        <button @click="toggle(r)" :class="['rounded p-1.5', r.is_active ? 'text-amber-500 hover:bg-amber-50' : 'text-emerald-500 hover:bg-emerald-50']">
                            <PowerIcon class="h-4 w-4" />
                        </button>
                        <button @click="remove(r)" class="rounded p-1.5 text-red-500 hover:bg-red-50">
                            <TrashIcon class="h-4 w-4" />
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Form 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">
                <div class="mb-4 flex items-center justify-between">
                    <h3 class="text-lg font-semibold">Yeni Otomatik Yanıtlayıcı</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">E-posta Hesabı</label>
                        <select v-model="form.email_account_id" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm">
                            <option :value="null">Seçin...</option>
                            <option v-for="e in emails" :key="e.id" :value="e.id">{{ e.local }}@{{ e.domain }}</option>
                        </select>
                    </div>
                    <div class="grid grid-cols-2 gap-3">
                        <div>
                            <label class="block text-sm font-medium">Gönderen Adı</label>
                            <input v-model="form.from_name" type="text" placeholder="Şirket Adı" 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">Aralık (saat)</label>
                            <input v-model.number="form.interval_hours" type="number" min="1" max="720" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm" />
                        </div>
                    </div>
                    <div>
                        <label class="block text-sm font-medium">Konu</label>
                        <input v-model="form.subject" 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">Mesaj</label>
                        <textarea v-model="form.body" rows="6" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm font-mono"></textarea>
                    </div>
                    <div class="grid grid-cols-2 gap-3">
                        <div>
                            <label class="block text-sm font-medium">Başlangıç (ops.)</label>
                            <input v-model="form.start_at" type="datetime-local" 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">Bitiş (ops.)</label>
                            <input v-model="form.stop_at" type="datetime-local" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm" />
                        </div>
                    </div>
                    <div class="flex justify-end gap-2 border-t border-slate-200 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.email_account_id || form.processing" class="rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700">Kaydet</button>
                    </div>
                </form>
            </div>
        </div>
    </CustomerLayout>
</template>
