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

// Imports
import { onMount, untrack } 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_data_store from '$lib/elements/element_data_store.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/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 {
    Activity,
    ArrowLeft,
    Calendar,
    Edit,
    Eye,
    HelpCircle,
    History,
    Link,
    LoaderCircle,
    MessageSquare,
    ShieldCheck,
    Unlink,
    User,
    UserPlus,
    Users
} from '@lucide/svelte';
interface Props {
    data: any;
}

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

// Variables
let ae_acct = $derived(data[data.account_id]);

$effect(() => {
    if (!ae_acct) return;
    untrack(() => {
        $slct.account_id = 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 confirm_action = $state<string | null>(null);

// .get() uses the primary key (id), which V3 never populates — always use .where().equals().first()
let lq__person_obj = liveQuery(() => db_core.person.where('person_id').equals($slct.person_id ?? '').first());
$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_action !== `link_user_${user_id}`) {
        confirm_action = `link_user_${user_id}`;
        return;
    }
    confirm_action = null;

    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_action !== 'unlink_user') {
        confirm_action = 'unlink_user';
        return;
    }
    confirm_action = null;

    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 mx-auto flex h-full flex-col space-y-4 pt-0 pb-8 md:container">
    <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}>
                <ArrowLeft size="1em" class="mx-1" />
                Back to People
            </a>

            {#if $ae_loc.edit_mode}
                <button
                    type="button"
                    onclick={() => (is_editing = !is_editing)}
                    class="btn btn-sm preset-tonal-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">
                <HelpCircle size="1em" class="mx-1" />
                {#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 preset-tonal-error border-error-500 hover:preset-filled-error-500 mx-1 border"
                class:hidden={!$ae_loc.person.show_content__person_page_help}
                title="Help and information about the session search">
                <HelpCircle size="1em" class="mx-1" />
                {#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 preset-tonal-surface mx-4 space-y-4 p-4">
            <header
                class="border-surface-500/30 flex items-center justify-between border-b 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}
                    {#if confirm_action === 'unlink_user'}
                        <span class="self-center text-sm font-bold text-red-600">Unlink this user?</span>
                        <button
                            class="btn btn-sm preset-filled-error"
                            onclick={handle_unlink_user}>
                            <Unlink size={14} class="mr-2" /> Confirm Unlink
                        </button>
                        <button
                            class="btn btn-sm preset-tonal-surface"
                            onclick={() => (confirm_action = null)}>
                            Cancel
                        </button>
                    {:else}
                        <button
                            class="btn btn-sm preset-tonal-error"
                            onclick={handle_unlink_user}>
                            <Unlink size={14} class="mr-2" /> Unlink User
                        </button>
                    {/if}
                {:else}
                    <button
                        class="btn btn-sm preset-tonal-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 preset-filled-primary flex h-12 w-12 items-center justify-center rounded-full">
                        <Users size={24} />
                    </div>
                    <div>
                        <p
                            class="text-sm font-bold tracking-widest uppercase opacity-60">
                            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 h-20 w-full animate-pulse">
                        </div>
                    {:else if available_users.length === 0}
                        <p
                            class="border-surface-500/30 border border-dashed py-4 text-center italic opacity-60">
                            No unlinked user accounts found.
                        </p>
                    {:else}
                        <div
                            class="grid grid-cols-1 gap-2 sm:grid-cols-2 lg:grid-cols-3">
                            {#each available_users as user (user.user_id)}
                                {#if confirm_action === `link_user_${user.user_id}`}
                                    <div class="card preset-tonal-warning flex flex-col gap-2 p-3">
                                        <span class="text-sm font-bold">Link {user.username}?</span>
                                        <div class="flex gap-2">
                                            <button
                                                class="btn btn-sm preset-filled-primary flex-1"
                                                onclick={() => handle_link_user(user.user_id)}>
                                                Confirm
                                            </button>
                                            <button
                                                class="btn btn-sm preset-tonal-surface"
                                                onclick={() => (confirm_action = null)}>
                                                Cancel
                                            </button>
                                        </div>
                                    </div>
                                {:else}
                                    <button
                                        class="card preset-tonal-primary hover:preset-filled-primary flex flex-col gap-1 p-3 text-left transition-all"
                                        onclick={() =>
                                            handle_link_user(user.user_id)}>
                                        <span
                                            class="flex items-center gap-2 font-bold">
                                            <User size={14} />
                                            {user.username}
                                        </span>
                                        <span class="truncate text-xs opacity-70"
                                            >{user.email}</span>
                                        <div class="mt-1 flex gap-1">
                                            {#if user.super}<span
                                                    class="badge preset-filled-error text-[10px]"
                                                    >Super</span
                                                >{/if}
                                            {#if user.manager}<span
                                                    class="badge preset-filled-warning text-[10px]"
                                                    >Manager</span
                                                >{/if}
                                        </div>
                                    </button>
                                {/if}
                            {/each}
                        </div>
                    {/if}
                </div>
            {:else}
                <div class="flex items-center gap-2 py-2 opacity-60">
                    <Users size={20} />
                    <p class="text-sm italic">
                        This person is not currently linked to a user account.
                    </p>
                </div>
            {/if}
        </div>

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

            <div class="grid grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-3">
                <!-- Related Events -->
                <div class="space-y-3">
                    <h4
                        class="h4 flex items-center gap-2 text-sm font-bold tracking-wider uppercase opacity-70">
                        <Calendar size={16} /> Related Events
                    </h4>
                    {#if loading_activity}
                        <div class="placeholder h-20 w-full animate-pulse">
                        </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 (ev.event_id)}
                                <a
                                    href="/events/{ev.event_id}"
                                    class="card preset-tonal-surface hover:preset-tonal-primary flex flex-col gap-1 p-3 transition-all">
                                    <span class="text-sm font-bold"
                                        >{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 font-bold tracking-wider uppercase opacity-70">
                        <MessageSquare size={16} /> Related Posts
                    </h4>
                    {#if loading_activity}
                        <div class="placeholder h-20 w-full animate-pulse">
                        </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 (post.post_id)}
                                <a
                                    href="/idaa/bb/{post.post_id}"
                                    class="card preset-tonal-surface hover:preset-tonal-primary flex flex-col gap-1 p-3 transition-all">
                                    <span class="text-sm font-bold"
                                        >{post.title}</span>
                                    <div
                                        class="flex items-center justify-between text-[10px] opacity-60">
                                        <span
                                            >{new Date(
                                                post.created_on
                                            ).toLocaleDateString()}</span>
                                        <span
                                            class="badge preset-tonal-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 font-bold tracking-wider uppercase opacity-70">
                        <Activity size={16} /> Recent Activity
                    </h4>
                    {#if loading_activity}
                        <div class="placeholder h-20 w-full animate-pulse">
                        </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, index (index)}
                                <div
                                    class="card preset-tonal-surface flex flex-col gap-1 p-3">
                                    <div
                                        class="flex items-start justify-between gap-2">
                                        <span
                                            class="badge preset-filled-surface text-[9px] tracking-tighter uppercase"
                                            >{log.action}</span>
                                        <span class="text-[9px] opacity-50"
                                            >{new Date(
                                                log.created_on
                                            ).toLocaleDateString()}</span>
                                    </div>
                                    {#if log.summary}
                                        <span
                                            class="line-clamp-1 text-xs opacity-80"
                                            >{log.summary}</span>
                                    {/if}
                                </div>
                            {/each}
                            <a
                                href="/core/activity_logs?person_id={$slct.person_id}"
                                class="btn btn-sm preset-tonal-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">
            <LoaderCircle size="1em" class="mx-1 animate-spin" />
            <span>Loading Person...</span>
        </div>
    {:else if is_editing}
        <div class="px-4">
            <Person_form
                person={$lq__person_obj}
                onSave={(updated) => {
                    is_editing = false;
                }}
                onCancel={() => (is_editing = false)} />
        </div>
    {:else}
        <Person_view person_id={$slct.person_id} />
    {/if}
</section>
