---
import yaml from "js-yaml";
import textConfig from "../../config/text.yml?raw";

// Parse YAML configuration
const text = yaml.load(textConfig) as any;
const { editor_title, form } = text.ui.tables.events;
---

<!-- Event Editor Dialog -->
<dialog id="eventEditor" class="modal">
    <div class="modal-box w-11/12 max-w-4xl">
        <h3 class="font-bold text-lg mb-6">{editor_title}</h3>
        <form
            class="space-y-6"
            id="eventForm"
            novalidate
            onsubmit="event.preventDefault();"
        >
            <!-- Basic Info Section -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div class="form-control">
                    <label class="label" for="editorEventId">
                        <span class="label-text">{form.event_id.label}</span>
                    </label>
                    <input
                        type="text"
                        id="editorEventId"
                        class="input input-bordered w-full"
                        placeholder={form.event_id.placeholder}
                        pattern="[A-Za-z0-9_\-]+"
                        minlength="3"
                        maxlength="50"
                        required
                    />
                    <label class="label">
                        <span
                            class="label-text-alt text-error hidden"
                            id="eventIdError">This field is required</span
                        >
                    </label>
                </div>

                <div class="form-control">
                    <label class="label" for="editorEventCode">
                        <span class="label-text">{form.event_code.label}</span>
                    </label>
                    <input
                        type="text"
                        id="editorEventCode"
                        class="input input-bordered w-full"
                        placeholder={form.event_code.placeholder}
                        pattern="[A-Za-z0-9_\-]+"
                        minlength="3"
                        maxlength="20"
                        required
                    />
                    <label class="label">
                        <span
                            class="label-text-alt text-error hidden"
                            id="eventCodeError">This field is required</span
                        >
                    </label>
                </div>
            </div>

            <div class="form-control">
                <label class="label" for="editorEventName">
                    <span class="label-text">{form.event_name.label}</span>
                </label>
                <input
                    type="text"
                    id="editorEventName"
                    class="input input-bordered w-full"
                    placeholder={form.event_name.placeholder}
                    minlength="3"
                    maxlength="100"
                    required
                />
                <label class="label">
                    <span
                        class="label-text-alt text-error hidden"
                        id="eventNameError">This field is required</span
                    >
                </label>
            </div>

            <!-- Date/Time Section -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div class="space-y-4">
                    <h4 class="font-medium text-sm opacity-70">
                        Start Date/Time
                    </h4>
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <div class="form-control">
                            <label class="label" for="editorStartDate">
                                <span class="label-text"
                                    >{form.start_date.date_label}</span
                                >
                            </label>
                            <input
                                type="date"
                                id="editorStartDate"
                                class="input input-bordered w-full"
                                placeholder={form.start_date.date_placeholder}
                                required
                            />
                            <label class="label">
                                <span
                                    class="label-text-alt text-error hidden"
                                    id="startDateError"
                                    >This field is required</span
                                >
                            </label>
                        </div>
                        <div class="form-control">
                            <label class="label" for="editorStartTime">
                                <span class="label-text"
                                    >{form.start_date.time_label}</span
                                >
                            </label>
                            <input
                                type="time"
                                id="editorStartTime"
                                class="input input-bordered w-full"
                                placeholder={form.start_date.time_placeholder}
                                required
                            />
                            <label class="label">
                                <span
                                    class="label-text-alt text-error hidden"
                                    id="startTimeError"
                                    >This field is required</span
                                >
                            </label>
                        </div>
                    </div>
                </div>

                <div class="space-y-4">
                    <h4 class="font-medium text-sm opacity-70">
                        End Date/Time
                    </h4>
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <div class="form-control">
                            <label class="label" for="editorEndDate">
                                <span class="label-text"
                                    >{form.end_date.date_label}</span
                                >
                            </label>
                            <input
                                type="date"
                                id="editorEndDate"
                                class="input input-bordered w-full"
                                placeholder={form.end_date.date_placeholder}
                                required
                            />
                            <label class="label">
                                <span
                                    class="label-text-alt text-error hidden"
                                    id="endDateError"
                                    >This field is required</span
                                >
                            </label>
                        </div>
                        <div class="form-control">
                            <label class="label" for="editorEndTime">
                                <span class="label-text"
                                    >{form.end_date.time_label}</span
                                >
                            </label>
                            <input
                                type="time"
                                id="editorEndTime"
                                class="input input-bordered w-full"
                                placeholder={form.end_date.time_placeholder}
                                required
                            />
                            <label class="label">
                                <span
                                    class="label-text-alt text-error hidden"
                                    id="endTimeError"
                                    >This field is required</span
                                >
                            </label>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Additional Info Section -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div class="form-control">
                    <label class="label" for="editorPointsToReward">
                        <span class="label-text"
                            >{form.points_to_reward.label}</span
                        >
                    </label>
                    <input
                        type="number"
                        id="editorPointsToReward"
                        class="input input-bordered w-full"
                        placeholder={form.points_to_reward.placeholder}
                        min="0"
                        max="1000"
                        required
                    />
                    <label class="label">
                        <span
                            class="label-text-alt text-error hidden"
                            id="pointsError">This field is required</span
                        >
                    </label>
                </div>

                <div class="form-control">
                    <label class="label" for="editorLocation">
                        <span class="label-text">{form.location.label}</span>
                    </label>
                    <input
                        type="text"
                        id="editorLocation"
                        class="input input-bordered w-full"
                        placeholder={form.location.placeholder}
                        maxlength="200"
                    />
                    <label class="label">
                        <span
                            class="label-text-alt text-error hidden"
                            id="locationError"></span>
                    </label>
                </div>
            </div>

            <!-- Files Section -->
            <div class="form-control">
                <label class="label" for="editorFiles">
                    <span class="label-text">{form.files.label}</span>
                </label>
                <input
                    type="file"
                    id="editorFiles"
                    class="file-input file-input-bordered w-full"
                    multiple
                    accept=".pdf,.doc,.docx,.txt,.jpg,.jpeg,.png"
                />
                <div id="uploadProgress" class="w-full mt-2 hidden">
                    <div class="flex justify-between mb-1 text-xs opacity-70">
                        <span>Uploading files...</span>
                        <span id="uploadProgressText">0%</span>
                    </div>
                    <progress
                        id="uploadProgressBar"
                        class="progress progress-primary w-full"
                        value="0"
                        max="100"></progress>
                </div>
                <div id="currentFiles" class="mt-4 space-y-2"></div>
                <label class="label">
                    <span class="label-text-alt opacity-70"
                        >{form.files.help_text}</span
                    >
                </label>
            </div>

            <div class="modal-action flex-wrap gap-2">
                <button
                    type="button"
                    class="btn btn-ghost order-1 sm:order-none"
                    onclick="eventEditor.close()"
                >
                    {form.buttons.cancel}
                </button>
                <button
                    type="submit"
                    id="saveEventButton"
                    class="btn btn-primary flex-1 sm:flex-none"
                >
                    {form.buttons.save}
                </button>
            </div>
        </form>
    </div>
    <form method="dialog" class="modal-backdrop">
        <button>close</button>
    </form>
