<script lang="ts">
    // console.log(`ae_core root +page.svelte data:`, data);

    // import { onMount } from 'svelte';
    import { goto, invalidate, pushState, replaceState } from '$app/navigation';

    import type { key_val } from '$lib/stores/ae_stores';
    // import { ae_util } from '$lib/ae_utils/ae_utils';
    // import { api } from '$lib/api';
    // import Element_ae_crud from '$lib/element_ae_crud.svelte';
    // import Element_data_store from '$lib/element_data_store_v2.svelte';
    import Comp_person_obj_tbl from './ae_comp__person_obj_tbl.svelte';

    // import { liveQuery } from "dexie";
    import { core_func } from '$lib/ae_core/ae_core_functions';
    import { Building, Globe, Users, ShieldCheck, List, Plus } from 'lucide-svelte';
    // import { db_core } from "$lib/db_core";
    // import { db_events } from "$lib/db_events";
    import {
        ae_snip,
        ae_loc,
        ae_sess,
        ae_api,
        ae_trig,
        slct,
        slct_trigger
    } from '$lib/stores/ae_stores';
    interface Props {
        /** @type {import('./$types').PageData} */
        data: any;
    }

    let { data }: Props = $props();
    // import { events_loc, events_sess, events_slct, events_trigger } from '$lib/stores/ae_events_stores';
    // import { events_func } from '$lib/ae_events_functions';

    // Quickly save the data passed from the parent(s) to the Svelte stores, localStorage, and other.
    $slct.account_id = data.account_id;
    console.log(`$slct.account_id = `, $slct.account_id);
    let ae_acct = data[$slct.account_id];
    console.log(`ae_acct = `, ae_acct);

    let person_id_random_li: string[] = $state([]);

    // let load_obj_li_results: Promise<any>|key_val;
    // let search_submit_results: Promise<any>|key_val;
</script>

