<script lang="ts">
import { onMount } from 'svelte';
import { ae_loc, ae_api, slct } from '$lib/stores/ae_stores';
import { goto } from '$app/navigation';
import {
    Activity,
    Contact,
    ExternalLink,
    ListFilter,
    Mail,
    Phone,
    Plus,
    Search,
    ShieldCheck,
    User,
    X
} from '@lucide/svelte';
import {
    load_ae_obj_li__contact,
    create_ae_obj__contact
} from '$lib/ae_core/ae_core__contact';
import Contact_form from './ae_comp__contact_form.svelte';

let contact_li: any[] = $state([]);
let qry_str = $state('');
let filtered_li: any[] = $derived(
    qry_str
        ? contact_li.filter(
              (c) =>
                  c.name?.toLowerCase().includes(qry_str.toLowerCase()) ||
                  c.title?.toLowerCase().includes(qry_str.toLowerCase()) ||
                  c.email?.toLowerCase().includes(qry_str.toLowerCase()) ||
                  c.phone_office?.toLowerCase().includes(qry_str.toLowerCase())
          )
        : contact_li
);
let loading = $state(true);
let show_add_form = $state(false);

async function load_contacts() {
    if (!$ae_loc.account_id) return;
    loading = true;
    contact_li = await load_ae_obj_li__contact({
        api_cfg: $ae_api,
        for_obj_id: $ae_loc.account_id,
        enabled: 'all',
        hidden: 'all',
        log_lvl: 1
    });
    loading = false;
}

onMount(() => {
    if (!$ae_loc.manager_access) {
        goto('/core');
        return;
    }
    load_contacts();
});
</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">
                <Phone size={24} class="text-primary-500" />
            </div>
            <h1 class="h2 font-black tracking-tight">Contact Management</h1>
        </div>
        <button
            class="btn btn-sm preset-filled-primary font-bold shadow-lg"
            onclick={() => (show_add_form = !show_add_form)}>
            {#if show_add_form}
                <X size={16} class="mr-2" /> Cancel
            {:else}
                <Plus size={16} class="mr-2" /> Add Contact
            {/if}
        </button>
    </header>

    {#if show_add_form}
        <div class="animate-fade-in">
            <Contact_form
                onSave={(new_con) => {
                    show_add_form = false;
                    load_contacts();
                    if (new_con.contact_id) {
                        goto(`/core/contacts/${new_con.contact_id}`);
                    }
                }}
                onCancel={() => (show_add_form = false)} />
        </div>
    {/if}

    <div
        class="card preset-tonal-surface border-surface-500/10 border p-6 shadow-xl">
        <div class="max-w-2xl space-y-1">
            <span
                class="label ml-1 block text-xs font-bold tracking-wider uppercase opacity-75"
                >Search Directory</span>
            <div
                class="bg-surface-200-700-token border-surface-500/20 group focus-within:ring-primary-500/50 flex overflow-hidden rounded-lg border shadow-inner transition-all focus-within:ring-2">
                <div
                    class="bg-surface-300-600-token border-surface-500/20 flex items-center justify-center border-r px-4">
                    <Search size={18} class="opacity-50" />
                </div>
                <input
                    class="grow border-0 bg-transparent p-3 ring-0 placeholder:opacity-50 focus:ring-0"
                    type="search"
                    bind:value={qry_str}
                    placeholder="Search by name, title, email, or phone..." />
                <button
                    class="preset-filled-primary border-surface-500/20 flex min-w-[100px] items-center justify-center border-l px-10 py-3 font-bold transition-all hover:brightness-110"
                    onclick={load_contacts}
                    disabled={loading}>
                    {#if loading}
                        <span class="animate-spin text-xl">⏳</span>
                    {:else}
                        <span class="tracking-wide whitespace-nowrap"
                            >Refresh</span>
                    {/if}
                </button>
            </div>
        </div>
    </div>

    {#if loading}
        <div class="card flex h-64 items-center justify-center p-8">
            <div class="placeholder h-full w-full animate-pulse rounded-2xl">
            </div>
        </div>
    {:else if filtered_li.length === 0}
        <div
            class="card preset-tonal-surface border-surface-500/20 rounded-2xl border-2 border-dashed p-12 text-center">
            <Contact size={48} class="mx-auto mb-4 opacity-20" />
            <h3 class="h3 font-bold opacity-50">No Contacts Found</h3>
            <p class="mx-auto mt-2 max-w-xs opacity-60">
                Business and support contacts will appear here.
            </p>
        </div>
    {:else}
        <div
            class="card preset-tonal-surface border-surface-500/10 border p-6 shadow-xl">
            <h3
                class="h4 border-surface-500/30 mb-6 flex items-center gap-2 border-b pb-2 font-bold">
                <ListFilter size={18} class="text-secondary-500" />
                Directory Results
                <span class="badge preset-tonal-secondary ml-auto"
                    >{filtered_li.length} entries</span>
            </h3>

            <div class="grid grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-3">
                {#each filtered_li as con (con.contact_id)}
                    <div
                        class="card preset-tonal-surface border-surface-500/10 hover:border-primary-500/30 group relative space-y-4 border p-5 shadow-md transition-all">
                        <div class="absolute top-4 right-4">
                            <span
                                class="badge {con.enable
                                    ? 'preset-filled-success'
                                    : 'preset-filled-error'} text-[8px] font-bold uppercase shadow-sm">
                                {con.enable ? 'Active' : 'Disabled'}
                            </span>
                        </div>

                        <header class="flex items-center gap-3">
                            <div
                                class="avatar preset-filled-primary flex h-12 w-12 items-center justify-center rounded-full shadow-inner transition-transform group-hover:scale-110">
                                <User size={24} />
                            </div>
                            <div class="pr-12">
                                <p class="truncate font-black tracking-tight">
                                    {con.name || con.title || '--'}
                                </p>
                                <p
                                    class="truncate text-[10px] font-bold uppercase opacity-50">
                                    {con.title || 'Support Contact'}
                                </p>
                            </div>
                        </header>

                        <div class="space-y-2 text-xs opacity-70">
                            <div
                                class="flex items-center gap-2 rounded-lg bg-black/5 p-2">
                                <Mail
                                    size={14}
                                    class="text-primary-500 shrink-0" />
                                <span class="truncate"
                                    >{con.email || 'No Email'}</span>
                            </div>
                            <div
                                class="flex items-center gap-2 rounded-lg bg-black/5 p-2">
                                <Phone
                                    size={14}
                                    class="text-secondary-500 shrink-0" />
                                <span class="truncate"
                                    >{con.phone_office ||
                                        con.phone_mobile ||
                                        '--'}</span>
                            </div>
                        </div>

                        <a
                            class="btn btn-sm preset-filled-primary w-full font-bold shadow-lg transition-all group-hover:brightness-110"
                            href="/core/contacts/{con.contact_id}">
                            Manage Contact
                        </a>
                    </div>
                {/each}
            </div>
        </div>
    {/if}
</div>
