<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 {
    Activity,
    ArrowLeft,
    Building2,
    Clock,
    Edit,
    Eye,
    Globe,
    Info,
    MapPin,
    MapPinned,
    Save,
    ShieldCheck,
    Trash2,
    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);
let confirm_action = $state<string | null>(null);

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_action !== 'delete_address') {
        confirm_action = 'delete_address';
        return;
    }
    confirm_action = null;
    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 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/addresses">
                <ArrowLeft size={16} />
            </a>
            <div class="flex items-center gap-3">
                <div class="bg-primary-500/10 rounded-lg p-2">
                    <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 tracking-widest uppercase opacity-50">
                        Address 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_address'}
                <span class="self-center text-sm font-bold text-red-600">Delete this address?</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 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="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">
                            <MapPinned size={20} class="text-primary-500" />
                            Location 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">
                                    <User size={10} /> Attention To
                                </p>
                                <p class="font-bold">
                                    {address.attention_to || '--'}
                                </p>
                            </div>
                            <div class="space-y-1">
                                <p
                                    class="flex items-center gap-1 text-[10px] font-black tracking-widest uppercase opacity-60">
                                    <Building2 size={10} /> Organization
                                </p>
                                <p class="font-bold">
                                    {address.organization_name || '--'}
                                </p>
                            </div>
                            <div
                                class="border-surface-500/10 space-y-1 rounded-xl border bg-black/5 p-4 md:col-span-2">
                                <p
                                    class="text-[10px] font-black tracking-widest uppercase opacity-60">
                                    Street Address
                                </p>
                                <div class="mt-1 space-y-1">
                                    <p
                                        class="text-lg leading-tight font-black tracking-tight">
                                        {address.line_1}
                                    </p>
                                    {#if address.line_2}<p
                                            class="text-lg leading-tight font-black tracking-tight opacity-75">
                                            {address.line_2}
                                        </p>{/if}
                                    {#if address.line_3}<p
                                            class="text-lg leading-tight font-black tracking-tight opacity-50">
                                            {address.line_3}
                                        </p>{/if}
                                </div>
                            </div>
                            <div class="space-y-1">
                                <p
                                    class="flex items-center gap-1 text-[10px] font-black tracking-widest uppercase opacity-60">
                                    <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="flex items-center gap-1 text-[10px] font-black tracking-widest uppercase opacity-60">
                                    <Globe size={10} /> Postal Code / Country
                                </p>
                                <p class="font-bold">
                                    {address.postal_code || '--'} /
                                    <span class="badge preset-tonal-surface"
                                        >{address.country_name ||
                                            address.country ||
                                            '--'}</span>
                                </p>
                            </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">
                            <Activity size={20} class="text-secondary-500" />
                            Technical Details
                        </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">
                                    <Clock size={10} /> Timezone
                                </p>
                                <p class="font-mono">
                                    {address.timezone || '--'}
                                </p>
                            </div>
                            <div class="space-y-1">
                                <p
                                    class="flex items-center gap-1 text-[10px] font-black tracking-widest uppercase opacity-60">
                                    <MapPin size={10} /> Coordinates
                                </p>
                                <p class="font-mono">
                                    {address.latitude || '--'}, {address.longitude ||
                                        '--'}
                                </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">
                                    {address.notes ||
                                        'No internal notes provided for this address.'}
                                </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" />
                            Visibility & Status
                        </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 {address.enable
                                        ? 'preset-filled-success'
                                        : 'preset-filled-error'} px-4 py-1 shadow-sm">
                                    {address.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 {address.hide
                                        ? 'preset-filled-warning'
                                        : 'preset-filled-surface'} px-4 py-1 shadow-sm">
                                    {address.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 {address.priority
                                        ? 'preset-filled-secondary'
                                        : 'preset-filled-surface'} px-4 py-1 shadow-sm">
                                    {address.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"
                                    >{address.address_id}</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>
