<script setup>
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout.vue'
import { Head, router } from '@inertiajs/vue3'
import { ref, computed } from 'vue'

const props = defineProps({
    services: {
        type: Array,
        default: () => [],
    },
    archived: {
        type: Boolean,
        default: false,
    },
})

const toastMessage = ref('')
const toastType = ref('info')
const confirmDialog = ref(false)
const confirmWarnings = ref([])
const confirmServiceId = ref(null)
const deleteDialog = ref(false)
const deleteServiceId = ref(null)
const deleteServiceTitle = ref('')
const finalizing = ref(false)
const showArchived = computed(() => props.archived)

function formatDate(dateStr) {
    if (!dateStr) return '—'
    const d = new Date(dateStr)
    return d.toLocaleDateString('de-DE', {
        day: '2-digit',
        month: '2-digit',
        year: 'numeric',
    })
}

function formatDateTime(dateStr) {
    if (!dateStr) return '—'
    const d = new Date(dateStr)
    return d.toLocaleDateString('de-DE', {
        day: '2-digit',
        month: '2-digit',
        year: 'numeric',
        hour: '2-digit',
        minute: '2-digit',
    })
}

function showToast(message, type = 'info') {
    toastMessage.value = message
    toastType.value = type

    setTimeout(() => {
        toastMessage.value = ''
    }, 3500)
}

function toastClasses() {
    if (toastType.value === 'success') {
        return 'border-emerald-300 bg-emerald-50 text-emerald-700'
    }
    if (toastType.value === 'warning') {
        return 'border-orange-300 bg-orange-50 text-orange-700'
    }
    return 'border-blue-300 bg-blue-50 text-blue-700'
}

async function finalizeService(serviceId) {
    finalizing.value = true
    try {
        const response = await fetch(route('services.finalize', serviceId), {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content ?? '',
            },
            body: JSON.stringify({ confirmed: false }),
        })
        const data = await response.json()

        if (data.needs_confirmation) {
            confirmWarnings.value = data.warnings
            confirmServiceId.value = serviceId
            confirmDialog.value = true
            return
        }

        showToast(data.success, 'success')
        router.reload({ preserveScroll: true })
    } finally {
        finalizing.value = false
    }
}

async function confirmFinalize() {
    finalizing.value = true
    confirmDialog.value = false
    try {
        const response = await fetch(route('services.finalize', confirmServiceId.value), {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content ?? '',
            },
            body: JSON.stringify({ confirmed: true }),
        })
        const data = await response.json()

        showToast(data.success, 'success')
        router.reload({ preserveScroll: true })
    } finally {
        finalizing.value = false
        confirmServiceId.value = null
        confirmWarnings.value = []
    }
}

function cancelFinalize() {
    confirmDialog.value = false
    confirmServiceId.value = null
    confirmWarnings.value = []
}

function reopenService(serviceId) {
    router.post(route('services.reopen', serviceId), {}, {
        preserveScroll: true,
        onSuccess: () => showToast('Service wurde wieder geöffnet.', 'success'),
    })
}

function promptDeleteService(service) {
    deleteServiceId.value = service.id
    deleteServiceTitle.value = service.title
    deleteDialog.value = true
}

function cancelDeleteService() {
    deleteDialog.value = false
    deleteServiceId.value = null
    deleteServiceTitle.value = ''
}

function confirmDeleteService() {
    router.delete(route('services.destroy', deleteServiceId.value), {
        preserveScroll: true,
        onSuccess: () => {
            deleteDialog.value = false
            deleteServiceId.value = null
            deleteServiceTitle.value = ''
            showToast('Service wurde gelöscht.', 'success')
        },
    })
}

async function downloadService(serviceId) {
    try {
        const response = await fetch(route('services.download', serviceId), {
            headers: {
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content ?? '',
            },
        })

        if (!response.ok) {
            const data = await response.json().catch(() => ({}))
            showToast(data.message || 'Fehler beim Herunterladen.', 'warning')
            return
        }

        const disposition = response.headers.get('content-disposition')
        const filenameMatch = disposition?.match(/filename="?([^"]+)"?/)
        const filename = filenameMatch?.[1] || 'playlist.proplaylist'

        const blob = await response.blob()
        const url = URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = filename
        a.click()
        URL.revokeObjectURL(url)

        showToast('Playlist wurde heruntergeladen.', 'success')
    } catch {
        showToast('Fehler beim Herunterladen.', 'warning')
    }
}

