<script lang="ts">
import { onMount } from 'svelte';
import { page } from '$app/stores';
import {
    load_ae_obj_id__contact,
    update_ae_obj__contact,
    delete_ae_obj_id__contact
} from '$lib/ae_core/ae_core__contact';
import { editable_fields__contact } from '$lib/ae_core/ae_core__contact.editable_fields';
import { ae_api, ae_loc } from '$lib/stores/ae_stores';
import { goto } from '$app/navigation';
import {
    Activity,
    ArrowLeft,
    Contact,
    Edit,
    Eye,
    Globe,
    Info,
    Link2,
    Linkedin,
    Mail,
    Phone,
    Save,
    ShieldCheck,
    Trash2,
    UserRound
} from '@lucide/svelte';
import Contact_form from '../ae_comp__contact_form.svelte';

let contact_id = $derived($page.params.contact_id ?? '');
let contact: any = $state(null);
let loading = $state(true);
let is_editing = $state(false);
let confirm_action = $state<string | null>(null);

async function load_data() {
    loading = true;
    contact = await load_ae_obj_id__contact({
        api_cfg: $ae_api,
        contact_id,
        log_lvl: 1
    });
    loading = false;
}

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

async function handle_delete() {
    if (confirm_action !== 'delete_contact') {
        confirm_action = 'delete_contact';
        return;
    }
    confirm_action = null;
    await delete_ae_obj_id__contact({
        api_cfg: $ae_api,
        contact_id,
        method: 'delete',
        log_lvl: 1
    });
    goto('/core/contacts');
}
</script>

