<script lang="ts">
    /**
     * Address Form Component
     * Standardized 2026-01-09 for Core UI Polish.
     * Uses unified ae_Address type and Svelte 5 Runes.
     */
    import { ae_api, ae_loc } from '$lib/stores/ae_stores';
    import { update_ae_obj__address, create_ae_obj__address } from '$lib/ae_core/ae_core__address';
    import type { ae_Address } from '$lib/types/ae_types';
    import { Save, X, MapPin, Globe, Clock, Navigation } from 'lucide-svelte';

    interface Props {
        address?: ae_Address | null;
        onSave?: (address: ae_Address) => void;
        onCancel?: () => void;
    }

    let { address = null, onSave, onCancel }: Props = $props();

    // Form State (Runes)
    let formData = $state({
        attention_to: '',
        organization_name: '',
        line_1: '',
        line_2: '',
        line_3: '',
        city: '',
        state_province: '',
        postal_code: '',
        country: '',
        timezone: '',
        latitude: '',
        longitude: '',
        notes: '',
        enable: true,
        hide: false,
        priority: false
    });

    // Reset form when address prop changes
    $effect(() => {
        formData.attention_to = address?.attention_to ?? '';
        formData.organization_name = address?.organization_name ?? '';
        formData.line_1 = address?.line_1 ?? '';
        formData.line_2 = address?.line_2 ?? '';
        formData.line_3 = address?.line_3 ?? '';
        formData.city = address?.city ?? '';
        formData.state_province = address?.state_province ?? '';
        formData.postal_code = address?.postal_code ?? '';
        formData.country = address?.country ?? '';
        formData.timezone = address?.timezone ?? '';
        formData.latitude = address?.latitude ?? '';
        formData.longitude = address?.longitude ?? '';
        formData.notes = address?.notes ?? '';
        formData.enable = address?.enable ?? true;
        formData.hide = address?.hide ?? false;
        formData.priority = address?.priority ?? false;
    });

    let is_loading = $state(false);
    let error_msg = $state('');

    async function handleSubmit(event: Event) {
        event.preventDefault();
        is_loading = true;
        error_msg = '';

        // Surgical Payload
        const payload: any = { ...formData };
        for (const key in payload) {
            if (typeof payload[key] === 'string' && payload[key].trim() === '') {
                // line_1 and city are likely required, but we'll trim them
                if (key === 'line_1' || key === 'city') {
                    payload[key] = payload[key].trim();
                } else {
                    payload[key] = null;
                }
            }
        }

        try {
            let result;
            if (address?.address_id_random) {
                // Update existing
                result = await update_ae_obj__address({
                    api_cfg: $ae_api,
                    address_id: address.address_id_random,
                    data_kv: payload,
                    log_lvl: 1
                });
            } else {
                // Create new
                result = await create_ae_obj__address({
                    api_cfg: $ae_api,
                    account_id: $ae_loc.account_id,
                    data_kv: payload,
                    log_lvl: 1
                });
            }

            if (result) {
                if (onSave) onSave(result);
            } else {
                error_msg = 'Failed to save address record.';
            }
        } catch (err: any) {
            error_msg = err.message || 'An error occurred while saving.';
        } finally {
            is_loading = false;
        }
    }
</script>

