<script lang="ts">
/**
 * Contact Form Component
 * Standardized 2026-01-09 for Core UI Polish.
 * Uses unified ae_Contact type and Svelte 5 Runes.
 */
import { ae_api, ae_loc } from '$lib/stores/ae_stores';
import {
    update_ae_obj__contact,
    create_ae_obj__contact
} from '$lib/ae_core/ae_core__contact';
import type { ae_Contact } from '$lib/types/ae_types';
import {
    Facebook,
    Globe,
    Instagram,
    Linkedin,
    Mail,
    Phone,
    Save,
    UserPlus,
    X
} from '@lucide/svelte';
interface Props {
    contact?: ae_Contact | null;
    onSave?: (contact: ae_Contact) => void;
    onCancel?: () => void;
}

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

// Form State (Runes)
let formData = $state({
    title: '',
    tagline: '',
    email: '',
    phone_mobile: '',
    phone_office: '',
    website_url: '',
    facebook_url: '',
    instagram_url: '',
    linkedin_url: '',
    notes: '',
    enable: true,
    hide: false,
    priority: false
});

// Reset form when contact prop changes
$effect(() => {
    formData.title = contact?.title ?? '';
    formData.tagline = contact?.tagline ?? '';
    formData.email = contact?.email ?? '';
    formData.phone_mobile = contact?.phone_mobile ?? '';
    formData.phone_office = contact?.phone_office ?? '';
    formData.website_url = contact?.website_url ?? '';
    formData.facebook_url = contact?.facebook_url ?? '';
    formData.instagram_url = contact?.instagram_url ?? '';
    formData.linkedin_url = contact?.linkedin_url ?? '';
    formData.notes = contact?.notes ?? '';
    formData.enable = contact?.enable ?? true;
    formData.hide = contact?.hide ?? false;
    formData.priority = contact?.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() === '') {
            // title is likely required, but we'll trim it
            if (key === 'title') {
                payload[key] = payload[key].trim();
            } else {
                payload[key] = null;
            }
        }
    }

    try {
        let result;
        if (contact?.contact_id) {
            // Update existing
            result = await update_ae_obj__contact({
                api_cfg: $ae_api,
                contact_id: contact.contact_id,
                data_kv: payload,
                log_lvl: 1
            });
        } else {
            // Create new
            result = await create_ae_obj__contact({
                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 contact 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">
            <UserPlus size={24} />
            {contact ? 'Edit Contact' : 'Create New Contact'}
        </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 Contact
            </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">
        <!-- Identity Section -->
        <fieldset class="space-y-4">
            <legend
                class="text-sm font-bold tracking-widest uppercase opacity-60"
                >Identity & Branding</legend>

            <div class="space-y-1">
                <label
                    class="label text-xs font-bold opacity-75"
                    for="contact-title">Title / Name</label>
                <input
                    class="input preset-filled-surface placeholder-surface-400 rounded-lg p-2"
                    id="contact-title"
                    type="text"
                    bind:value={formData.title}
                    required
                    placeholder="Business Office" />
            </div>

            <div class="space-y-1">
                <label
                    class="label text-xs font-bold opacity-75"
                    for="contact-tagline">Tagline</label>
                <input
                    class="input preset-filled-surface placeholder-surface-400 rounded-lg p-2"
                    id="contact-tagline"
                    type="text"
                    bind:value={formData.tagline}
                    placeholder="Primary contact for business inquiries" />
            </div>

            <div class="space-y-1">
                <label
                    class="label text-xs font-bold opacity-75"
                    for="contact-email">Email Address</label>
                <div
                    class="input-group input-group-divider preset-filled-surface grid-cols-[auto_1fr] overflow-hidden rounded-lg">
                    <div class="input-group-shim"><Mail size={16} /></div>
                    <input
                        class="placeholder-surface-400 border-0 bg-transparent p-2 ring-0 focus:ring-0"
                        id="contact-email"
                        type="email"
                        bind:value={formData.email}
                        placeholder="contact@example.com" />
                </div>
            </div>
        </fieldset>

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

            <div class="grid grid-cols-2 gap-2">
                <div class="space-y-1">
                    <label
                        class="label text-xs font-bold opacity-75"
                        for="contact-phone-mobile">Mobile Phone</label>
                    <div
                        class="input-group input-group-divider preset-filled-surface grid-cols-[auto_1fr] overflow-hidden rounded-lg">
                        <div class="input-group-shim"><Phone size={16} /></div>
                        <input
                            class="placeholder-surface-400 border-0 bg-transparent p-2 ring-0 focus:ring-0"
                            id="contact-phone-mobile"
                            type="tel"
                            bind:value={formData.phone_mobile}
                            placeholder="+1..." />
                    </div>
                </div>
                <div class="space-y-1">
                    <label
                        class="label text-xs font-bold opacity-75"
                        for="contact-phone-office">Office Phone</label>
                    <div
                        class="input-group input-group-divider preset-filled-surface grid-cols-[auto_1fr] overflow-hidden rounded-lg">
                        <div class="input-group-shim"><Phone size={16} /></div>
                        <input
                            class="placeholder-surface-400 border-0 bg-transparent p-2 ring-0 focus:ring-0"
                            id="contact-phone-office"
                            type="tel"
                            bind:value={formData.phone_office}
                            placeholder="+1..." />
                    </div>
                </div>
            </div>

            <div class="space-y-1">
                <label
                    class="label text-xs font-bold opacity-75"
                    for="contact-website">Website URL</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="contact-website"
                        type="url"
                        bind:value={formData.website_url}
                        placeholder="https://..." />
                </div>
            </div>
        </fieldset>

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

            <div class="space-y-1">
                <label
                    class="label text-xs font-bold opacity-75"
                    for="contact-linkedin">LinkedIn URL</label>
                <div
                    class="input-group input-group-divider preset-filled-surface grid-cols-[auto_1fr] overflow-hidden rounded-lg">
                    <div class="input-group-shim"><Linkedin size={16} /></div>
                    <input
                        class="placeholder-surface-400 border-0 bg-transparent p-2 ring-0 focus:ring-0"
                        id="contact-linkedin"
                        type="url"
                        bind:value={formData.linkedin_url}
                        placeholder="https://linkedin.com/in/..." />
                </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="contact-facebook">Facebook URL</label>
                    <div
                        class="input-group input-group-divider preset-filled-surface grid-cols-[auto_1fr] overflow-hidden rounded-lg">
                        <div class="input-group-shim">
                            <Facebook size={16} />
                        </div>
                        <input
                            class="placeholder-surface-400 border-0 bg-transparent p-2 ring-0 focus:ring-0"
                            id="contact-facebook"
                            type="url"
                            bind:value={formData.facebook_url}
                            placeholder="https://facebook.com/..." />
                    </div>
                </div>
                <div class="space-y-1">
                    <label
                        class="label text-xs font-bold opacity-75"
                        for="contact-instagram">Instagram URL</label>
                    <div
                        class="input-group input-group-divider preset-filled-surface grid-cols-[auto_1fr] overflow-hidden rounded-lg">
                        <div class="input-group-shim">
                            <Instagram size={16} />
                        </div>
                        <input
                            class="placeholder-surface-400 border-0 bg-transparent p-2 ring-0 focus:ring-0"
                            id="contact-instagram"
                            type="url"
                            bind:value={formData.instagram_url}
                            placeholder="https://instagram.com/..." />
                    </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="contact-notes">Internal Notes</label>
                <textarea
                    class="textarea preset-filled-surface placeholder-surface-400 rounded-lg p-2"
                    id="contact-notes"
                    rows="2"
                    bind:value={formData.notes}
                    placeholder="Additional details..."></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}
            {contact ? 'Update Contact Record' : 'Create Contact Record'}
        </button>
    </footer>
</form>
