<script lang="ts">
import { liveQuery } from 'dexie';
import { ArrowLeft, Pencil, Plus, Settings, Trash2 } from '@lucide/svelte';
import { events_func } from '$lib/ae_events/ae_events_functions';
import { ae_api } from '$lib/stores/ae_stores';
import { Modal } from 'flowbite-svelte';
import Comp_badge_template_form from './ae_comp__badge_template_form.svelte';

interface Props {
    data: any; // PageData from SvelteKit
}

let { data }: Props = $props();

let event_id = $derived(data.params.event_id);

let show_create_template_modal: boolean = $state(false);
let selected_template_id: string | null = $state(null);
let show_edit_template_modal: boolean = $state(false);

let lq__badge_templates = $derived(
    liveQuery(async () => {
        const result = await events_func.load_ae_obj_li__event_badge_template({
            api_cfg: $ae_api,
            event_id: event_id,
            log_lvl: 0
        });
        return result || [];
    })
);

function handle_create_success() {
    show_create_template_modal = false;
    // Trigger a refresh of the list (by updating a store or re-fetching)
    // For now, relying on liveQuery to react to DB changes
}

function handle_edit_success() {
    show_edit_template_modal = false;
    selected_template_id = null;
    // Trigger a refresh of the list
}

function handle_cancel() {
    show_create_template_modal = false;
    show_edit_template_modal = false;
    selected_template_id = null;
}

function edit_template(template_id: string) {
    selected_template_id = template_id;
    show_edit_template_modal = true;
}

async function delete_template(template_id: string) {
    if (
        confirm(
            'Are you sure you want to delete this badge template? This action cannot be undone.'
        )
    ) {
        try {
            await events_func.delete_ae_obj_id__event_badge_template({
                api_cfg: $ae_api,
                event_id: event_id,
                event_badge_template_id: template_id
            });
            // Rely on liveQuery to refresh list
        } catch (error) {
            console.error('Error deleting template:', error);
            alert('Failed to delete template.');
        }
    }
}
</script>

<svelte:head>
    <title>Badge Templates - Event {event_id}</title>
</svelte:head>

<section class="p-4">
    <header class="mb-4 flex items-center justify-between gap-4">
        <div class="flex items-center gap-2">
            <a href="/events/{event_id}/badges/config"
                class="btn btn-sm preset-tonal-surface"
                title="Back to Badges Config">
                <ArrowLeft size="1em" />
            </a>
            <Settings size="1.2em" class="text-primary-500" />
            <h1 class="text-xl font-bold">Badge Templates</h1>
        </div>
        <button
            type="button"
            class="btn btn-primary"
            onclick={() => (show_create_template_modal = true)}>
            <Plus size="1em" class="mr-2" /> Add New Template
        </button>
    </header>

    {#if $lq__badge_templates}
        {#if $lq__badge_templates.length > 0}
            <div class="card p-4">
                <ul class="list-group">
                    {#each $lq__badge_templates as template (template.event_badge_template_id)}
                        <li
                            class="list-group-item flex items-center justify-between">
                            <span>{template.name}</span>
                            <div>
                                <button
                                    type="button"
                                    class="btn btn-sm preset-filled-primary"
                                    onclick={() =>
                                        edit_template(
                                            template.event_badge_template_id
                                        )}>
                                    <Pencil size="1em" aria-hidden="true" /> Edit
                                </button>
                                <button
                                    type="button"
                                    class="btn btn-sm preset-filled-error ml-2"
                                    onclick={() =>
                                        delete_template(
                                            template.event_badge_template_id
                                        )}>
                                    <Trash2 size="1em" aria-hidden="true" /> Delete
                                </button>
                            </div>
                        </li>
                    {/each}
                </ul>
            </div>
        {:else}
            <p>
                No badge templates found for this event. Click "Add New
                Template" to create one.
            </p>
        {/if}
    {:else}
        <p>Loading badge templates...</p>
    {/if}
</section>

{#if show_create_template_modal}
    <Modal bind:open={show_create_template_modal}>
        <div class="card p-4">
            <Comp_badge_template_form
                {event_id}
                onsuccess={handle_create_success}
                oncancel={handle_cancel} />
        </div>
    </Modal>
{/if}

{#if show_edit_template_modal}
    <Modal bind:open={show_edit_template_modal}>
        <div class="card p-4">
            <Comp_badge_template_form
                {event_id}
                template_id={selected_template_id}
                onsuccess={handle_edit_success}
                oncancel={handle_cancel} />
        </div>
    </Modal>
{/if}