<section class="ae_core md:container mx-auto p-4 space-y-6">
    <header class="flex justify-between items-center border-b border-surface-500/30 pb-4">
        <h2 class="h2">Æ Core Management</h2>
        <div class="text-right">
            <p class="text-sm opacity-60">Active Account</p>
            <p class="font-bold">{$ae_loc.account_name ?? 'Loading...'}</p>
        </div>
    </header>

    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        <!-- Account Management Card -->
        <div class="card p-4 space-y-4 variant-soft-primary">
            <div class="flex items-center gap-2">
                <Building size={20} />
                <h3 class="h4">Accounts</h3>
            </div>
            <p class="text-sm opacity-80 text-balance">Manage client accounts and high-level system settings.</p>
            <button class="btn variant-filled-primary w-full" onclick={() => goto('/core/accounts')}>
                Manage Accounts
            </button>
        </div>

        <!-- Site Management Card -->
        <div class="card p-4 space-y-4 variant-soft-secondary">
            <div class="flex items-center gap-2">
                <Globe size={20} />
                <h3 class="h4">Sites</h3>
            </div>
            <p class="text-sm opacity-80 text-balance">Configure sites and domains associated with the active account.</p>
            <button class="btn variant-filled-secondary w-full" onclick={() => goto('/core/sites')}>
                Manage Sites
            </button>
        </div>

        <!-- User Management Card -->
        <div class="card p-4 space-y-4 variant-soft-error">
            <div class="flex items-center gap-2">
                <ShieldCheck size={20} />
                <h3 class="h4">Users</h3>
            </div>
            <p class="text-sm opacity-80 text-balance">Manage system access, permissions, and user credentials.</p>
            <button class="btn variant-filled-error w-full" onclick={() => goto('/core/users')}>
                Manage Users
            </button>
        </div>

        <!-- Person Management Card -->
        <div class="card p-4 space-y-4 variant-soft-warning">
            <div class="flex items-center gap-2">
                <Users size={20} />
                <h3 class="h4">People</h3>
            </div>
            <p class="text-sm opacity-80 text-balance">View and manage person records and their associated user accounts.</p>
            <div class="flex gap-2">
                <button
                    type="button"
                    onclick={() => {
                        let person_results = core_func
                            .load_ae_obj_li__person({
                                api_cfg: $ae_api,
                                for_obj_type: 'account',
                                for_obj_id: $slct.account_id,
                                limit: $ae_loc.person.qry_limit__people,
                                log_lvl: 1
                            })
                            .then(function (load_results) {
                                if (load_results) {
                                    $slct.person_id_random_li = load_results;
                                    person_id_random_li = load_results.map((p: any) => p.person_id_random);
                                }
                                return load_results;
                            })
                            .finally(() => {
                                $ae_sess.person.show_report__person_li = true;
                            });
                    }}
                    class="btn variant-filled-warning flex-1"
                >
                    List People
                </button>
                <button
                    type="button"
                    onclick={async () => {
                        if (!confirm(`Add a new person to ${$ae_loc.account_name}?`)) return;
                        let person_data = {
                            account_id_random: $slct.account_id,
                            source_code: 'manual:SK-core',
                            given_name: 'New',
                            family_name: 'Person',
                            enable: true
                        };
                        let new_person_obj = await core_func.create_ae_obj__person({
                            api_cfg: $ae_api,
                            data_kv: person_data,
                            log_lvl: 1
                        });
                        if (new_person_obj && confirm(`Person created. View details?`)) {
                            goto(`/core/person/${new_person_obj.person_id_random}`);
                        }
                    }}
                    class="btn variant-filled-warning btn-icon"
                    class:hidden={!$ae_loc.edit_mode}
                >
                    <Plus size={16} />
                </button>
            </div>
        </div>

        <!-- Lookups Card -->
        <div class="card p-4 space-y-4 variant-soft-surface">
            <div class="flex items-center gap-2">
                <List size={20} />
                <h3 class="h4">Lookups</h3>
            </div>
            <p class="text-sm opacity-80 text-balance">View system lookup tables (countries, time zones, etc).</p>
            <button class="btn variant-filled-surface w-full" onclick={() => goto('/core/lookups')}>
                View Lookups
            </button>
        </div>
    </div>


    <!-- Show people for this account -->
    {#if $ae_sess.person.show_report__person_li && person_id_random_li?.length > 0}
        <h3 class="h4 text-center">Person Records</h3>

        <label class="text-sm" for="qry_limit__people"
            >Max results:

            <select
                id="qry_limit__people"
                bind:value={$ae_loc.person.qry_limit__people}
                onchange={() => {
                    core_func
                        .load_ae_obj_li__person({
                            api_cfg: $ae_api,
                            for_obj_type: 'account',
                            for_obj_id: $slct.account_id,
                            enabled: 'enabled',
                            hidden: 'not_hidden',
                            limit: $ae_loc.person.qry_limit__people,
                            // params: {
                            //     'qry__enabled': 'enabled',
                            //     'qry__hidden': 'not_hidden',
                            //     'qry__limit': $ae_loc.person.qry_limit__people,},
                            log_lvl: 1
                        })
                        .then(function (load_results) {
                            console.log(`Loaded person_obj_li:`, load_results);
                            if (load_results) {
                                $slct.person_id_random_li = load_results;

                                person_id_random_li = [];

                                let tmp_li = []; // This is to prevent the array from constantly updating and triggering the liveQuery.

                                for (let i = 0; i < $slct.person_id_random_li.length; i++) {
                                    let person_obj = $slct.person_id_random_li[i];
                                    let person_id_random = person_obj.person_id_random;
                                    tmp_li.push(person_id_random);
                                }
                                person_id_random_li = tmp_li;
                            }
                            return load_results;
                        });
                }}
                class="select max-w-20 text-sm"
            >
                <option value={25}>25</option>
                <option value={50}>50</option>
                <option value={75}>75</option>
                <option value={100}>100</option>
                <option value={150}>150</option>
                <option value={200}>200</option>
                <option value={250}>250</option>
                <option value={500}>500</option>
                <option value={750}>750</option>
                <option value={1000}>1000</option>
            </select>
        </label>

        <div class="outline">
            <!-- Count: {person_id_random_li?.length} -->
            <Comp_person_obj_tbl
                bind:person_id_random_li
                show_user_fields={$ae_loc.administrator_access}
            ></Comp_person_obj_tbl>
        </div>
    {/if}
</section>
