<script lang="ts">
    /** @type {import('./$types').PageData} */
    // import { page } from '$app/stores';

    // Imports
    import { onMount } from 'svelte';
    import { goto } 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/elements/element_data_store_v3.svelte';

    import { liveQuery } from 'dexie';
    // import { core_func } from '$lib/ae_core_functions';
    import { db_core } from '$lib/ae_core/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';
    // import { events_loc, events_sess, slct, events_trigger } from '$lib/stores/ae_events_stores';
    // import { events_func } from '$lib/ae_events_functions';

    import Person_view from './../../person_view.svelte';
    import Person_form from './../ae_comp__person_form.svelte';
    import { load_ae_obj_li__user } from '$lib/ae_core/ae_core__user';
    import { update_ae_obj__person } from '$lib/ae_core/ae_core__person';
    import { qry_ae_obj_li__event } from '$lib/ae_events/ae_events__event';
    import { qry__post } from '$lib/ae_posts/ae_posts__post';
    import { qry__activity_log } from '$lib/ae_core/ae_core__activity_log';
    import { Users, Link, Unlink, UserPlus, ShieldCheck, User, Calendar, MessageSquare, History, Activity, Edit, Eye } from 'lucide-svelte';

    interface Props {
        data: any;
    }

    let { data }: Props = $props();

    // Variables
    $slct.account_id = data.account_id;
    let ae_acct = data[data.account_id];

    $ae_loc.url_origin = data.url.origin;

    $slct.person_id = ae_acct.slct.person_id;
    $slct.person_obj = ae_acct.slct.person_obj;

    let is_editing = $state(false);

    let lq__person_obj = liveQuery(() => db_core.person.get($slct.person_id));
    $slct.lq__person_obj = lq__person_obj;

    let available_users: any[] = $state([]);
    let loading_users = $state(false);
    let show_link_ui = $state(false);

    let related_events: any[] = $state([]);
    let related_posts: any[] = $state([]);
    let related_activity_logs: any[] = $state([]);
    let loading_activity = $state(false);

    async function load_activity() {
        if (!$slct.person_id) return;
        loading_activity = true;

        // Load related data using search queries
        const [events, posts, logs] = await Promise.all([
            qry_ae_obj_li__event({
                api_cfg: $ae_api,
                for_obj_id: $ae_loc.account_id,
                qry_person_id: $slct.person_id,
                log_lvl: 1
            }),
            qry__post({
                api_cfg: $ae_api,
                account_id: $ae_loc.account_id,
                qry_person_id: $slct.person_id,
                log_lvl: 1
            }),
            qry__activity_log({
                api_cfg: $ae_api,
                account_id: $ae_loc.account_id,
                qry_person_id: $slct.person_id,
                limit: 10,
                log_lvl: 1
            })
        ]);

        related_events = events || [];
        related_posts = posts || [];
        related_activity_logs = logs || [];
        loading_activity = false;
    }

    async function load_unlinked_users() {
        if (!$ae_loc.manager_access) return;
        loading_users = true;
        const all_users = await load_ae_obj_li__user({
            api_cfg: $ae_api,
            enabled: 'enabled',
            log_lvl: 1
        });
        // Filter users that don't have a person_id linked
        // NOTE: The backend might return person_id or person_id
        available_users = all_users.filter(u => !u.person_id && !u.person_id);
        loading_users = false;
    }

    async function handle_link_user(user_id: string) {
        if (!confirm('Link this person to this user account?')) return;

        const result = await update_ae_obj__person({
            api_cfg: $ae_api,
            person_id: $slct.person_id,
            data_kv: { user_id },
            log_lvl: 1
        });

        if (result) {
            show_link_ui = false;
            available_users = [];
        }
    }

    async function handle_unlink_user() {
        if (!confirm('Unlink this person from their user account?')) return;

        const result = await update_ae_obj__person({
            api_cfg: $ae_api,
            person_id: $slct.person_id,
            data_kv: { user_id: null },
            log_lvl: 1
        });
    }

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

    if (!$ae_loc.person) {
        $ae_loc.person = {};
    }
    $ae_loc.person.show_content__person_page_help = false;

    // *** Functions and Logic
