<script lang="ts">
    import { untrack } from 'svelte';
    import type { key_val } from '$lib/stores/ae_stores';
    import { events_func } from '$lib/ae_events_functions';
    import { ae_api } from '$lib/stores/ae_stores';

    interface Props {
        event_id: string;
        template_id?: string | null; // Null for creation, string for editing
        onsuccess?: (result: any) => void;
        onerror?: (error: any) => void;
        oncancel?: () => void;
    }

    let {
        event_id,
        template_id = null,
        onsuccess,
        onerror,
        oncancel
    }: Props = $props();

    function prevent_default(fn: () => void) {
        return function (event: Event) {
            event.preventDefault();
            fn();
        };
    }

    // Form fields (Runes)
    let name = $state('');
    let header_path = $state('');
    let logo_path = $state('');
    let header_row_1 = $state('');
    let header_row_2 = $state('');
    let secondary_header_path = $state('');
    let footer_text = $state('');
    let show_qr_front = $state(true);
    let show_qr_back = $state(true);
    let wireless_ssid = $state('');
    let wireless_password = $state('');
    let ticket_1_text = $state('');
    let ticket_2_text = $state('');
    let ticket_3_text = $state('');

    let submit_status = $state('idle'); // idle, loading, success, error

    // Load template data if in edit mode
    $effect(() => {
        if (template_id) {
            untrack(() => {
                load_template(template_id);
            });
        }
    });

    async function load_template(id: string) {
        submit_status = 'loading';
        try {
            const template_obj =
                await events_func.load_ae_obj_id__event_badge_template({
                    api_cfg: $ae_api,
                    event_badge_template_id: id
                });
            if (template_obj) {
                name = template_obj.name || '';
                header_path = template_obj.header_path || '';
                logo_path = template_obj.logo_path || '';
                header_row_1 = template_obj.header_row_1 || '';
                header_row_2 = template_obj.header_row_2 || '';
                secondary_header_path =
                    template_obj.secondary_header_path || '';
                footer_text = template_obj.footer_text || '';
                show_qr_front = template_obj.show_qr_front ?? true;
                show_qr_back = template_obj.show_qr_back ?? true;
                wireless_ssid = template_obj.wireless_ssid || '';
                wireless_password = template_obj.wireless_password || '';
                ticket_1_text = template_obj.ticket_1_text || '';
                ticket_2_text = template_obj.ticket_2_text || '';
                ticket_3_text = template_obj.ticket_3_text || '';
                submit_status = 'idle';
            } else {
                submit_status = 'error';
                console.error('Template not found for editing.');
            }
        } catch (error) {
            submit_status = 'error';
            console.error('Error loading template for editing:', error);
        }
    }

    async function handle_submit() {
        submit_status = 'loading';
        const data_to_save: key_val = {
            name,
            header_path,
            logo_path,
            header_row_1,
            header_row_2,
            secondary_header_path,
            footer_text,
            show_qr_front,
            show_qr_back,
            wireless_ssid,
            wireless_password,
            ticket_1_text,
            ticket_2_text,
            ticket_3_text
        };

        try {
            let result;
            if (template_id) {
                result = await events_func.update_ae_obj__event_badge_template({
                    api_cfg: $ae_api,
                    event_badge_template_id: template_id,
                    data_kv: data_to_save
                });
            } else {
                result = await events_func.create_ae_obj__event_badge_template({
                    api_cfg: $ae_api,
                    event_id: event_id,
                    data_kv: data_to_save
                });
            }

            if (result) {
                submit_status = 'success';
                if (onsuccess) onsuccess(result);
            } else {
                submit_status = 'error';
                if (onerror) onerror('Failed to save template');
            }
        } catch (error) {
            submit_status = 'error';
            console.error('Error saving template:', error);
            if (onerror) onerror(error);
        }
    }

    function handle_cancel() {
        if (oncancel) oncancel();
    }
</script>

<form onsubmit={prevent_default(handle_submit)} class="p-4 space-y-4">
    <h3 class="h3">{template_id ? 'Edit' : 'Create New'} Badge Template</h3>

    <label class="label">
        <span>Template Name</span>
        <input type="text" bind:value={name} class="input" required />
    </label>

    <label class="label">
        <span>Header Path (URL)</span>
        <input type="text" bind:value={header_path} class="input" />
    </label>
    <label class="label">
        <span>Logo Path (URL, if no Header Path)</span>
        <input type="text" bind:value={logo_path} class="input" />
    </label>
    <label class="label">
        <span>Header Row 1 Text (HTML allowed)</span>
        <textarea bind:value={header_row_1} class="textarea" rows="2"
        ></textarea>
    </label>
    <label class="label">
        <span>Header Row 2 Text (HTML allowed)</span>
        <textarea bind:value={header_row_2} class="textarea" rows="2"
        ></textarea>
    </label>
    <label class="label">
        <span>Secondary Header Path (URL, back of badge)</span>
        <input type="text" bind:value={secondary_header_path} class="input" />
    </label>

    <label class="label">
        <span>Footer Text (HTML allowed)</span>
        <textarea bind:value={footer_text} class="textarea" rows="2"></textarea>
    </label>

    <label class="label flex items-center gap-2">
        <input type="checkbox" bind:checked={show_qr_front} class="checkbox" />
        <span>Show QR Code on Front</span>
    </label>
    <label class="label flex items-center gap-2">
        <input type="checkbox" bind:checked={show_qr_back} class="checkbox" />
        <span>Show QR Code on Back</span>
    </label>

    <label class="label">
        <span>Wireless SSID</span>
        <input type="text" bind:value={wireless_ssid} class="input" />
    </label>
    <label class="label">
        <span>Wireless Password</span>
        <input type="text" bind:value={wireless_password} class="input" />
    </label>

    <label class="label">
        <span>Ticket 1 Text (HTML allowed)</span>
        <textarea bind:value={ticket_1_text} class="textarea" rows="2"
        ></textarea>
    </label>
    <label class="label">
        <span>Ticket 2 Text (HTML allowed)</span>
        <textarea bind:value={ticket_2_text} class="textarea" rows="2"
        ></textarea>
    </label>
    <label class="label">
        <span>Ticket 3 Text (HTML allowed)</span>
        <textarea bind:value={ticket_3_text} class="textarea" rows="2"
        ></textarea>
    </label>

    <div class="flex justify-end gap-2">
        <button
            type="button"
            class="btn variant-filled-tertiary"
            onclick={handle_cancel}
            disabled={submit_status === 'loading'}>Cancel</button
        >
        <button
            type="submit"
            class="btn variant-filled-primary"
            disabled={submit_status === 'loading'}
        >
            {#if submit_status === 'loading'}
                <span class="fas fa-spinner fa-spin mr-2"></span>
            {/if}
            {template_id ? 'Save Changes' : 'Create Template'}
        </button>
    </div>
</form>

{#if submit_status === 'success'}
    <p class="text-green-500">Template saved successfully!</p>
{:else if submit_status === 'error'}
    <p class="text-red-500">Error saving template. Please try again.</p>
{/if}