function mappingStatusClass(service) {
    if (service.songs_total_count === 0) {
        return 'text-red-600'
    }

    if (service.songs_mapped_count === service.songs_total_count) {
        return 'text-emerald-700'
    }

    return 'text-orange-600'
}

function arrangementStatusClass(service) {
    if (service.songs_total_count === 0) {
        return 'text-red-600'
    }

    if (service.songs_arranged_count === service.songs_total_count) {
        return 'text-emerald-700'
    }

    return 'text-orange-600'
}

function stateIconClass(isDone) {
    return isDone ? 'text-emerald-600' : 'text-red-600'
}
</script>

<template>
    <Head title="Services" />

    <AuthenticatedLayout>
        <template #header>
            <div class="flex flex-wrap items-center justify-between gap-4">
                <div>
                    <h2 class="text-xl font-semibold leading-tight text-gray-800">Services</h2>
                    <p class="mt-1 text-sm text-gray-500">
                        {{ showArchived ? 'Hier siehst du alle vergangenen Services.' : 'Hier siehst du alle heutigen und kommenden Services.' }}
                    </p>
                </div>
                <div class="inline-flex rounded-lg border border-gray-300 bg-white p-1 shadow-sm">
                    <button
                        type="button"
                        :class="[
                            'rounded-md px-4 py-2 text-sm font-medium transition-all',
                            !showArchived
                                ? 'bg-blue-600 text-white shadow-sm'
                                : 'text-gray-700 hover:bg-gray-100',
                        ]"
                        @click="router.get(route('services.index'), { archived: 0 }, { preserveState: true, preserveScroll: true })"
                    >
                        Kommende
                    </button>
                    <button
                        type="button"
                        :class="[
                            'rounded-md px-4 py-2 text-sm font-medium transition-all',
                            showArchived
                                ? 'bg-blue-600 text-white shadow-sm'
                                : 'text-gray-700 hover:bg-gray-100',
                        ]"
                        @click="router.get(route('services.index'), { archived: 1 }, { preserveState: true, preserveScroll: true })"
                    >
                        Vergangene
                    </button>
                </div>
            </div>
        </template>

        <div class="py-8">
            <div class="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
                <Transition
                    enter-active-class="transition duration-200 ease-out"
                    enter-from-class="translate-y-1 opacity-0"
                    enter-to-class="translate-y-0 opacity-100"
                    leave-active-class="transition duration-150 ease-in"
                    leave-from-class="opacity-100"
                    leave-to-class="opacity-0"
                >
                    <div
                        v-if="toastMessage"
                        :class="toastClasses()"
                        role="status"
                    >
                        {{ toastMessage }}
                    </div>
                </Transition>

                <div class="overflow-hidden rounded-xl border border-gray-200 bg-white shadow-sm">
                    <div v-if="services.length === 0" data-testid="service-list-empty" class="p-8 text-center text-sm text-gray-500">
                        {{ showArchived ? 'Keine vergangenen Services vorhanden.' : 'Aktuell gibt es keine heutigen oder kommenden Services.' }}
                    </div>

                    <div v-else class="overflow-x-auto">
                        <table data-testid="service-list-table" class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th class="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wider text-gray-500">Titel</th>
                                    <th class="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wider text-gray-500">Prediger</th>
                                    <th class="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wider text-gray-500">Beamer-Techniker</th>
                                    <th class="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wider text-gray-500">Anzahl Songs</th>
                                    <th class="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wider text-gray-500">Letzte Änderung</th>
                                    <th class="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wider text-gray-500">Status</th>
                                    <th class="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wider text-gray-500">Aktionen</th>
                                </tr>
                            </thead>

                            <tbody class="divide-y divide-gray-100 bg-white">
                                <tr v-for="service in services" :key="service.id" :data-testid="`service-list-row-${service.id}`" class="align-top hover:bg-gray-50/60">
                                    <td class="px-4 py-4">
                                        <div class="font-medium text-gray-900" :title="'CTS Event #' + service.cts_event_id">{{ service.title }}</div>
                                        <div class="mt-1 text-xs text-gray-500">{{ formatDate(service.date) }}</div>
                                    </td>

                                    <td class="px-4 py-4 text-sm text-gray-700">
                                        {{ service.preacher_name || '-' }}
                                    </td>

                                    <td class="px-4 py-4 text-sm text-gray-700">
                                        {{ service.beamer_tech_name || '-' }}
                                    </td>

                                    <td class="px-4 py-4 text-sm text-gray-700">
                                        {{ service.songs_total_count }}
                                    </td>

                                    <td class="px-4 py-4 text-sm text-gray-700">
                                        {{ formatDateTime(service.updated_at) }}
                                    </td>

                                    <td class="px-4 py-4">
                                        <div class="space-y-1.5 text-xs font-medium">
                                            <div v-if="!service.has_agenda" class="flex items-center gap-1.5 text-gray-400">
                                                <span aria-hidden="true">•</span>
                                                <span>Keine Agenda</span>
                                            </div>

                                            <div :class="mappingStatusClass(service)">
                                                {{ service.songs_mapped_count }}/{{ service.songs_total_count }} Songs zugeordnet
                                            </div>

                                            <div :class="arrangementStatusClass(service)">
                                                {{ service.songs_arranged_count }}/{{ service.songs_total_count }} Arrangements geprueft
                                            </div>

                                            <div :class="stateIconClass(service.has_sermon_slides)" class="flex items-center gap-1.5">
                                                <span aria-hidden="true">{{ service.has_sermon_slides ? '✓' : '•' }}</span>
                                                <span>Predigtfolien</span>
                                            </div>

                                            <div :class="stateIconClass(service.info_slides_count > 0)" class="flex items-center gap-1.5">
                                                <span aria-hidden="true">{{ service.info_slides_count > 0 ? '✓' : '•' }}</span>
                                                <span>{{ service.info_slides_count }} Infofolien</span>
                                            </div>

                                            <div
                                                v-if="service.agenda_slides_count > 0"
                                                data-testid="agenda-slides-count"
                                                class="flex items-center gap-1.5 text-emerald-700"
                                            >
                                                <span aria-hidden="true">✓</span>
                                                <span>{{ service.agenda_slides_count }} weitere Folien</span>
                                            </div>

                                            <div :class="stateIconClass(Boolean(service.finalized_at))" class="flex items-center gap-1.5">
                                                <span aria-hidden="true">{{ service.finalized_at ? '✓' : '•' }}</span>
                                                <span>
                                                    Abgeschlossen am
                                                    {{ service.finalized_at ? formatDateTime(service.finalized_at) : '-' }}
                                                </span>
                                            </div>
                                        </div>
                                    </td>

                                    <td class="px-4 py-4">
                                        <div class="flex flex-col gap-2">
                                            <template v-if="service.finalized_at">
                                                <button
                                                    data-testid="service-list-reopen-button"
                                                    type="button"
                                                    class="inline-flex items-center justify-center rounded-md border border-amber-300 bg-amber-50 px-3 py-1.5 text-xs font-semibold text-amber-800 transition hover:bg-amber-100"
                                                    @click="reopenService(service.id)"
                                                >
                                                    Wieder öffnen
                                                </button>
                                                <button
                                                    data-testid="service-list-download-button"
                                                    type="button"
                                                    class="inline-flex items-center justify-center rounded-md border border-gray-300 bg-white px-3 py-1.5 text-xs font-semibold text-gray-700 transition hover:bg-gray-50"
                                                    @click="downloadService(service.id)"
                                                >
                                                    Herunterladen
                                                </button>
                                                <button
                                                    data-testid="service-list-delete-button"
                                                    type="button"
                                                    class="inline-flex items-center justify-center rounded-md border border-red-300 bg-red-50 px-3 py-1.5 text-xs font-semibold text-red-800 transition hover:bg-red-100"
                                                    @click="promptDeleteService(service)"
                                                >
                                                    Löschen
                                                </button>
                                            </template>

                                            <template v-else>
                                                <button
                                                    data-testid="service-list-edit-button"
                                                    type="button"
                                                    :class="[
                                                        'inline-flex items-center justify-center rounded-md border px-3 py-1.5 text-xs font-semibold transition',
                                                        service.has_agenda
                                                            ? 'border-gray-300 bg-white text-gray-700 hover:bg-gray-50'
                                                            : 'cursor-not-allowed border-gray-200 bg-gray-100 text-gray-400',
                                                    ]"
                                                    :disabled="!service.has_agenda"
                                                    :title="!service.has_agenda ? 'Keine Agenda vorhanden' : ''"
                                                    @click="service.has_agenda && router.get(route('services.edit', service.id))"
                                                >
                                                    Bearbeiten
                                                </button>
                                                <button
                                                    data-testid="service-list-finalize-button"
                                                    type="button"
                                                    :class="[
                                                        'inline-flex items-center justify-center rounded-md border px-3 py-1.5 text-xs font-semibold transition',
                                                        service.has_agenda
                                                            ? 'border-emerald-300 bg-emerald-50 text-emerald-800 hover:bg-emerald-100'
                                                            : 'cursor-not-allowed border-gray-200 bg-gray-100 text-gray-400',
                                                    ]"
                                                    :disabled="finalizing || !service.has_agenda"
                                                    :title="!service.has_agenda ? 'Keine Agenda vorhanden' : ''"
                                                    @click="service.has_agenda && finalizeService(service.id)"
                                                >
                                                    Abschließen
                                                </button>
                                                <button
                                                    data-testid="service-list-delete-button"
                                                    type="button"
                                                    class="inline-flex items-center justify-center rounded-md border border-red-300 bg-red-50 px-3 py-1.5 text-xs font-semibold text-red-800 transition hover:bg-red-100"
                                                    @click="promptDeleteService(service)"
                                                >
                                                    Löschen
                                                </button>
                                            </template>
                                        </div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- Confirmation Dialog -->
        <Teleport to="body">
            <Transition
                enter-active-class="transition duration-200 ease-out"
                enter-from-class="opacity-0"
                enter-to-class="opacity-100"
                leave-active-class="transition duration-150 ease-in"
                leave-from-class="opacity-100"
                leave-to-class="opacity-0"
            >
                <div
                    v-if="confirmDialog"
                    class="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4"
                    @click.self="cancelFinalize"
                >
                    <div class="w-full max-w-md rounded-xl bg-white p-6 shadow-xl">
                        <h3 class="text-lg font-semibold text-gray-900">Service abschließen?</h3>
                        <p class="mt-2 text-sm text-gray-600">
                            Es gibt noch offene Punkte. Möchtest du trotzdem abschließen?
                        </p>

                        <ul class="mt-3 space-y-1.5">
                            <li
                                v-for="(warning, idx) in confirmWarnings"
                                :key="idx"
                                class="flex items-start gap-2 text-sm text-amber-700"
                            >
                                <span class="mt-0.5 shrink-0" aria-hidden="true">⚠</span>
                                <span>{{ warning }}</span>
                            </li>
                        </ul>

                        <div class="mt-5 flex justify-end gap-3">
                            <button
                                data-testid="service-list-confirm-cancel-button"
                                type="button"
                                class="rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 transition hover:bg-gray-50"
                                @click="cancelFinalize"
                            >
                                Abbrechen
                            </button>
                            <button
                                data-testid="service-list-confirm-submit-button"
                                type="button"
                                class="rounded-md border border-emerald-300 bg-emerald-600 px-4 py-2 text-sm font-semibold text-white transition hover:bg-emerald-700"
                                @click="confirmFinalize"
                            >
                                Trotzdem abschließen
                            </button>
                        </div>
                    </div>
                </div>
            </Transition>
        </Teleport>

        <Teleport to="body">
            <Transition
                enter-active-class="transition duration-200 ease-out"
                enter-from-class="opacity-0"
                enter-to-class="opacity-100"
                leave-active-class="transition duration-150 ease-in"
                leave-from-class="opacity-100"
                leave-to-class="opacity-0"
            >
                <div
                    v-if="deleteDialog"
                    class="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4"
                    @click.self="cancelDeleteService"
                >
                    <div class="w-full max-w-md rounded-xl bg-white p-6 shadow-xl">
                        <h3 class="text-lg font-semibold text-gray-900">Service löschen?</h3>
                        <p class="mt-2 text-sm text-gray-600">
                            „{{ deleteServiceTitle }}" wird gelöscht und beim nächsten Sync aus ChurchTools neu erstellt.
                        </p>
                        <div class="mt-5 flex justify-end gap-3">
                            <button
                                type="button"
                                class="rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 transition hover:bg-gray-50"
                                @click="cancelDeleteService"
                            >
                                Abbrechen
                            </button>
                            <button
                                type="button"
                                class="rounded-md border border-red-300 bg-red-600 px-4 py-2 text-sm font-semibold text-white transition hover:bg-red-700"
                                @click="confirmDeleteService"
                            >
                                Löschen
                            </button>
                        </div>
                    </div>
                </div>
            </Transition>
        </Teleport>
    </AuthenticatedLayout>
</template>
