<script lang="ts">
/**
 * src/routes/events/[event_id]/(leads)/leads/exhibit/[exhibit_id]/ae_comp__exhibit_license_list.svelte
 * Exhibitor License Management - Handles parsing and editing event_exhibit.license_li_json
 */
import { untrack } from 'svelte';
import { ae_api } from '$lib/stores/ae_stores';
import { events_func } from '$lib/ae_events/ae_events_functions';
import {
    Key,
    LoaderCircle,
    Mail,
    Plus,
    Save,
    Trash2,
    User,
    Users
} from '@lucide/svelte';
interface Props {
    exhibit_id: string;
    event_id: string;
    license_li_json?: string; // Raw JSON string from DB
    license_max?: number;
}

let {
    exhibit_id,
    event_id,
    license_li_json = '[]',
    license_max = 0
}: Props = $props();

// Local state for the parsed list
let local_license_li: any[] = $state([]);
let is_saving = $state(false);

// Parse JSON into local state
$effect(() => {
    try {
        const raw = license_li_json;
        if (!raw) {
            untrack(() => (local_license_li = []));
            return;
        }

        // Handle both string and pre-parsed array/object formats
        let parsed = [];
        if (Array.isArray(raw)) {
            parsed = raw;
        } else if (typeof raw === 'string') {
            parsed = JSON.parse(raw || '[]');
        }

        untrack(() => {
            local_license_li = Array.isArray(parsed) ? parsed : [];
        });
    } catch (e) {
        console.error('Failed to parse license_li_json', e);
        untrack(() => {
            local_license_li = [];
        });
    }
});

async function save_licenses() {
    if (!exhibit_id) return;
    is_saving = true;
    try {
        const json_str = JSON.stringify(local_license_li);
        await events_func.update_ae_obj__exhibit({
            api_cfg: $ae_api,
            event_id: event_id,
            exhibit_id: exhibit_id,
            data_kv: {
                license_li_json: json_str
            }
        });
    } catch (e) {
        console.error('Failed to save licenses', e);
    } finally {
        is_saving = false;
    }
}

function add_license() {
    if (local_license_li.length >= (license_max || 1)) {
        alert(`Maximum licenses (${license_max}) reached.`);
        return;
    }
    local_license_li.push({
        full_name: '',
        email: '',
        passcode: Math.random().toString(36).substring(2, 8).toUpperCase()
    });
}

function remove_license(index: number) {
    if (
        confirm('Remove this license? The user will lose access immediately.')
    ) {
        local_license_li.splice(index, 1);
    }
}
</script>

<div class="exhibit-license-list space-y-4">
    <div class="flex items-center justify-between">
        <h3 class="text-sm font-bold tracking-widest uppercase opacity-50">
            Assigned Licenses
        </h3>
        <span class="bg-surface-500/10 rounded px-2 py-1 font-mono text-xs">
            {local_license_li.length} / {license_max || 1}
        </span>
    </div>

    <div class="space-y-3">
        {#each local_license_li as license, i (i)}
            <div
                class="card preset-tonal-surface border-surface-500/10 group animate-in fade-in slide-in-from-right-2 relative space-y-3 border p-4">
                <button
                    class="text-error-500 absolute top-2 right-2 p-2 opacity-0 transition-opacity group-hover:opacity-100"
                    onclick={() => remove_license(i)}
                    title="Remove License">
                    <Trash2 size="1.2em" />
                </button>

                <!-- Name -->
                <div class="flex items-center gap-3">
                    <User size="1.2em" class="opacity-30" />
                    <input
                        type="text"
                        bind:value={license.full_name}
                        placeholder="Full Name"
                        class="border-surface-500/20 focus:border-primary-500 flex-1 border-b bg-transparent text-sm font-bold outline-none" />
                </div>

                <!-- Email -->
                <div class="flex items-center gap-3">
                    <Mail size="1.2em" class="opacity-30" />
                    <input
                        type="email"
                        bind:value={license.email}
                        placeholder="email@example.com"
                        class="border-surface-500/20 focus:border-primary-500 flex-1 border-b bg-transparent text-sm outline-none" />
                </div>

                <!-- Passcode -->
                <div class="flex items-center gap-3">
                    <Key size="1.2em" class="opacity-30" />
                    <input
                        type="text"
                        bind:value={license.passcode}
                        placeholder="PASSCODE"
                        class="border-surface-500/20 focus:border-primary-500 w-32 border-b bg-transparent font-mono text-sm font-bold outline-none" />
                </div>
            </div>
        {/each}

        {#if local_license_li.length === 0}
            <div
                class="border-surface-500/20 rounded-xl border-2 border-dashed p-8 text-center opacity-30">
                <Users size="2em" class="mx-auto mb-2" />
                <p class="text-sm italic">No licenses assigned yet.</p>
            </div>
        {/if}
    </div>

    <div class="flex gap-2 pt-2">
        <button
            class="btn btn-sm preset-filled-secondary flex-1"
            onclick={add_license}
            disabled={local_license_li.length >= (license_max || 1)}>
            <Plus size="1.2em" class="mr-2" /> Add Leads Licensee
        </button>

        <button
            class="btn btn-sm preset-filled-primary flex-1"
            onclick={save_licenses}
            disabled={is_saving}>
            {#if is_saving}
                <LoaderCircle size="1.2em" class="mr-2 animate-spin" />
            {:else}
                <Save size="1.2em" class="mr-2" />
            {/if}
            Save Changes
        </button>
    </div>
</div>
