<script lang="ts">
import { onMount } from 'svelte';
import { page } from '$app/stores';
import {
    load_ae_obj_id__account,
    load_ae_obj_li__account,
    update_ae_obj__account,
    delete_ae_obj_id__account
} from '$lib/ae_core/ae_core__account';
import { db_core } from '$lib/ae_core/db_core';
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 {
    Activity,
    ArrowLeft,
    Building,
    Info,
    Save,
    Settings,
    Trash2
} from '@lucide/svelte';
let account_id = $derived($page.params.account_id ?? '');
let account: any = $state(null);
let loading = $state(true);
let saving = $state(false);
let save_success = $state(false);
let confirm_action = $state<string | null>(null);
let load_error = $state<string | null>(null);
let loaded_from_list_fallback = $state(false);
let loaded_from_local_cache = $state(false);

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

        if (!account) {
            const account_li = await load_ae_obj_li__account({
                api_cfg: $ae_api,
                enabled: 'all',
                hidden: 'all',
                try_cache: false,
                log_lvl: 0
            });

            const account_from_list =
                account_li?.find((a: any) => a.account_id === account_id) ??
                null;

            if (account_from_list) {
                account = account_from_list;
                loaded_from_list_fallback = true;
            }

            const cached_account = await db_core.account
                .where('account_id')
                .equals(account_id)
                .first();

            if (!account && cached_account) {
                account = cached_account;
                loaded_from_local_cache = true;
            }

            if (!account) {
                load_error =
                    'Unable to load this account. Authentication or permissions may be missing for this record.';
            }
        }
    } catch (error) {
        console.error('Failed to load account:', error);
        load_error =
            'Unable to load this account due to a network or API error. Please retry.';
    } finally {
        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) {
        save_success = true;
        setTimeout(() => (save_success = false), 2500);
    }
    saving = false;
}

async function handle_delete() {
    if (confirm_action !== 'disable_account') {
        confirm_action = 'disable_account';
        return;
    }
    confirm_action = null;

    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 space-y-6 p-4">
    <header
        class="bg-surface-50-900-token border-surface-500/10 flex items-center justify-between rounded-xl border p-4 shadow-lg">
        <div class="flex items-center gap-4">
            <a
                class="btn btn-sm preset-tonal-surface shadow-sm"
                href="/core/accounts">
                <ArrowLeft size={16} />
            </a>
            <div class="flex items-center gap-2">
                <div class="bg-primary-500/10 rounded-lg p-2">
                    <Building size={24} class="text-primary-500" />
                </div>
                <h1 class="h2 font-black tracking-tight">
                    {account?.name ?? 'Loading...'}
                </h1>
            </div>
        </div>
        <div class="flex items-center gap-2">
            {#if confirm_action === 'disable_account'}
                <span class="text-sm font-bold text-red-600">Disable this account?</span>
                <button
                    class="btn btn-sm preset-filled-error font-bold shadow-lg"
                    onclick={handle_delete}
                    disabled={loading || saving}>
                    <Trash2 size={16} class="mr-2" /> Confirm Disable
                </button>
                <button
                    class="btn btn-sm preset-tonal-surface"
                    onclick={() => (confirm_action = null)}>
                    Cancel
                </button>
            {:else}
                <button
                    class="btn btn-sm preset-filled-error font-bold shadow-lg"
                    onclick={handle_delete}
                    disabled={loading || saving}>
                    <Trash2 size={16} class="mr-2" /> Disable
                </button>
            {/if}
            {#if save_success}
                <span class="flex items-center gap-1 text-sm font-bold text-green-600">
                    <Info size={16} /> Saved
                </span>
            {/if}
            <button
                class="btn btn-sm preset-filled-primary font-bold shadow-lg"
                onclick={handle_save}
                disabled={loading || saving}>
                {#if saving}
                    <span class="mr-2 animate-spin">⏳</span>
                {:else}
                    <Save size={16} class="mr-2" />
                {/if}
                Save Changes
            </button>
        </div>
    </header>

    {#if loading}
        <div class="card flex h-64 items-center justify-center p-8">
            <div class="placeholder h-full w-full animate-pulse rounded-2xl">
            </div>
        </div>
    {:else if load_error}
        <div
            class="card border-error-500/30 bg-error-500/5 flex flex-col items-start gap-3 border p-6 shadow-xl">
            <h3 class="h4 font-black text-error-600">Account Load Failed</h3>
            <p class="text-sm opacity-80">{load_error}</p>
            {#if !$ae_loc.jwt}
                <p class="text-xs opacity-70">
                    This session is using manager passcode access (no JWT). Some account-by-id API routes may require stronger auth than list views.
                </p>
            {/if}
            <div class="flex flex-wrap gap-2 pt-1">
                <button
                    class="btn btn-sm preset-filled-primary"
                    onclick={load_account}>
                    Retry
                </button>
                <a class="btn btn-sm preset-tonal-surface" href="/core/accounts">
                    Back to Accounts
                </a>
            </div>
        </div>
    {:else if account}
        {#if loaded_from_list_fallback || loaded_from_local_cache}
            <div
                class="card border-warning-500/30 bg-warning-500/5 mb-2 flex items-start gap-3 border p-4 shadow-sm">
                <p class="text-sm opacity-80">
                    {#if loaded_from_local_cache}
                        This record loaded from local cache because direct account API access is currently restricted for this session.
                    {:else}
                        This record loaded from the account list fallback because direct account-by-id API access is currently restricted for this session.
                    {/if}
                </p>
            </div>
        {/if}
        <div class="grid grid-cols-1 gap-6 md:grid-cols-2">
            <div
                class="card preset-tonal-surface border-surface-500/10 space-y-4 border p-6 shadow-xl">
                <h3
                    class="h4 border-surface-500/30 flex items-center gap-2 border-b pb-2 font-bold">
                    <Info size={18} class="text-primary-500" /> Basic Information
                </h3>
                <div class="space-y-4">
                    <div class="space-y-1">
                        <span
                            class="label ml-1 block text-xs font-bold tracking-wider uppercase opacity-75"
                            >Account Name</span>
                        <input
                            class="input preset-filled-surface rounded-lg p-3"
                            type="text"
                            bind:value={account.name} />
                    </div>
                    <div class="space-y-1">
                        <span
                            class="label ml-1 block text-xs font-bold tracking-wider uppercase opacity-75"
                            >Short Name</span>
                        <input
                            class="input preset-filled-surface rounded-lg p-3"
                            type="text"
                            bind:value={account.short_name} />
                    </div>
                    <div class="space-y-1">
                        <span
                            class="label ml-1 block text-xs font-bold tracking-wider uppercase opacity-75"
                            >Account Code</span>
                        <input
                            class="input preset-filled-surface rounded-lg p-3 font-mono"
                            type="text"
                            bind:value={account.code} />
                    </div>
                    <div class="space-y-1">
                        <span
                            class="label ml-1 block text-xs font-bold tracking-wider uppercase opacity-75"
                            >Description</span>
                        <textarea
                            class="textarea preset-filled-surface rounded-lg p-3"
                            rows="3"
                            bind:value={account.description}></textarea>
                    </div>
                </div>
            </div>

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

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