<script lang="ts">
    import { onMount } from 'svelte';
    import { page } from '$app/stores';
    import { load_ae_obj_id__account, update_ae_obj__account, delete_ae_obj_id__account } from '$lib/ae_core/ae_core__account';
    import { editable_fields__account } from '$lib/ae_core/ae_core__account.editable_fields';
    import { ae_api, ae_loc } from '$lib/stores/ae_stores';
    import { goto } from '$app/navigation';
    import { Save, Trash2, ArrowLeft, Building, Settings, Activity, Info } from 'lucide-svelte';

    let account_id = $derived($page.params.account_id ?? '');
    let account: any = $state(null);
    let loading = $state(true);
    let saving = $state(false);

    async function load_account() {
        loading = true;
        account = await load_ae_obj_id__account({
            api_cfg: $ae_api,
            account_id,
            log_lvl: 1
        });
        loading = false;
    }

    onMount(() => {
        if (!$ae_loc.manager_access) {
            goto('/core');
            return;
        }
        load_account();
    });

    async function handle_save() {
        saving = true;
        // Filter fields to only include editable ones
        const data_kv: any = {};
        editable_fields__account.forEach(field => {
            if (account[field] !== undefined) {
                data_kv[field] = account[field];
            }
        });

        const result = await update_ae_obj__account({
            api_cfg: $ae_api,
            account_id,
            data_kv,
            log_lvl: 1
        });

        if (result) {
            alert('Account updated successfully');
        }
        saving = false;
    }

    async function handle_delete() {
        if (!confirm('Are you sure you want to disable this account?')) return;
        
        const result = await delete_ae_obj_id__account({
            api_cfg: $ae_api,
            account_id,
            method: 'disable',
            log_lvl: 1
        });

        if (result) {
            goto('/core/accounts');
        }
    }
</script>

<div class="container mx-auto p-4 space-y-6">
    <header class="flex justify-between items-center bg-surface-50-900-token p-4 rounded-xl shadow-lg border border-surface-500/10">
        <div class="flex items-center gap-4">
            <a class="btn btn-sm variant-soft-surface shadow-sm" href="/core/accounts">
                <ArrowLeft size={16} />
            </a>
            <div class="flex items-center gap-2">
                <div class="p-2 bg-primary-500/10 rounded-lg">
                    <Building size={24} class="text-primary-500" />
                </div>
                <h1 class="h2 font-black tracking-tight">{account?.name ?? 'Loading...'}</h1>
            </div>
        </div>
        <div class="flex gap-2">
            <button class="btn btn-sm variant-filled-error font-bold shadow-lg" onclick={handle_delete} disabled={loading || saving}>
                <Trash2 size={16} class="mr-2" /> Disable
            </button>
            <button class="btn btn-sm variant-filled-primary font-bold shadow-lg" onclick={handle_save} disabled={loading || saving}>
                {#if saving}
                    <span class="animate-spin mr-2">⏳</span>
                {:else}
                    <Save size={16} class="mr-2" />
                {/if}
                Save Changes
            </button>
        </div>
    </header>

    {#if loading}
        <div class="card p-8 flex justify-center items-center h-64">
            <div class="placeholder animate-pulse w-full h-full rounded-2xl"></div>
        </div>
    {:else if account}
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div class="card p-6 space-y-4 shadow-xl variant-glass-surface border border-surface-500/10">
                <h3 class="h4 font-bold border-b border-surface-500/30 pb-2 flex items-center gap-2">
                    <Info size={18} class="text-primary-500" /> Basic Information
                </h3>
                <div class="space-y-4">
                    <div class="space-y-1">
                        <span class="label block text-xs font-bold opacity-75 uppercase tracking-wider ml-1">Account Name</span>
                        <input class="input variant-filled-surface rounded-lg p-3" type="text" bind:value={account.name} />
                    </div>
                    <div class="space-y-1">
                        <span class="label block text-xs font-bold opacity-75 uppercase tracking-wider ml-1">Short Name</span>
                        <input class="input variant-filled-surface rounded-lg p-3" type="text" bind:value={account.short_name} />
                    </div>
                    <div class="space-y-1">
                        <span class="label block text-xs font-bold opacity-75 uppercase tracking-wider ml-1">Account Code</span>
                        <input class="input variant-filled-surface rounded-lg font-mono p-3" type="text" bind:value={account.code} />
                    </div>
                    <div class="space-y-1">
                        <span class="label block text-xs font-bold opacity-75 uppercase tracking-wider ml-1">Description</span>
                        <textarea class="textarea variant-filled-surface rounded-lg p-3" rows="3" bind:value={account.description}></textarea>
                    </div>
                </div>
            </div>

            <div class="card p-6 space-y-4 shadow-xl variant-glass-surface border border-surface-500/10">
                <h3 class="h4 font-bold border-b border-surface-500/30 pb-2 flex items-center gap-2">
                    <Settings size={18} class="text-secondary-500" /> Settings & Status
                </h3>
                <div class="flex flex-col gap-4 py-2">
                    <label class="flex items-center space-x-3 cursor-pointer group">
                        <input class="checkbox" type="checkbox" bind:checked={account.enable} />
                        <span class="text-sm font-bold opacity-70 group-hover:opacity-100 transition-opacity">Enabled</span>
                    </label>
                    <label class="flex items-center space-x-3 cursor-pointer group">
                        <input class="checkbox" type="checkbox" bind:checked={account.hide} />
                        <span class="text-sm font-bold opacity-70 group-hover:opacity-100 transition-opacity">Hidden</span>
                    </label>
                    <label class="flex items-center space-x-3 cursor-pointer group">
                        <input class="checkbox" type="checkbox" bind:checked={account.priority} />
                        <span class="text-sm font-bold opacity-70 group-hover:opacity-100 transition-opacity">Priority Account</span>
                    </label>
                </div>
                <div class="space-y-4 border-t border-surface-500/30 pt-4">
                    <div class="space-y-1">
                        <span class="label block text-xs font-bold opacity-75 uppercase tracking-wider ml-1">Group</span>
                        <input class="input variant-filled-surface rounded-lg p-3" type="text" bind:value={account.group} />
                    </div>
                    <div class="space-y-1">
                        <span class="label block text-xs font-bold opacity-75 uppercase tracking-wider ml-1">Sort Order</span>
                        <input class="input variant-filled-surface rounded-lg p-3" type="number" bind:value={account.sort} />
                    </div>
                </div>
            </div>

            <div class="card p-6 space-y-4 md:col-span-2 shadow-xl variant-glass-surface border border-surface-500/10">
                <h3 class="h4 font-bold border-b border-surface-500/30 pb-2 flex items-center gap-2">
                    <Activity size={18} class="text-tertiary-500" /> Internal Notes
                </h3>
                <div class="space-y-1">
                    <textarea class="textarea variant-filled-surface rounded-lg p-3" rows="4" bind:value={account.notes} placeholder="Private notes for staff..."></textarea>
                </div>
            </div>
        </div>
    {/if}
</div>
