<script setup>
import { ref } from 'vue'
import { route } from 'ziggy-js'

const props = defineProps({
    prefixFiles: { type: Array, default: () => [] },
    postfixFiles: { type: Array, default: () => [] },
    keywordFiles: { type: Array, default: () => [] },
})

const prefixDragActive = ref(false)
const postfixDragActive = ref(false)
const keywordDragActive = ref(false)
const keywordInput = ref('')
const uploading = ref(false)
const error = ref(null)

function getXsrfToken() {
    return decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1] ?? '')
}

async function uploadFiles(type, files, keyword = null) {
    if (!files || files.length === 0) return
    if (type === 'keyword' && (!keyword || keyword.trim() === '')) {
        error.value = 'Bitte gib zuerst ein Schlüsselwort ein.'
        return
    }
    uploading.value = true
    error.value = null

    const form = new FormData()
    form.append('type', type)
    if (type === 'keyword') {
        form.append('keyword', keyword.trim())
    }
    for (const file of files) {
        form.append('files[]', file)
    }

    try {
        const res = await fetch(route('settings.export-pro-files.store'), {
            method: 'POST',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'X-XSRF-TOKEN': getXsrfToken(),
            },
            body: form,
        })
        if (!res.ok) {
            const data = await res.json()
            error.value = data.message || 'Upload fehlgeschlagen'
            return
        }
        window.location.reload()
    } catch {
        error.value = 'Netzwerkfehler beim Upload'
    } finally {
        uploading.value = false
    }
}

function handlePrefixChange(event) {
    const files = event.target.files
    if (!files || files.length === 0) return
    event.target.value = ''
    uploadFiles('prefix', files)
}

function handlePostfixChange(event) {
    const files = event.target.files
    if (!files || files.length === 0) return
    event.target.value = ''
    uploadFiles('postfix', files)
}

function handleKeywordChange(event) {
    const files = event.target.files
    if (!files || files.length === 0) return
    event.target.value = ''
    uploadFiles('keyword', files, keywordInput.value)
}

function handlePrefixDrop(event) {
    prefixDragActive.value = false
    uploadFiles('prefix', event.dataTransfer.files)
}

function handlePostfixDrop(event) {
    postfixDragActive.value = false
    uploadFiles('postfix', event.dataTransfer.files)
}

function handleKeywordDrop(event) {
    keywordDragActive.value = false
    uploadFiles('keyword', event.dataTransfer.files, keywordInput.value)
}

async function updateKeyword(id, value) {
    error.value = null
    try {
        const res = await fetch(route('settings.export-pro-files.update-keyword', id), {
            method: 'PATCH',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest',
                'X-XSRF-TOKEN': getXsrfToken(),
            },
            body: JSON.stringify({ keyword: value }),
        })
        if (!res.ok) {
            const data = await res.json().catch(() => ({}))
            error.value = data.message || 'Aktualisierung fehlgeschlagen'
        }
    } catch {
        error.value = 'Netzwerkfehler beim Speichern'
    }
}

async function deleteFile(id) {
    try {
        await fetch(route('settings.export-pro-files.destroy', id), {
            method: 'DELETE',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'X-XSRF-TOKEN': getXsrfToken(),
            },
        })
        window.location.reload()
    } catch {
        // silent fail
    }
}
</script>