</script>

<svelte:head>
    <title>
        Person: {ae_util.shorten_string({
            string: $lq__person_obj?.full_name,
            max_length: 20,
            begin_length: 10,
            end_length: 4
        })}
        ({$lq__person_obj?.person_id ?? 'loading...'}) - Core - {$ae_loc?.title}
    </title>
</svelte:head>

<section class="ae_core__person md:container h-full mx-auto flex flex-col space-y-4 pt-0 pb-8">
    <div
        class="core__person_view_menu {ae_snip.classes__core_menu}"
        class:border-gray-100={!$ae_loc.person.show_content__person_page_help}
    >
        <div>
            <a href="/core/people" class={ae_snip.classes__core_menu__button}>
                <span class="fas fa-arrow-left mx-1"></span>
                Back to People
            </a>

            {#if $ae_loc.edit_mode}
                <button
                    type="button"
                    onclick={() => is_editing = !is_editing}
                    class="btn btn-sm variant-soft-secondary mx-1"
                >
                    {#if is_editing}
                        <Eye size={16} class="mr-2" /> View Mode
                    {:else}
                        <Edit size={16} class="mr-2" /> Edit Mode
                    {/if}
                </button>
            {/if}

            <button
                type="button"
                onclick={() => {
                    $ae_loc.person.show_content__person_page_help =
                        !$ae_loc.person.show_content__person_page_help;
                }}
                class={ae_snip.classes__core_menu__button}
                title="Help and information about the person page"
            >
                <span class="fas fa-question-circle mx-1"></span>
                {#if $ae_loc.person.show_content__person_page_help}
                    Hide
                {:else}
                    Show
                {/if}
                Help?
            </button>
        </div>

        <Element_data_store
            ds_code="events__core__person_page_help"
            ds_name="Default: Core - Person Page Help"
            ds_type="html"
            for_type="event"
            for_id={$slct.event_id}
            class_li="bg-yellow-100 p-2 rounded-md border border-yellow-200"
            show_edit={false}
            show_edit_btn={true}
            hide={!$ae_loc.person.show_content__person_page_help}
        />

        <div>
            <button
                type="button"
                onclick={() => {
                    $ae_loc.person.show_content__person_page_help =
                        !$ae_loc.person.show_content__person_page_help;
                }}
                class="btn btn-sm mx-1 preset-tonal-error border border-error-500 hover:preset-filled-error-500"
                class:hidden={!$ae_loc.person.show_content__person_page_help}
                title="Help and information about the session search"
            >
                <span class="fas fa-question-circle mx-1"></span>
                {#if $ae_loc.person.show_content__person_page_help}
                    Hide
                {:else}
                    Show
                {/if}
                Help?
            </button>
        </div>
    </div>

    {#if $ae_loc.manager_access}
        <div class="card p-4 variant-soft-surface space-y-4 mx-4">
            <header class="flex justify-between items-center border-b border-surface-500/30 pb-2">
                <div class="flex items-center gap-2 font-bold">
                    <ShieldCheck size={18} />
                    <span>User Account Linking</span>
                </div>
                {#if $lq__person_obj?.user_id}
                    <button class="btn btn-sm variant-soft-error" onclick={handle_unlink_user}>
                        <Unlink size={14} class="mr-2" /> Unlink User
                    </button>
                {:else}
                    <button
                        class="btn btn-sm variant-soft-primary"
                        onclick={() => { show_link_ui = !show_link_ui; if(show_link_ui) load_unlinked_users(); }}
                    >
                        <Link size={14} class="mr-2" /> {show_link_ui ? 'Cancel Linking' : 'Link to User'}
                    </button>
                {/if}
            </header>

            {#if $lq__person_obj?.user_id}
                <div class="flex items-center gap-4 py-2">
                    <div class="avatar variant-filled-primary w-12 h-12 flex items-center justify-center rounded-full">
                        <Users size={24} />
                    </div>
                    <div>
                        <p class="text-sm opacity-60 uppercase tracking-widest font-bold">Linked User ID</p>
                        <p class="font-mono text-lg">{$lq__person_obj.user_id}</p>
                        <p class="text-xs opacity-60">Username: {$lq__person_obj.username || '--'}</p>
                    </div>
                </div>
            {:else if show_link_ui}
                <div class="space-y-4 py-2">
                    <p class="text-sm opacity-80">Select a user account to link to this person. Only accounts without a linked person are shown.</p>
                    {#if loading_users}
                        <div class="placeholder animate-pulse h-20 w-full"></div>
                    {:else if available_users.length === 0}
                        <p class="text-center py-4 italic opacity-60 border border-dashed border-surface-500/30">No unlinked user accounts found.</p>
                    {:else}
                        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2">
                            {#each available_users as user}
                                <button
                                    class="card p-3 variant-soft-primary hover:variant-filled-primary text-left transition-all flex flex-col gap-1"
                                    onclick={() => handle_link_user(user.user_id)}
                                >
                                    <span class="font-bold flex items-center gap-2">
                                        <User size={14} />
                                        {user.username}
                                    </span>
                                    <span class="text-xs opacity-70 truncate">{user.email}</span>
                                    <div class="flex gap-1 mt-1">
                                        {#if user.super}<span class="badge variant-filled-error text-[10px]">Super</span>{/if}
                                        {#if user.manager}<span class="badge variant-filled-warning text-[10px]">Manager</span>{/if}
                                    </div>
                                </button>
                            {/each}
                        </div>
                    {/if}
                </div>
            {:else}
                <div class="flex items-center gap-2 py-2 opacity-60">
                    <Users size={20} />
                    <p class="italic text-sm">This person is not currently linked to a user account.</p>
                </div>
            {/if}
        </div>

        <!-- Activity & Content Section -->
        <div class="card p-4 variant-soft-surface space-y-4 mx-4">
            <header class="flex items-center gap-2 font-bold border-b border-surface-500/30 pb-2">
                <History size={18} />
                <span>Linked Activity & Content</span>
            </header>

            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                <!-- Related Events -->
                <div class="space-y-3">
                    <h4 class="h4 flex items-center gap-2 text-sm opacity-70 uppercase tracking-wider font-bold">
                        <Calendar size={16} /> Related Events
                    </h4>
                    {#if loading_activity}
                        <div class="placeholder animate-pulse h-20 w-full"></div>
                    {:else if related_events.length === 0}
                        <p class="text-sm italic opacity-50">No related events found.</p>
                    {:else}
                        <div class="space-y-2">
                            {#each related_events as ev}
                                <a href="/events/{ev.event_id}" class="card p-3 variant-soft flex flex-col gap-1 hover:variant-soft-primary transition-all">
                                    <span class="font-bold text-sm">{ev.name}</span>
                                    <span class="text-[10px] opacity-60">{new Date(ev.start_datetime).toLocaleDateString()}</span>
                                </a>
                            {/each}
                        </div>
                    {/if}
                </div>

                <!-- Related Posts -->
                <div class="space-y-3">
                    <h4 class="h4 flex items-center gap-2 text-sm opacity-70 uppercase tracking-wider font-bold">
                        <MessageSquare size={16} /> Related Posts
                    </h4>
                    {#if loading_activity}
                        <div class="placeholder animate-pulse h-20 w-full"></div>
                    {:else if related_posts.length === 0}
                        <p class="text-sm italic opacity-50">No related posts found.</p>
                    {:else}
                        <div class="space-y-2">
                            {#each related_posts as post}
                                <a href="/idaa/bb/{post.post_id}" class="card p-3 variant-soft flex flex-col gap-1 hover:variant-soft-primary transition-all">
                                    <span class="font-bold text-sm">{post.title}</span>
                                    <div class="flex justify-between items-center text-[10px] opacity-60">
                                        <span>{new Date(post.created_on).toLocaleDateString()}</span>
                                        <span class="badge variant-soft-surface scale-75">{post.post_comment_count || 0} comments</span>
                                    </div>
                                </a>
                            {/each}
                        </div>
                    {/if}
                </div>

                <!-- Recent Activity -->
                <div class="space-y-3">
                    <h4 class="h4 flex items-center gap-2 text-sm opacity-70 uppercase tracking-wider font-bold">
                        <Activity size={16} /> Recent Activity
                    </h4>
                    {#if loading_activity}
                        <div class="placeholder animate-pulse h-20 w-full"></div>
                    {:else if related_activity_logs.length === 0}
                        <p class="text-sm italic opacity-50">No recent activity logs.</p>
                    {:else}
                        <div class="space-y-2">
                            {#each related_activity_logs as log}
                                <div class="card p-3 variant-soft flex flex-col gap-1">
                                    <div class="flex justify-between items-start gap-2">
                                        <span class="badge variant-filled-surface text-[9px] uppercase tracking-tighter">{log.action}</span>
                                        <span class="text-[9px] opacity-50">{new Date(log.created_on).toLocaleDateString()}</span>
                                    </div>
                                    {#if log.summary}
                                        <span class="text-xs opacity-80 line-clamp-1">{log.summary}</span>
                                    {/if}
                                </div>
                            {/each}
                            <a href="/core/activity_logs?person_id={$slct.person_id}" class="btn btn-sm variant-soft-surface w-full text-[10px]">
                                View All Activity
                            </a>
                        </div>
                    {/if}
                </div>
            </div>
        </div>
    {/if}

    {#if !$lq__person_obj}
        <div class="flex flex-row items-center justify-center p-8">
            <span class="fas fa-spinner fa-spin mx-1"></span>
            <span>Loading Person...</span>
        </div>
    {:else if is_editing}
        <div class="px-4">
            <Person_form
                person={$lq__person_obj}
                onSave={(updated) => {
                    is_editing = false;
                    // The liveQuery should pick up the changes after they are saved to IndexedDB
                    // inside update_ae_obj__person -> db_save_ae_obj_li__ae_obj
                }}
                onCancel={() => is_editing = false}
            />
        </div>
    {:else}
        <Person_view person_id={$slct.person_id} />
    {/if}
    <!-- {:catch error}
    <div class="text-red-800">
        <span class="fas fa-exclamation-triangle text-xl"></span>
        <span>Error: {error.message}</span>
    </div>
{/await} -->

    <!-- {$slct.person_id ?? 'Unknown ID'} -->
</section>

<style lang="postcss">
    /* Use the div.ae_quick_modal_container to block background clicks when using the section.ae_quick_popover. */
    div.ae_quick_modal_container {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: 100;
        background-color: hsla(0, 0%, 50%, 0.75);
        /* padding: 1rem; */
        /* border: solid thick red; */
    }

    /* The section.ae_quick_popover should be above the rest of the content and centered on the page. */
    section.ae_quick_popover {
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        z-index: 100;
        background-color: hsla(0, 0%, 97%, 0.97);
        /* margin-top: 1rem;
    margin-bottom: 2rem; */
        /* padding: 1rem;
    padding-top:4rem; */
        /* padding-bottom: 4rem; */
        border: solid thin hsla(0, 0%, 0%, 0.9);
        border-radius: 0.5rem;
        box-shadow: 0 0 1rem hsla(0, 0%, 0%, 0.5);

        min-height: 30%;
        /* max-height: 100vh; */
        min-width: 80%;

        /* overflow-y: auto; */
    }
</style>
