<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 { Save, Trash2, ArrowLeft, UserRound, Edit, Eye, Mail, Phone, Globe, Linkedin, Info, ShieldCheck, Activity, Link2, Contact } 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);

    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('Permanently delete this contact?')) return;
        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 p-4 space-y-6">
    <header class="flex flex-wrap justify-between items-center bg-surface-50-900-token p-4 rounded-xl shadow-lg border border-surface-500/10 gap-4">
        <div class="flex items-center gap-4">
            <a class="btn btn-sm variant-soft-surface shadow-sm" href="/core/contacts">
                <ArrowLeft size={16} />
            </a>
            <div class="flex items-center gap-3">
                <div class="p-2 bg-primary-500/10 rounded-lg">
                    <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 opacity-50 uppercase tracking-widest">Contact Detail</p>
                </div>
            </div>
        </div>
        <div class="flex gap-2">
            <button class="btn btn-sm variant-soft-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>
            <button class="btn btn-sm variant-soft-error font-bold shadow-sm" onclick={handle_delete} disabled={loading}>
                <Trash2 size={16} class="mr-2" /> Delete
            </button>
        </div>
    </header>

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

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

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

                    <div class="card p-5 variant-soft-surface shadow-inner border border-surface-500/10 space-y-3">
                        <p class="text-[10px] uppercase font-black opacity-40 tracking-widest border-b border-surface-500/20 pb-1">System Audit</p>
                        <div class="space-y-2 text-[10px] font-mono opacity-60">
                            <p class="flex justify-between"><span>ID:</span> <span class="text-primary-500 font-bold">{contact.contact_id_random}</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>
