<script lang="ts">
import { onMount } from 'svelte';
import { goto } from '$app/navigation';
import { ListFilter, Plus, Users, X } from '@lucide/svelte';
import { ae_loc, ae_sess, slct, ae_api } from '$lib/stores/ae_stores';
import { core_func } from '$lib/ae_core/ae_core_functions';
import Comp_person_search from './ae_comp__person_search.svelte';
import Comp_person_obj_tbl from '../ae_comp__person_obj_tbl.svelte';
import Person_form from './ae_comp__person_form.svelte';

let person_id_li: string[] = $state([]);
let show_add_form = $state(false);

onMount(() => {
    if (!$ae_loc.manager_access) {
        goto('/core');
        return;
    }
});
</script>

<div class="container mx-auto space-y-6 p-4">
    <header
        class="bg-surface-50-900-token border-surface-500/10 flex items-center justify-between rounded-xl border p-4 shadow-lg">
        <div class="flex items-center gap-2">
            <div class="bg-primary-500/10 rounded-lg p-2">
                <Users size={24} class="text-primary-500" />
            </div>
            <h1 class="h2 font-black tracking-tight">People Management</h1>
        </div>
        <button
            type="button"
            onclick={() => (show_add_form = !show_add_form)}
            class="btn btn-sm preset-filled-primary font-bold shadow-lg"
            class:hidden={!$ae_loc.edit_mode}>
            {#if show_add_form}
                <X size={16} class="mr-2" /> Cancel
            {:else}
                <Plus size={16} class="mr-2" /> Add Person
            {/if}
        </button>
    </header>

    {#if show_add_form}
        <div class="animate-fade-in">
            <Person_form
                onSave={(new_person) => {
                    show_add_form = false;
                    goto(`/core/people/${new_person.person_id}`);
                }}
                onCancel={() => (show_add_form = false)} />
        </div>
    {/if}

    <Comp_person_search
        on_results={(results) => {
            person_id_li = results.map((p) => p.person_id);
            $ae_sess.person.show_report__person_li = true;
        }} />

    {#if $ae_sess.person.show_report__person_li}
        <div
            class="card preset-tonal-surface border-surface-500/10 space-y-4 border p-6 shadow-xl">
            <h3
                class="h4 border-surface-500/30 flex items-center gap-2 border-b pb-2 font-bold">
                <ListFilter size={18} class="text-secondary-500" />
                Search Results
                <span class="badge preset-tonal-secondary ml-auto"
                    >{person_id_li.length} found</span>
            </h3>
            <div class="overflow-x-auto">
                <Comp_person_obj_tbl
                    bind:person_id_li
                    show_user_fields={$ae_loc.administrator_access}
                ></Comp_person_obj_tbl>
            </div>
        </div>
    {/if}
</div>
