<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 { Clock, Globe, MapPin, Navigation, Save, X } 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) {
            // Update existing
            result = await update_ae_obj__address({
                api_cfg: $ae_api,
                address_id: address.address_id,
                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 preset-tonal-surface space-y-6 p-6 shadow-xl">
    <header
        class="border-surface-500/30 flex items-center justify-between border-b 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 preset-tonal-surface"
                    onclick={onCancel}>
                    <X size={16} class="mr-1" /> Cancel
                </button>
            {/if}
            <button
                type="submit"
                class="btn btn-sm preset-filled-primary font-bold shadow-lg"
                disabled={is_loading}>
                {#if is_loading}
                    <span class="mr-2 animate-spin">⏳</span>
                {:else}
                    <Save size={16} class="mr-1" />
                {/if}
                Save Address
            </button>
        </div>
    </header>

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

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

            <div class="space-y-1">
                <label
                    class="label text-xs font-bold opacity-75"
                    for="addr-attention-to">Attention To / Name</label>
                <input
                    class="input preset-filled-surface placeholder-surface-400 rounded-lg p-2"
                    id="addr-attention-to"
                    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"
                    for="addr-org-name">Organization Name</label>
                <input
                    class="input preset-filled-surface placeholder-surface-400 rounded-lg p-2"
                    id="addr-org-name"
                    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"
                    for="addr-line-1">Address Line 1</label>
                <input
                    class="input preset-filled-surface placeholder-surface-400 rounded-lg p-2"
                    id="addr-line-1"
                    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"
                        for="addr-line-2">Line 2</label>
                    <input
                        class="input preset-filled-surface placeholder-surface-400 rounded-lg p-2"
                        id="addr-line-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"
                        for="addr-line-3">Line 3</label>
                    <input
                        class="input preset-filled-surface placeholder-surface-400 rounded-lg p-2"
                        id="addr-line-3"
                        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 tracking-widest uppercase 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"
                        for="addr-city">City</label>
                    <input
                        class="input preset-filled-surface placeholder-surface-400 rounded-lg p-2"
                        id="addr-city"
                        type="text"
                        bind:value={formData.city}
                        required
                        placeholder="Metropolis" />
                </div>
                <div class="space-y-1">
                    <label
                        class="label text-xs font-bold opacity-75"
                        for="addr-state">State / Province</label>
                    <input
                        class="input preset-filled-surface placeholder-surface-400 rounded-lg p-2"
                        id="addr-state"
                        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"
                        for="addr-postal">Postal Code</label>
                    <input
                        class="input preset-filled-surface placeholder-surface-400 rounded-lg p-2"
                        id="addr-postal"
                        type="text"
                        bind:value={formData.postal_code}
                        placeholder="12345" />
                </div>
                <div class="space-y-1">
                    <label
                        class="label text-xs font-bold opacity-75"
                        for="addr-country">Country (Code)</label>
                    <div
                        class="input-group input-group-divider preset-filled-surface grid-cols-[auto_1fr] overflow-hidden rounded-lg">
                        <div class="input-group-shim"><Globe size={16} /></div>
                        <input
                            class="placeholder-surface-400 border-0 bg-transparent p-2 ring-0 focus:ring-0"
                            id="addr-country"
                            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 tracking-widest uppercase opacity-60"
                >Technical & GIS</legend>

            <div class="space-y-1">
                <label
                    class="label text-xs font-bold opacity-75"
                    for="addr-timezone">Timezone</label>
                <div
                    class="input-group input-group-divider preset-filled-surface grid-cols-[auto_1fr] overflow-hidden rounded-lg">
                    <div class="input-group-shim"><Clock size={16} /></div>
                    <input
                        class="placeholder-surface-400 border-0 bg-transparent p-2 ring-0 focus:ring-0"
                        id="addr-timezone"
                        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"
                        for="addr-latitude">Latitude</label>
                    <div
                        class="input-group input-group-divider preset-filled-surface grid-cols-[auto_1fr] overflow-hidden rounded-lg">
                        <div class="input-group-shim">
                            <Navigation size={16} />
                        </div>
                        <input
                            class="placeholder-surface-400 border-0 bg-transparent p-2 ring-0 focus:ring-0"
                            id="addr-latitude"
                            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"
                        for="addr-longitude">Longitude</label>
                    <div
                        class="input-group input-group-divider preset-filled-surface grid-cols-[auto_1fr] overflow-hidden rounded-lg">
                        <div class="input-group-shim">
                            <Navigation size={16} />
                        </div>
                        <input
                            class="placeholder-surface-400 border-0 bg-transparent p-2 ring-0 focus:ring-0"
                            id="addr-longitude"
                            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 tracking-widest uppercase opacity-60"
                >Status</legend>

            <div class="flex flex-wrap gap-4 pt-2">
                <label class="flex cursor-pointer items-center space-x-2">
                    <input
                        class="checkbox"
                        type="checkbox"
                        bind:checked={formData.enable} />
                    <span class="text-sm font-medium">Enabled</span>
                </label>
                <label class="flex cursor-pointer items-center space-x-2">
                    <input
                        class="checkbox"
                        type="checkbox"
                        bind:checked={formData.hide} />
                    <span class="text-sm font-medium">Hidden</span>
                </label>
                <label class="flex cursor-pointer items-center space-x-2">
                    <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"
                    for="addr-notes">Internal Notes</label>
                <textarea
                    class="textarea preset-filled-surface placeholder-surface-400 rounded-lg p-2"
                    id="addr-notes"
                    rows="2"
                    bind:value={formData.notes}
                    placeholder="Notes about this address..."></textarea>
            </div>
        </fieldset>
    </div>

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