<script lang="ts">
/**
 * Person Form Component
 * Standardized 2026-01-09 for Core UI Polish.
 * Uses unified ae_Person type and Svelte 5 Runes.
 */
import { ae_api, ae_loc } from '$lib/stores/ae_stores';
import { core_func } from '$lib/ae_core/ae_core_functions';
import type { ae_Person } from '$lib/types/ae_types';
import {
    Briefcase,
    Building,
    Link,
    Mail,
    Phone,
    Save,
    Tag,
    User,
    X
} from '@lucide/svelte';
interface Props {
    person?: ae_Person | null;
    onSave?: (person: ae_Person) => void;
    onCancel?: () => void;
}

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

// Form State (Runes)
let formData = $state({
    given_name: '',
    family_name: '',
    middle_name: '',
    prefix: '',
    suffix: '',
    nickname: '',
    professional_title: '',
    affiliations: '',
    primary_email: '',
    phone: '',
    tagline: '',
    notes: '',
    user_id_random: '',
    enable: true,
    hide: false,
    priority: false
});

// Reset form when person prop changes
$effect(() => {
    formData.given_name = person?.given_name ?? '';
    formData.family_name = person?.family_name ?? '';
    formData.middle_name = person?.middle_name ?? '';
    formData.prefix = person?.prefix ?? person?.title_names ?? '';
    formData.suffix = person?.suffix ?? person?.designations ?? '';
    formData.nickname = person?.informal_name ?? '';
    formData.professional_title = person?.professional_title ?? '';
    formData.affiliations = person?.affiliations ?? '';
    formData.primary_email = person?.primary_email ?? '';
    formData.phone = person?.phone ?? '';
    formData.tagline = person?.tagline ?? '';
    formData.notes = person?.notes ?? '';
    formData.user_id_random = person?.user_id_random ?? '';
    formData.enable = person?.enable ?? true;
    formData.hide = person?.hide ?? false;
    formData.priority = person?.priority ?? false;
});

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

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

    // Clean payload: Map fields and handle optional values
    const payload: any = {
        prefix: formData.prefix.trim() || null,
        given_name: formData.given_name.trim(),
        family_name: formData.family_name.trim() || null,
        middle_name: formData.middle_name.trim() || null,
        informal_name: formData.nickname.trim() || null,
        // title_names: formData.prefix.trim() || null, // DO NOT USE - Scott 2026-01-09
        designations: formData.suffix.trim() || null,
        // NOTE:DO NOT USE Do note send the full_name field at this time - Scott 2026-01-09
        // full_name: `${formData.prefix ? formData.prefix + ' ' : ''}${formData.given_name} ${formData.family_name}${formData.suffix ? ', ' + formData.suffix : ''}`.trim(), // DO NOT USE - Scott 2026-01-09
        professional_title: formData.professional_title.trim() || null,
        affiliations: formData.affiliations.trim() || null,
        primary_email: formData.primary_email.trim() || null,
        tagline: formData.tagline.trim() || null,
        notes: formData.notes.trim() || null,
        user_id_random: formData.user_id_random.trim() || null,
        allow_auth_key: true,
        enable: formData.enable,
        hide: formData.hide,
        priority: formData.priority
    };

    // Ensure strings are truly null if empty after trim
    for (const key in payload) {
        if (payload[key] === '') {
            if (key !== 'given_name' && key !== 'full_name') {
                payload[key] = null;
            }
        }
    }

    try {
        let result;
        if (person?.person_id) {
            // Update existing
            result = await core_func.update_ae_obj__person({
                api_cfg: $ae_api,
                person_id: person.person_id,
                data_kv: payload,
                log_lvl: 1
            });
        } else {
            // Create new
            result = await core_func.create_ae_obj__person({
                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 person record. The server rejected the request (400).';
        }
    } 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">
            <User size={24} />
            {person ? 'Edit Person' : 'Create New Person'}
        </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 Person
            </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">
        <!-- Name Section -->
        <fieldset class="space-y-4">
            <legend
                class="text-sm font-bold tracking-widest uppercase opacity-60"
                >Identity</legend>

            <div class="grid grid-cols-4 gap-2">
                <div class="col-span-1 space-y-1">
                    <label
                        class="label text-xs font-bold opacity-75"
                        for="person-prefix">Prefix</label>
                    <input
                        class="input preset-filled-surface placeholder-surface-400 rounded-lg p-2"
                        id="person-prefix"
                        type="text"
                        bind:value={formData.prefix}
                        placeholder="Mr." />
                </div>
                <div class="col-span-3 space-y-1">
                    <label
                        class="label text-xs font-bold opacity-75"
                        for="person-given-name">Given Name</label>
                    <input
                        class="input preset-filled-surface placeholder-surface-400 rounded-lg p-2"
                        id="person-given-name"
                        type="text"
                        bind:value={formData.given_name}
                        required
                        placeholder="Jane" />
                </div>
            </div>

            <div class="grid grid-cols-4 gap-2">
                <div class="col-span-3 space-y-1">
                    <label
                        class="label text-xs font-bold opacity-75"
                        for="person-family-name">Family Name</label>
                    <input
                        class="input preset-filled-surface placeholder-surface-400 rounded-lg p-2"
                        id="person-family-name"
                        type="text"
                        bind:value={formData.family_name}
                        required
                        placeholder="Doe" />
                </div>
                <div class="col-span-1 space-y-1">
                    <label
                        class="label text-xs font-bold opacity-75"
                        for="person-suffix">Suffix</label>
                    <input
                        class="input preset-filled-surface placeholder-surface-400 rounded-lg p-2"
                        id="person-suffix"
                        type="text"
                        bind:value={formData.suffix}
                        placeholder="PhD" />
                </div>
            </div>

            <div class="space-y-1">
                <label
                    class="label text-xs font-bold opacity-75"
                    for="person-middle-name"
                    >Middle Name / Informal Name (Nickname)</label>
                <div class="grid grid-cols-2 gap-2">
                    <input
                        class="input preset-filled-surface placeholder-surface-400 rounded-lg p-2"
                        id="person-middle-name"
                        type="text"
                        bind:value={formData.middle_name}
                        placeholder="Middle" />
                    <input
                        class="input preset-filled-surface placeholder-surface-400 rounded-lg p-2"
                        type="text"
                        bind:value={formData.nickname}
                        placeholder="Nickname" />
                </div>
            </div>
        </fieldset>

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

            <div class="space-y-1">
                <label
                    class="label text-xs font-bold opacity-75"
                    for="person-primary-email">Primary Email</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="person-primary-email"
                        type="email"
                        bind:value={formData.primary_email}
                        placeholder="jane.doe@example.com" />
                </div>
            </div>

            <div class="space-y-1">
                <label
                    class="label text-xs font-bold opacity-75"
                    for="person-phone">Phone Number</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="person-phone"
                        type="tel"
                        bind:value={formData.phone}
                        placeholder="+1 (555) 000-0000" />
                </div>
                <small class="px-1 text-xs opacity-60"
                    >(Saved only locally until Contact created)</small>
            </div>

            <div class="space-y-1">
                <label
                    class="label text-xs font-bold opacity-75"
                    for="person-tagline">Tagline</label>
                <div
                    class="input-group input-group-divider preset-filled-surface grid-cols-[auto_1fr] overflow-hidden rounded-lg">
                    <div class="input-group-shim"><Tag size={16} /></div>
                    <input
                        class="placeholder-surface-400 border-0 bg-transparent p-2 ring-0 focus:ring-0"
                        id="person-tagline"
                        type="text"
                        bind:value={formData.tagline}
                        placeholder="Software Architect & Visionary" />
                </div>
            </div>
        </fieldset>

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

            <div class="space-y-1">
                <label
                    class="label text-xs font-bold opacity-75"
                    for="person-professional-title">Professional Title</label>
                <div
                    class="input-group input-group-divider preset-filled-surface grid-cols-[auto_1fr] overflow-hidden rounded-lg">
                    <div class="input-group-shim"><Briefcase size={16} /></div>
                    <input
                        class="placeholder-surface-400 border-0 bg-transparent p-2 ring-0 focus:ring-0"
                        id="person-professional-title"
                        type="text"
                        bind:value={formData.professional_title}
                        placeholder="Senior Engineer" />
                </div>
            </div>

            <div class="space-y-1">
                <label
                    class="label text-xs font-bold opacity-75"
                    for="person-affiliations">Affiliations</label>
                <div
                    class="input-group input-group-divider preset-filled-surface grid-cols-[auto_1fr] overflow-hidden rounded-lg">
                    <div class="input-group-shim"><Building size={16} /></div>
                    <input
                        class="placeholder-surface-400 border-0 bg-transparent p-2 ring-0 focus:ring-0"
                        id="person-affiliations"
                        type="text"
                        bind:value={formData.affiliations}
                        placeholder="One Sky IT, LLC" />
                </div>
            </div>
        </fieldset>

        <!-- Metadata Section -->
        <fieldset class="space-y-4">
            <legend
                class="text-sm font-bold tracking-widest uppercase opacity-60"
                >Status & Flags</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="person-notes">Notes (Internal)</label>
                <textarea
                    class="textarea preset-filled-surface placeholder-surface-400 rounded-lg p-2"
                    id="person-notes"
                    rows="3"
                    bind:value={formData.notes}
                    placeholder="Additional details..."></textarea>
            </div>
        </fieldset>

        {#if $ae_loc.manager_access}
            <!-- Admin/Linking Section -->
            <fieldset
                class="border-surface-500/30 space-y-4 border-t pt-4 md:col-span-2">
                <legend
                    class="text-sm font-bold tracking-widest uppercase opacity-60"
                    >System Linking (Managers Only)</legend>

                <div class="max-w-md space-y-1">
                    <label
                        class="label text-xs font-bold opacity-75"
                        for="person-user-id-random"
                        >Linked User ID (Random)</label>
                    <div
                        class="input-group input-group-divider preset-filled-surface grid-cols-[auto_1fr] overflow-hidden rounded-lg">
                        <div class="input-group-shim"><Link size={16} /></div>
                        <input
                            class="placeholder-surface-400 border-0 bg-transparent p-2 font-mono ring-0 focus:ring-0"
                            id="person-user-id-random"
                            type="text"
                            bind:value={formData.user_id_random}
                            placeholder="e.g. AB12CD34" />
                    </div>
                    <small
                        class="px-1 text-[10px] tracking-tighter uppercase opacity-60"
                        >Enter the unique random ID of the user account to link
                        to this person.</small>
                </div>
            </fieldset>
        {/if}
    </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}
            {person ? 'Update Person Record' : 'Create Person Record'}
        </button>
    </footer>
</form>
