<script lang="ts">
    import { onMount } from 'svelte';
    import { page } from '$app/stores';
    import {
        load_ae_obj_id__address,
        update_ae_obj__address,
        delete_ae_obj_id__address
    } from '$lib/ae_core/ae_core__address';
    import { editable_fields__address } from '$lib/ae_core/ae_core__address.editable_fields';
    import { ae_api, ae_loc } from '$lib/stores/ae_stores';
    import { goto } from '$app/navigation';
    import { Save, Trash2, ArrowLeft, MapPin, Edit, Eye, Globe, Building2, MapPinned, Info, ShieldCheck, Activity, Clock, User } from 'lucide-svelte';
    import Address_form from '../ae_comp__address_form.svelte';

    let address_id = $derived($page.params.address_id ?? '');
    let address: any = $state(null);
    let loading = $state(true);
    let is_editing = $state(false);

    async function load_data() {
        loading = true;
        address = await load_ae_obj_id__address({
            api_cfg: $ae_api,
            address_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 address?')) return;
        await delete_ae_obj_id__address({
            api_cfg: $ae_api,
            address_id,
            method: 'delete',
            log_lvl: 1
        });
        goto('/core/addresses');
    }
</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/addresses">
                <ArrowLeft size={16} />
            </a>
            <div class="flex items-center gap-3">
                <div class="p-2 bg-primary-500/10 rounded-lg">
                    <MapPin size={24} class="text-primary-500" />
                </div>
                <div>
                    <h1 class="h2 font-black tracking-tight">{address ? `${address.city}, ${address.state_province}` : 'Loading...'}</h1>
                    <p class="text-xs font-bold opacity-50 uppercase tracking-widest">Address 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 address}
        {#if is_editing}
            <div class="animate-fade-in">
                <Address_form 
                    {address} 
                    onSave={(updated) => {
                        address = 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">
                            <MapPinned size={20} class="text-primary-500" />
                            Location 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">
                                    <User size={10} /> Attention To
                                </p>
                                <p class="font-bold">{address.attention_to || '--'}</p>
                            </div>
                            <div class="space-y-1">
                                <p class="text-[10px] opacity-60 uppercase font-black tracking-widest flex items-center gap-1">
                                    <Building2 size={10} /> Organization
                                </p>
                                <p class="font-bold">{address.organization_name || '--'}</p>
                            </div>
                            <div class="md:col-span-2 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">Street Address</p>
                                <div class="space-y-1 mt-1">
                                    <p class="text-lg font-black tracking-tight leading-tight">{address.line_1}</p>
                                    {#if address.line_2}<p class="text-lg font-black tracking-tight leading-tight opacity-75">{address.line_2}</p>{/if}
                                    {#if address.line_3}<p class="text-lg font-black tracking-tight leading-tight opacity-50">{address.line_3}</p>{/if}
                                </div>
                            </div>
                            <div class="space-y-1">
                                <p class="text-[10px] opacity-60 uppercase font-black tracking-widest flex items-center gap-1">
                                    <MapPin size={10} /> City, State/Province
                                </p>
                                <p class="font-bold">{address.city}, {address.state_province || '--'}</p>
                            </div>
                            <div class="space-y-1">
                                <p class="text-[10px] opacity-60 uppercase font-black tracking-widest flex items-center gap-1">
                                    <Globe size={10} /> Postal Code / Country
                                </p>
                                <p class="font-bold">{address.postal_code || '--'} / <span class="badge variant-soft-surface">{address.country_name || address.country || '--'}</span></p>
                            </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">
                            <Activity size={20} class="text-secondary-500" />
                            Technical Details
                        </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">
                                    <Clock size={10} /> Timezone
                                </p>
                                <p class="font-mono">{address.timezone || '--'}</p>
                            </div>
                            <div class="space-y-1">
                                <p class="text-[10px] opacity-60 uppercase font-black tracking-widest flex items-center gap-1">
                                    <MapPin size={10} /> Coordinates
                                </p>
                                <p class="font-mono">{address.latitude || '--'}, {address.longitude || '--'}</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]">
                                    {address.notes || 'No internal notes provided for this address.'}
                                </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" />
                            Visibility & Status
                        </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 {address.enable ? 'variant-filled-success' : 'variant-filled-error'} px-4 py-1 shadow-sm">
                                    {address.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 {address.hide ? 'variant-filled-warning' : 'variant-filled-surface'} px-4 py-1 shadow-sm">
                                    {address.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 {address.priority ? 'variant-filled-secondary' : 'variant-filled-surface'} px-4 py-1 shadow-sm">
                                    {address.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">{address.address_id_random}</span></p>
                            <p class="flex justify-between"><span>Created:</span> <span>{new Date(address.created_on).toLocaleString()}</span></p>
                            {#if address.updated_on}
                                <p class="flex justify-between"><span>Updated:</span> <span>{new Date(address.updated_on).toLocaleString()}</span></p>
                            {/if}
                        </div>
                    </div>
                </div>
            </div>
        {/if}
    {/if}
</div>
