<script lang="ts">
    // import { createEventDispatcher } 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;
        onsuccess?: () => void;
        oncancel?: () => void;
        onerror?: (error: any) => void;
    }

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

    // const dispatch = createEventDispatcher();

    let file_input: HTMLInputElement | undefined = $state();
    let selected_file: File | null = $state(null);
    let upload_status: string = $state('idle'); // idle, loading, processing, success, error
    let upload_message: string = $state('');
    let processed_badges_count: number = $state(0);
    let total_badges_in_file: number = $state(0);

    // A very basic CSV parser that assumes the first row is headers
    function parse_csv(text: string): key_val[] {
        const lines = text.trim().split('\n');
        if (lines.length === 0) return [];

        const headers = lines[0].split(',').map((h) => h.trim());
        const data = lines.slice(1).map((line) => {
            const values = line.split(',').map((v) => v.trim());
            const obj: key_val = {};
            headers.forEach((header, index) => {
                obj[header] = values[index];
            });
            return obj;
        });
        return data;
    }

    async function handle_file_change(event: Event) {
        const target = event.target as HTMLInputElement;
        if (target.files && target.files.length > 0) {
            selected_file = target.files[0];
            upload_message = `Selected file: ${selected_file.name}`;
        } else {
            selected_file = null;
            upload_message = '';
        }
    }

    async function handle_upload(event: Event) {
        event.preventDefault();
        if (!selected_file) {
            upload_message = 'Please select a file first.';
            upload_status = 'error';
            return;
        }

        upload_status = 'loading';
        upload_message = 'Reading file...';

        const reader = new FileReader();
        reader.onload = async (e) => {
            try {
                upload_status = 'processing';
                upload_message = 'Processing file content...';
                processed_badges_count = 0;

                const text = e.target?.result as string;
                const badge_data_li = parse_csv(text);
                total_badges_in_file = badge_data_li.length;

                for (const data_kv of badge_data_li) {
                    // Simple mapping, customize as needed
                    const badge_payload: key_val = {
                        full_name_override:
                            data_kv.full_name || data_kv.name || null,
                        professional_title_override:
                            data_kv.professional_title || null,
                        affiliations_override:
                            data_kv.affiliations || data_kv.company || null,
                        location_override: data_kv.location || null,
                        email: data_kv.email || null,
                        allow_tracking:
                            data_kv.allow_tracking === 'true' ||
                            data_kv.allow_tracking === '1' ||
                            false,
                        badge_type_code: data_kv.badge_type_code || 'guest' // Default to 'guest' if not provided
                    };

                    await events_func.create_ae_obj__event_badge({
                        api_cfg: $ae_api,
                        event_id: event_id,
                        data_kv: badge_payload
                    });
                    processed_badges_count++;
                }

                upload_status = 'success';
                upload_message = `Successfully uploaded ${processed_badges_count} out of ${total_badges_in_file} badges.`;
                // dispatch('success');
                if (onsuccess) onsuccess();
            } catch (error: any) {
                upload_status = 'error';
                upload_message = `Error processing file: ${error?.message || 'Unknown error'}`;
                console.error('Error during file upload:', error);
                // dispatch('error', error);
                if (onerror) onerror(error);
            }
        };
        reader.onerror = (e) => {
            upload_status = 'error';
            upload_message = `Error reading file: ${reader.error?.message}`;
            console.error('FileReader error:', reader.error);
            // dispatch('error', reader.error);
            if (onerror) onerror(reader.error);
        };
        reader.readAsText(selected_file);
    }

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

<form onsubmit={handle_upload} class="p-4 space-y-4">
    <h3 class="h3">Upload Badge List (CSV)</h3>
    <p>
        Upload a CSV file containing badge data. The first row should be
        headers.
    </p>
    <p>
        Supported headers (case-sensitive): <code>full_name</code>,
        <code>name</code>,
        <code>professional_title</code>, <code>affiliations</code>,
        <code>company</code>,
        <code>location</code>, <code>email</code>, <code>allow_tracking</code>
        (true/false or 1/0),
        <code>badge_type_code</code>.
    </p>

    <label class="label">
        <span>Select CSV File</span>
        <input
            type="file"
            accept=".csv"
            bind:this={file_input}
            onchange={handle_file_change}
            class="input"
        />
    </label>

    {#if selected_file}
        <p>File: {selected_file.name} ({selected_file.size} bytes)</p>
    {/if}

    {#if upload_status !== 'idle'}
        <div
            class="alert variant-soft-{upload_status === 'error'
                ? 'error'
                : 'info'}"
        >
            <p>{upload_message}</p>
            {#if upload_status === 'processing' || upload_status === 'loading'}
                <progress
                    class="progress"
                    value={processed_badges_count}
                    max={total_badges_in_file}
                ></progress>
                <p>
                    Processed: {processed_badges_count} / {total_badges_in_file}
                </p>
            {/if}
        </div>
    {/if}

    <div class="flex justify-end gap-2">
        <button
            type="button"
            class="btn variant-filled-tertiary"
            onclick={handle_cancel}
            disabled={upload_status === 'loading' ||
                upload_status === 'processing'}>Cancel</button
        >
        <button
            type="submit"
            class="btn variant-filled-primary"
            disabled={!selected_file ||
                upload_status === 'loading' ||
                upload_status === 'processing'}
        >
            {#if upload_status === 'loading' || upload_status === 'processing'}
                <span class="fas fa-spinner fa-spin mr-2"></span>
            {/if}
            Upload Badges
        </button>
    </div>
</form>