</dialog>

<script>
    import { Authentication } from "../pocketbase/Authentication";
    import { Get } from "../pocketbase/Get";
    import { Update } from "../pocketbase/Update";
    import { SendLog } from "../pocketbase/SendLog";
    import { FileManager } from "../pocketbase/FileManager";

    const auth = Authentication.getInstance();
    const get = Get.getInstance();
    const update = Update.getInstance();
    const logger = SendLog.getInstance();
    const fileManager = FileManager.getInstance();

    // Handle file uploads
    if (editorFiles) {
        editorFiles.addEventListener("change", async (e) => {
            const files = Array.from(
                (e.target as HTMLInputElement).files || []
            );
            if (files.length > 0) {
                const uploadProgress =
                    document.getElementById("uploadProgress");
                const uploadProgressBar = document.getElementById(
                    "uploadProgressBar"
                ) as HTMLProgressElement;
                const uploadProgressText =
                    document.getElementById("uploadProgressText");

                if (uploadProgress) uploadProgress.classList.remove("hidden");

                try {
                    const user = auth.getCurrentUser();
                    if (!user) throw new Error("User not authenticated");

                    // Upload files
                    await fileManager.uploadFiles(
                        "events",
                        eventId,
                        "files",
                        files
                    );

                    // Update progress
                    if (uploadProgressBar) uploadProgressBar.value = 100;
                    if (uploadProgressText)
                        uploadProgressText.textContent = "100%";

                    // Log successful upload
                    await logger.send(
                        "update",
                        "event files",
                        `Successfully uploaded ${files.length} files to event ${eventId}`
                    );

                    // Refresh file list
                    await loadCurrentFiles();
                } catch (err) {
                    console.error("File upload error:", err);

                    // Log upload error
                    await logger.send(
                        "error",
                        "event files",
                        `Failed to upload files to event ${eventId}. Error: ${err instanceof Error ? err.message : "Unknown error"}`
                    );
                } finally {
                    if (uploadProgress) {
                        setTimeout(() => {
                            uploadProgress.classList.add("hidden");
                            if (uploadProgressBar) uploadProgressBar.value = 0;
                            if (uploadProgressText)
                                uploadProgressText.textContent = "0%";
                        }, 2000);
                    }
                }
            }
        });
    }

    // Function to load current files
    async function loadCurrentFiles() {
        const currentFiles = document.getElementById("currentFiles");
        if (!currentFiles || !eventId) return;

        try {
            const event = await get.getOne("events", eventId);
            if (!event.files || !Array.isArray(event.files)) return;

            currentFiles.innerHTML = event.files
                .map((filename) => {
                    const fileUrl = fileManager.getFileUrl(
                        "events",
                        eventId,
                        filename
                    );
                    return `
                    <div class="flex justify-between items-center p-2 bg-base-200 rounded-lg">
                        <span class="truncate flex-1">${filename}</span>
                        <div class="flex gap-2">
                            <a href="${fileUrl}" target="_blank" class="btn btn-sm btn-ghost">
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
                                </svg>
                            </a>
                            <button class="btn btn-sm btn-ghost text-error" onclick="deleteFile('${filename}')">
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                </svg>
                            </button>
                        </div>
                    </div>
                `;
                })
                .join("");
        } catch (err) {
            console.error("Failed to load current files:", err);
        }
    }

    // Function to delete a file
    async function deleteFile(filename: string) {
        if (!eventId) return;

        try {
            const event = await get.getOne("events", eventId);
            if (!event.files || !Array.isArray(event.files)) return;

            // Remove the file from the array
            const updatedFiles = event.files.filter((f) => f !== filename);
            await update.updateField("events", eventId, "files", updatedFiles);

            // Log successful deletion
            await logger.send(
                "delete",
                "event files",
                `Successfully deleted file ${filename} from event ${eventId}`
            );

            // Refresh file list
            await loadCurrentFiles();
        } catch (err) {
            console.error("Failed to delete file:", err);

            // Log deletion error
            await logger.send(
                "error",
                "event files",
                `Failed to delete file ${filename} from event ${eventId}. Error: ${err instanceof Error ? err.message : "Unknown error"}`
            );
        }
    }

    // Make deleteFile available globally
    window.deleteFile = deleteFile;

    // Load current files on page load
    loadCurrentFiles();
</script>