<template>
    <div class="space-y-8">
        <div>
            <h3 class="mb-1 text-sm font-semibold text-gray-900">Export-Dateien</h3>
            <p class="text-xs text-gray-500">
                Diese .pro- und .probundle-Dateien werden bei jedem Export vorne (Prefix) bzw. hinten (Postfix) an den Gottesdienst angehängt.
                Schlüsselwort-Dateien werden zusätzlich hinter jedem Ablaufpunkt eingefügt, dessen Titel das Schlüsselwort enthält.
            </p>
        </div>

        <div
            v-if="error"
            class="rounded-lg bg-red-50 p-3 text-sm text-red-700"
        >
            {{ error }}
        </div>

        <!-- Prefix section -->
        <div>
            <h4 class="mb-2 text-xs font-semibold uppercase tracking-wide text-gray-500">Prefix-Dateien</h4>
            <p class="mb-3 text-xs text-gray-400">Werden vor dem Gottesdienst eingefügt.</p>

            <label
                class="mb-4 flex cursor-pointer flex-col items-center justify-center rounded-xl border-2 border-dashed p-6 transition-colors"
                :class="prefixDragActive
                    ? 'border-amber-400 bg-amber-50'
                    : 'border-gray-200 bg-gray-50 hover:border-amber-300 hover:bg-amber-50'"
                data-testid="export-prefix-dropzone"
                @dragover.prevent
                @dragenter.prevent="prefixDragActive = true"
                @dragleave.prevent="prefixDragActive = false"
                @drop.prevent="handlePrefixDrop"
            >
                <svg class="mb-2 h-8 w-8 text-gray-300" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5m-13.5-9L12 3m0 0l4.5 4.5M12 3v13.5" />
                </svg>
                <span class="text-sm text-gray-500">
                    {{ uploading ? 'Wird hochgeladen...' : '.pro / .probundle-Dateien auswählen oder hierher ziehen' }}
                </span>
                <span class="mt-1 text-xs text-gray-400">Mehrere Dateien möglich</span>
                <input
                    type="file"
                    class="hidden"
                    accept=".pro,.probundle"
                    multiple
                    :disabled="uploading"
                    data-testid="export-prefix-file-input"
                    @change="handlePrefixChange"
                />
            </label>

            <div v-if="prefixFiles.length > 0" class="divide-y divide-gray-100 rounded-lg border border-gray-100">
                <div
                    v-for="file in prefixFiles"
                    :key="file.id"
                    class="flex items-center gap-3 px-3 py-2 text-sm"
                >
                    <svg class="h-4 w-4 shrink-0 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m2.25 0H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z" />
                    </svg>
                    <span class="flex-1 truncate text-gray-700">{{ file.original_name }}</span>
                    <span class="text-xs text-gray-400">#{{ file.order + 1 }}</span>
                    <button
                        class="ml-2 text-gray-400 hover:text-red-500"
                        :data-testid="'export-pro-file-delete-' + file.id"
                        @click="deleteFile(file.id)"
                    >
                        <svg class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
                        </svg>
                    </button>
                </div>
            </div>
            <p v-else class="text-sm text-gray-400">Noch keine Prefix-Dateien hochgeladen.</p>
        </div>

        <!-- Postfix section -->
        <div>
            <h4 class="mb-2 text-xs font-semibold uppercase tracking-wide text-gray-500">Postfix-Dateien</h4>
            <p class="mb-3 text-xs text-gray-400">Werden nach dem Gottesdienst angehängt.</p>

            <label
                class="mb-4 flex cursor-pointer flex-col items-center justify-center rounded-xl border-2 border-dashed p-6 transition-colors"
                :class="postfixDragActive
                    ? 'border-amber-400 bg-amber-50'
                    : 'border-gray-200 bg-gray-50 hover:border-amber-300 hover:bg-amber-50'"
                data-testid="export-postfix-dropzone"
                @dragover.prevent
                @dragenter.prevent="postfixDragActive = true"
                @dragleave.prevent="postfixDragActive = false"
                @drop.prevent="handlePostfixDrop"
            >
                <svg class="mb-2 h-8 w-8 text-gray-300" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5m-13.5-9L12 3m0 0l4.5 4.5M12 3v13.5" />
                </svg>
                <span class="text-sm text-gray-500">
                    {{ uploading ? 'Wird hochgeladen...' : '.pro / .probundle-Dateien auswählen oder hierher ziehen' }}
                </span>
                <span class="mt-1 text-xs text-gray-400">Mehrere Dateien möglich</span>
                <input
                    type="file"
                    class="hidden"
                    accept=".pro,.probundle"
                    multiple
                    :disabled="uploading"
                    data-testid="export-postfix-file-input"
                    @change="handlePostfixChange"
                />
            </label>

            <div v-if="postfixFiles.length > 0" class="divide-y divide-gray-100 rounded-lg border border-gray-100">
                <div
                    v-for="file in postfixFiles"
                    :key="file.id"
                    class="flex items-center gap-3 px-3 py-2 text-sm"
                >
                    <svg class="h-4 w-4 shrink-0 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m2.25 0H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z" />
                    </svg>
                    <span class="flex-1 truncate text-gray-700">{{ file.original_name }}</span>
                    <span class="text-xs text-gray-400">#{{ file.order + 1 }}</span>
                    <button
                        class="ml-2 text-gray-400 hover:text-red-500"
                        :data-testid="'export-pro-file-delete-' + file.id"
                        @click="deleteFile(file.id)"
                    >
                        <svg class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
                        </svg>
                    </button>
                </div>
            </div>
            <p v-else class="text-sm text-gray-400">Noch keine Postfix-Dateien hochgeladen.</p>
        </div>

        <!-- Keyword section -->
        <div>
            <h4 class="mb-2 text-xs font-semibold uppercase tracking-wide text-gray-500">Schlüsselwort-Dateien</h4>
            <p class="mb-3 text-xs text-gray-400">
                Werden beim Export hinter jedem Ablaufpunkt eingefügt, dessen Titel das Schlüsselwort enthält (Groß-/Kleinschreibung egal).
            </p>

            <div class="mb-4">
                <label class="mb-1 block text-xs font-medium text-gray-600">Schlüsselwort für den Upload</label>
                <input
                    v-model="keywordInput"
                    type="text"
                    class="w-full rounded-lg border-gray-200 text-sm shadow-sm focus:border-amber-400 focus:ring-amber-400"
                    placeholder="z. B. Abendmahl"
                    data-testid="export-keyword-upload-input"
                />
            </div>

            <label
                class="mb-4 flex cursor-pointer flex-col items-center justify-center rounded-xl border-2 border-dashed p-6 transition-colors"
                :class="keywordDragActive
                    ? 'border-amber-400 bg-amber-50'
                    : 'border-gray-200 bg-gray-50 hover:border-amber-300 hover:bg-amber-50'"
                data-testid="export-keyword-dropzone"
                @dragover.prevent
                @dragenter.prevent="keywordDragActive = true"
                @dragleave.prevent="keywordDragActive = false"
                @drop.prevent="handleKeywordDrop"
            >
                <svg class="mb-2 h-8 w-8 text-gray-300" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5m-13.5-9L12 3m0 0l4.5 4.5M12 3v13.5" />
                </svg>
                <span class="text-sm text-gray-500">
                    {{ uploading ? 'Wird hochgeladen...' : '.pro / .probundle-Dateien auswählen oder hierher ziehen' }}
                </span>
                <span class="mt-1 text-xs text-gray-400">Das Schlüsselwort oben wird allen hochgeladenen Dateien zugewiesen</span>
                <input
                    type="file"
                    class="hidden"
                    accept=".pro,.probundle"
                    multiple
                    :disabled="uploading"
                    data-testid="export-keyword-file-input"
                    @change="handleKeywordChange"
                />
            </label>

            <div v-if="keywordFiles.length > 0" class="divide-y divide-gray-100 rounded-lg border border-gray-100">
                <div
                    v-for="file in keywordFiles"
                    :key="file.id"
                    class="flex items-center gap-3 px-3 py-2 text-sm"
                >
                    <svg class="h-4 w-4 shrink-0 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m2.25 0H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z" />
                    </svg>
                    <span class="flex-1 truncate text-gray-700">{{ file.original_name }}</span>
                    <input
                        type="text"
                        class="w-40 rounded-lg border-gray-200 text-xs shadow-sm focus:border-amber-400 focus:ring-amber-400"
                        :value="file.keyword"
                        placeholder="Schlüsselwort"
                        :data-testid="'export-keyword-input-' + file.id"
                        @change="updateKeyword(file.id, $event.target.value)"
                        @blur="updateKeyword(file.id, $event.target.value)"
                    />
                    <button
                        class="ml-2 text-gray-400 hover:text-red-500"
                        :data-testid="'export-keyword-file-delete-' + file.id"
                        @click="deleteFile(file.id)"
                    >
                        <svg class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
                        </svg>
                    </button>
                </div>
            </div>
            <p v-else class="text-sm text-gray-400">Noch keine Schlüsselwort-Dateien hochgeladen.</p>
        </div>
    </div>
</template>