<form onsubmit={handleSubmit} class="card p-6 space-y-6 shadow-xl variant-glass-surface">
    <header class="flex justify-between items-center border-b border-surface-500/30 pb-4">
        <h3 class="h3 flex items-center gap-2">
            <MapPin size={24} />
            {address ? 'Edit Address' : 'Create New Address'}
        </h3>
        <div class="flex gap-2">
            {#if onCancel}
                <button type="button" class="btn btn-sm variant-soft-surface" onclick={onCancel}>
                    <X size={16} class="mr-1" /> Cancel
                </button>
            {/if}
            <button type="submit" class="btn btn-sm variant-filled-primary font-bold shadow-lg" disabled={is_loading}>
                {#if is_loading}
                    <span class="animate-spin mr-2">⏳</span>
                {:else}
                    <Save size={16} class="mr-1" />
                {/if}
                Save Address
            </button>
        </div>
    </header>

    {#if error_msg}
        <aside class="alert variant-filled-error">
            <div class="alert-message">
                <p>{error_msg}</p>
            </div>
        </aside>
    {/if}

    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
        <!-- Location Section -->
        <fieldset class="space-y-4">
            <legend class="text-sm font-bold uppercase tracking-widest opacity-60">Location Details</legend>

            <div class="space-y-1">
                <label class="label text-xs font-bold opacity-75">Attention To / Name</label>
                <input class="input variant-filled-surface rounded-lg placeholder-surface-400 p-2" type="text" bind:value={formData.attention_to} placeholder="John Doe" />
            </div>

            <div class="space-y-1">
                <label class="label text-xs font-bold opacity-75">Organization Name</label>
                <input class="input variant-filled-surface rounded-lg placeholder-surface-400 p-2" type="text" bind:value={formData.organization_name} placeholder="Acme Corp" />
            </div>

            <div class="space-y-1">
                <label class="label text-xs font-bold opacity-75">Address Line 1</label>
                <input class="input variant-filled-surface rounded-lg placeholder-surface-400 p-2" type="text" bind:value={formData.line_1} required placeholder="123 Main St" />
            </div>

            <div class="grid grid-cols-2 gap-2">
                <div class="space-y-1">
                    <label class="label text-xs font-bold opacity-75">Line 2</label>
                    <input class="input variant-filled-surface rounded-lg placeholder-surface-400 p-2" type="text" bind:value={formData.line_2} placeholder="Suite 100" />
                </div>
                <div class="space-y-1">
                    <label class="label text-xs font-bold opacity-75">Line 3</label>
                    <input class="input variant-filled-surface rounded-lg placeholder-surface-400 p-2" type="text" bind:value={formData.line_3} placeholder="Floor 2" />
                </div>
            </div>
        </fieldset>

        <!-- Region Section -->
        <fieldset class="space-y-4">
            <legend class="text-sm font-bold uppercase tracking-widest opacity-60">Region & Code</legend>

            <div class="grid grid-cols-2 gap-2">
                <div class="space-y-1">
                    <label class="label text-xs font-bold opacity-75">City</label>
                    <input class="input variant-filled-surface rounded-lg placeholder-surface-400 p-2" type="text" bind:value={formData.city} required placeholder="Metropolis" />
                </div>
                <div class="space-y-1">
                    <label class="label text-xs font-bold opacity-75">State / Province</label>
                    <input class="input variant-filled-surface rounded-lg placeholder-surface-400 p-2" type="text" bind:value={formData.state_province} placeholder="NY" />
                </div>
            </div>

            <div class="grid grid-cols-2 gap-2">
                <div class="space-y-1">
                    <label class="label text-xs font-bold opacity-75">Postal Code</label>
                    <input class="input variant-filled-surface rounded-lg placeholder-surface-400 p-2" type="text" bind:value={formData.postal_code} placeholder="12345" />
                </div>
                <div class="space-y-1">
                    <label class="label text-xs font-bold opacity-75">Country (Code)</label>
                    <div class="input-group input-group-divider grid-cols-[auto_1fr] variant-filled-surface rounded-lg overflow-hidden">
                        <div class="input-group-shim"><Globe size={16} /></div>
                        <input class="bg-transparent border-0 ring-0 focus:ring-0 placeholder-surface-400 p-2" type="text" bind:value={formData.country} placeholder="USA" />
                    </div>
                </div>
            </div>
        </fieldset>

        <!-- Technical Section -->
        <fieldset class="space-y-4">
            <legend class="text-sm font-bold uppercase tracking-widest opacity-60">Technical & GIS</legend>

            <div class="space-y-1">
                <label class="label text-xs font-bold opacity-75">Timezone</label>
                <div class="input-group input-group-divider grid-cols-[auto_1fr] variant-filled-surface rounded-lg overflow-hidden">
                    <div class="input-group-shim"><Clock size={16} /></div>
                    <input class="bg-transparent border-0 ring-0 focus:ring-0 placeholder-surface-400 p-2" type="text" bind:value={formData.timezone} placeholder="America/New_York" />
                </div>
            </div>

            <div class="grid grid-cols-2 gap-2">
                <div class="space-y-1">
                    <label class="label text-xs font-bold opacity-75">Latitude</label>
                    <div class="input-group input-group-divider grid-cols-[auto_1fr] variant-filled-surface rounded-lg overflow-hidden">
                        <div class="input-group-shim"><Navigation size={16} /></div>
                        <input class="bg-transparent border-0 ring-0 focus:ring-0 placeholder-surface-400 p-2" type="text" bind:value={formData.latitude} placeholder="40.7128" />
                    </div>
                </div>
                <div class="space-y-1">
                    <label class="label text-xs font-bold opacity-75">Longitude</label>
                    <div class="input-group input-group-divider grid-cols-[auto_1fr] variant-filled-surface rounded-lg overflow-hidden">
                        <div class="input-group-shim"><Navigation size={16} /></div>
                        <input class="bg-transparent border-0 ring-0 focus:ring-0 placeholder-surface-400 p-2" type="text" bind:value={formData.longitude} placeholder="-74.0060" />
                    </div>
                </div>
            </div>
        </fieldset>

        <!-- Status Section -->
        <fieldset class="space-y-4">
            <legend class="text-sm font-bold uppercase tracking-widest opacity-60">Status</legend>

            <div class="flex flex-wrap gap-4 pt-2">
                <label class="flex items-center space-x-2 cursor-pointer">
                    <input class="checkbox" type="checkbox" bind:checked={formData.enable} />
                    <span class="text-sm font-medium">Enabled</span>
                </label>
                <label class="flex items-center space-x-2 cursor-pointer">
                    <input class="checkbox" type="checkbox" bind:checked={formData.hide} />
                    <span class="text-sm font-medium">Hidden</span>
                </label>
                <label class="flex items-center space-x-2 cursor-pointer">
                    <input class="checkbox" type="checkbox" bind:checked={formData.priority} />
                    <span class="text-sm font-medium">Priority</span>
                </label>
            </div>

            <div class="space-y-1">
                <label class="label text-xs font-bold opacity-75">Internal Notes</label>
                <textarea class="textarea variant-filled-surface rounded-lg placeholder-surface-400 p-2" rows="2" bind:value={formData.notes} placeholder="Notes about this address..."></textarea>
            </div>
        </fieldset>
    </div>

    <footer class="flex justify-end gap-2 border-t border-surface-500/30 pt-4">
        <button type="submit" class="btn variant-filled-primary font-bold shadow-lg w-full md:w-auto" disabled={is_loading}>
            {#if is_loading}
                <span class="animate-spin mr-2">⏳</span>
            {/if}
            {address ? 'Update Address Record' : 'Create Address Record'}
        </button>
    </footer>
</form>