<div class="container mx-auto space-y-6 p-4">
    <header
        class="bg-surface-50-900-token border-surface-500/10 flex flex-wrap items-center justify-between gap-4 rounded-xl border p-4 shadow-lg">
        <div class="flex items-center gap-4">
            <a
                class="btn btn-sm preset-tonal-surface shadow-sm"
                href="/core/contacts">
                <ArrowLeft size={16} />
            </a>
            <div class="flex items-center gap-3">
                <div class="bg-primary-500/10 rounded-lg p-2">
                    <UserRound size={24} class="text-primary-500" />
                </div>
                <div>
                    <h1 class="h2 font-black tracking-tight">
                        {contact?.name || contact?.title || 'Loading...'}
                    </h1>
                    <p
                        class="text-xs font-bold tracking-widest uppercase opacity-50">
                        Contact Detail
                    </p>
                </div>
            </div>
        </div>
        <div class="flex flex-wrap gap-2">
            <button
                class="btn btn-sm preset-tonal-secondary font-bold shadow-sm"
                onclick={() => (is_editing = !is_editing)}
                disabled={loading}>
                {#if is_editing}
                    <Eye size={16} class="mr-2" /> View Mode
                {:else}
                    <Edit size={16} class="mr-2" /> Edit Mode
                {/if}
            </button>
            {#if confirm_action === 'delete_contact'}
                <span class="self-center text-sm font-bold text-red-600">Delete this contact?</span>
                <button
                    class="btn btn-sm preset-filled-error font-bold shadow-sm"
                    onclick={handle_delete}
                    disabled={loading}>
                    <Trash2 size={16} class="mr-2" /> Confirm Delete
                </button>
                <button
                    class="btn btn-sm preset-tonal-surface"
                    onclick={() => (confirm_action = null)}>
                    Cancel
                </button>
            {:else}
                <button
                    class="btn btn-sm preset-tonal-error font-bold shadow-sm"
                    onclick={handle_delete}
                    disabled={loading}>
                    <Trash2 size={16} class="mr-2" /> Delete
                </button>
            {/if}
        </div>
    </header>

    {#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 contact}
        {#if is_editing}
            <div class="animate-fade-in">
                <Contact_form
                    {contact}
                    onSave={(updated) => {
                        contact = updated;
                        is_editing = false;
                    }}
                    onCancel={() => (is_editing = false)} />
            </div>
        {:else}
            <div class="animate-fade-in grid grid-cols-1 gap-6 lg:grid-cols-3">
                <div class="space-y-6 lg:col-span-2">
                    <div
                        class="card preset-tonal-surface border-surface-500/10 space-y-6 border p-6 shadow-xl">
                        <h3
                            class="h4 border-surface-500/30 flex items-center gap-2 border-b pb-2 font-bold">
                            <Contact size={20} class="text-primary-500" />
                            Core Information
                        </h3>
                        <div class="grid grid-cols-1 gap-6 md:grid-cols-2">
                            <div class="space-y-1">
                                <p
                                    class="flex items-center gap-1 text-[10px] font-black tracking-widest uppercase opacity-60">
                                    <UserRound size={10} /> Full Name / Title
                                </p>
                                <p
                                    class="text-lg leading-tight font-black tracking-tight">
                                    {contact.name || contact.title || '--'}
                                </p>
                            </div>
                            <div class="space-y-1">
                                <p
                                    class="flex items-center gap-1 text-[10px] font-black tracking-widest uppercase opacity-60">
                                    <Activity size={10} /> Tagline / Role
                                </p>
                                <p class="font-bold">
                                    {contact.tagline || '--'}
                                </p>
                            </div>
                            <div
                                class="border-surface-500/10 space-y-1 rounded-xl border bg-black/5 p-4">
                                <p
                                    class="flex items-center gap-1 text-[10px] font-black tracking-widest uppercase opacity-60">
                                    <Mail size={10} /> Email Address
                                </p>
                                <p class="text-primary-500 font-bold break-all">
                                    {contact.email || '--'}
                                </p>
                            </div>
                            <div
                                class="border-surface-500/10 space-y-1 rounded-xl border bg-black/5 p-4">
                                <p
                                    class="flex items-center gap-1 text-[10px] font-black tracking-widest uppercase opacity-60">
                                    <Globe size={10} /> Website
                                </p>
                                {#if contact.website_url}
                                    <a
                                        href={contact.website_url}
                                        target="_blank"
                                        rel="noopener noreferrer"
                                        class="text-secondary-500 flex items-center gap-2 truncate font-bold hover:underline">
                                        {contact.website_url}
                                        <Link2 size={12} />
                                    </a>
                                {:else}
                                    <p class="font-bold">--</p>
                                {/if}
                            </div>
                        </div>
                    </div>

                    <div
                        class="card preset-tonal-surface border-surface-500/10 space-y-6 border p-6 shadow-xl">
                        <h3
                            class="h4 border-surface-500/30 flex items-center gap-2 border-b pb-2 font-bold">
                            <Phone size={20} class="text-secondary-500" />
                            Communication & Social
                        </h3>
                        <div class="grid grid-cols-1 gap-6 md:grid-cols-2">
                            <div class="space-y-1">
                                <p
                                    class="flex items-center gap-1 text-[10px] font-black tracking-widest uppercase opacity-60">
                                    <Phone size={10} /> Mobile Phone
                                </p>
                                <p class="font-mono font-bold">
                                    {contact.phone_mobile ||
                                        contact.phone ||
                                        '--'}
                                </p>
                            </div>
                            <div class="space-y-1">
                                <p
                                    class="flex items-center gap-1 text-[10px] font-black tracking-widest uppercase opacity-60">
                                    <Phone size={10} /> Office Phone
                                </p>
                                <p class="font-mono font-bold">
                                    {contact.phone_office || '--'}
                                </p>
                            </div>
                            <div class="space-y-1">
                                <p
                                    class="flex items-center gap-1 text-[10px] font-black tracking-widest uppercase opacity-60">
                                    <Linkedin size={10} /> LinkedIn
                                </p>
                                <p class="truncate font-bold">
                                    {contact.linkedin_url || '--'}
                                </p>
                            </div>
                            <div class="space-y-2 md:col-span-2">
                                <p
                                    class="flex items-center gap-1 text-[10px] font-black tracking-widest uppercase opacity-60">
                                    <Info size={10} /> Internal Notes
                                </p>
                                <div
                                    class="border-surface-500/20 min-h-[80px] rounded-xl border border-dashed bg-black/5 p-4 italic opacity-80">
                                    {contact.notes ||
                                        'No internal notes provided for this contact.'}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="space-y-6">
                    <div
                        class="card preset-tonal-surface border-surface-500/10 space-y-6 border p-6 shadow-xl">
                        <h3
                            class="h4 border-surface-500/30 flex items-center gap-2 border-b pb-2 font-bold">
                            <ShieldCheck size={20} class="text-warning-500" />
                            Status & Flags
                        </h3>
                        <div class="space-y-4">
                            <div
                                class="flex items-center justify-between rounded-lg bg-black/5 p-3">
                                <span class="text-sm font-bold opacity-75"
                                    >Enabled</span>
                                <span
                                    class="badge {contact.enable
                                        ? 'preset-filled-success'
                                        : 'preset-filled-error'} px-4 py-1 shadow-sm">
                                    {contact.enable ? 'ACTIVE' : 'DISABLED'}
                                </span>
                            </div>
                            <div
                                class="flex items-center justify-between rounded-lg bg-black/5 p-3">
                                <span class="text-sm font-bold opacity-75"
                                    >Hidden</span>
                                <span
                                    class="badge {contact.hide
                                        ? 'preset-filled-warning'
                                        : 'preset-filled-surface'} px-4 py-1 shadow-sm">
                                    {contact.hide ? 'YES' : 'NO'}
                                </span>
                            </div>
                            <div
                                class="flex items-center justify-between rounded-lg bg-black/5 p-3">
                                <span class="text-sm font-bold opacity-75"
                                    >Priority</span>
                                <span
                                    class="badge {contact.priority
                                        ? 'preset-filled-secondary'
                                        : 'preset-filled-surface'} px-4 py-1 shadow-sm">
                                    {contact.priority ? 'YES' : 'NO'}
                                </span>
                            </div>
                        </div>
                    </div>

                    <div
                        class="card preset-tonal-surface border-surface-500/10 space-y-3 border p-5 shadow-inner">
                        <p
                            class="border-surface-500/20 border-b pb-1 text-[10px] font-black tracking-widest uppercase opacity-40">
                            System Audit
                        </p>
                        <div class="space-y-2 font-mono text-[10px] opacity-60">
                            <p class="flex justify-between">
                                <span>ID:</span>
                                <span class="text-primary-500 font-bold"
                                    >{contact.contact_id}</span>
                            </p>
                            <p class="flex justify-between">
                                <span>Created:</span>
                                <span
                                    >{new Date(
                                        contact.created_on
                                    ).toLocaleString()}</span>
                            </p>
                            {#if contact.updated_on}
                                <p class="flex justify-between">
                                    <span>Updated:</span>
                                    <span
                                        >{new Date(
                                            contact.updated_on
                                        ).toLocaleString()}</span>
                                </p>
                            {/if}
                        </div>
                    </div>
                </div>
            </div>
        {/if}
    {/if}
</div>
