<script lang="ts">
    import { liveQuery } from 'dexie';
    import { events_func } from '$lib/ae_events_functions';
    import { ae_api } from '$lib/stores/ae_stores';
    import { events_slct } from '$lib/stores/ae_events_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: string = 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_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">
    <h1 class="h1">Badge Templates</h1>

    <div class="my-4 flex justify-end">
        <button class="btn btn-primary" onclick={() => (show_create_template_modal = true)}>
            <span class="fas fa-plus mr-2"></span> Add New Template
        </button>
    </div>

    {#await lq__badge_templates}
        <p>Loading badge templates...</p>
    {:then templates}
        {#if templates.length > 0}
            <div class="card p-4">
                <ul class="list-group">
                    {#each templates as template (template.event_badge_template_id_random)}
                        <li class="list-group-item flex justify-between items-center">
                            <span>{template.name}</span>
                            <div>
                                <button
                                    class="btn btn-sm variant-filled-primary"
                                    onclick={() =>
                                        edit_template(template.event_badge_template_id_random)}
                                >
                                    <span class="fas fa-edit"></span> Edit
                                </button>
                                <button
                                    class="btn btn-sm variant-filled-error ml-2"
                                    onclick={() =>
                                        delete_template(template.event_badge_template_id_random)}
                                >
                                    <span class="fas fa-trash"></span> 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}
    {:catch error}
        <p class="text-error-500">Error loading templates: {error.message}</p>
    {/await}
</section>

{#if show_create_template_modal}
    <Modal bind:show={show_create_template_modal}>
        <div class="card p-4">
            <Comp_badge_template_form
                {event_id}
                on:success={handle_create_success}
                on:cancel={handle_cancel}
            />
        </div>
    </Modal>
{/if}

{#if show_edit_template_modal}
    <Modal bind:show={show_edit_template_modal}>
        <div class="card p-4">
            <Comp_badge_template_form
                {event_id}
                template_id={selected_template_id}
                on:success={handle_edit_success}
                on:cancel={handle_cancel}
            />
        </div>
    </Modal>
{/if}
