<script lang="ts">
import { onMount } from 'svelte';
import { page } from '$app/stores';
import {
    load_ae_obj_id__site,
    update_ae_obj__site,
    delete_ae_obj_id__site,
    load_ae_obj_li__site_domain,
    create_ae_obj__site_domain,
    update_ae_obj__site_domain,
    delete_ae_obj_id__site_domain
} from '$lib/ae_core/ae_core__site';
import { editable_fields__site } from '$lib/ae_core/ae_core__site.editable_fields';
import { editable_fields__site_domain } from '$lib/ae_core/ae_core__site_domain.editable_fields';
import { ae_api, ae_loc } from '$lib/stores/ae_stores';
import { goto } from '$app/navigation';
import {
    Activity,
    ArrowLeft,
    Database,
    ExternalLink,
    Globe,
    Info,
    Key,
    Plus,
    Save,
    Settings,
    Trash2
} from '@lucide/svelte';
import AE_Comp_Site_Config_Editor from '$lib/elements/ae_comp__site_config_editor.svelte';

let site_id = $derived($page.params.site_id ?? '');
let site: any = $state(null);
let domain_li: any[] = $state([]);
let loading = $state(true);
let saving = $state(false);
let confirm_action = $state<string | null>(null);

async function load_data() {
    loading = true;
    site = await load_ae_obj_id__site({
        api_cfg: $ae_api,
        site_id,
        log_lvl: 1
    });
    domain_li = await load_ae_obj_li__site_domain({
        api_cfg: $ae_api,
        site_id,
        enabled: 'all',
        hidden: 'all',
        log_lvl: 1
    });
    loading = false;
}

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

async function handle_save_site() {
    saving = true;
    const data_kv: any = {};
    editable_fields__site.forEach((field) => {
        if (site[field] !== undefined) {
            data_kv[field] = site[field];
        }
    });

    // Keep cfg_json human-readable in DB TEXT columns.
    // Safe here: V3 update_ae_obj only stringifies *_json when the value is an object.
    data_kv.cfg_json = JSON.stringify(site.cfg_json, null, 2);

    await update_ae_obj__site({
        api_cfg: $ae_api,
        site_id,
        data_kv,
        log_lvl: 1
    });
    saving = false;
}

async function handle_add_domain() {
    const fqdn = prompt('Enter new domain (e.g. example.com):');
    if (!fqdn) return;

    await create_ae_obj__site_domain({
        api_cfg: $ae_api,
        site_id,
        data_kv: { fqdn, enable: true },
        log_lvl: 1
    });
    load_data();
}

async function handle_toggle_domain(dom: any) {
    await update_ae_obj__site_domain({
        api_cfg: $ae_api,
        site_id,
        site_domain_id: dom.site_domain_id,
        data_kv: { enable: !dom.enable },
        log_lvl: 1
    });
    load_data();
}

async function handle_delete_domain(dom: any) {
    if (confirm_action !== `delete_domain_${dom.site_domain_id}`) {
        confirm_action = `delete_domain_${dom.site_domain_id}`;
        return;
    }
    confirm_action = null;
    await delete_ae_obj_id__site_domain({
        api_cfg: $ae_api,
        site_id,
        site_domain_id: dom.site_domain_id,
        method: 'delete',
        log_lvl: 1
    });
    load_data();
}
</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/sites">
                <ArrowLeft size={16} />
            </a>
            <div class="flex items-center gap-2">
                <div class="bg-primary-500/10 rounded-lg p-2">
                    <Globe size={24} class="text-primary-500" />
                </div>
                <h1 class="h2 font-black tracking-tight">
                    {site?.name ?? 'Loading...'}
                </h1>
            </div>
        </div>
        <button
            class="btn btn-sm preset-filled-primary font-bold shadow-lg"
            onclick={handle_save_site}
            disabled={loading || saving}>
            {#if saving}
                <span class="mr-2 animate-spin">⏳</span>
            {:else}
                <Save size={16} class="mr-2" />
            {/if}
            Save Site Changes
        </button>
    </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 site}
        <div class="grid grid-cols-1 gap-6 lg:grid-cols-3">
            <!-- Site Config -->
            <div class="space-y-6 lg:col-span-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">
                        <Settings size={18} class="text-primary-500" /> Site Configuration
                    </h3>
                    <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
                        <div class="space-y-1">
                            <span
                                class="label ml-1 block text-xs font-bold tracking-wider uppercase opacity-75"
                                >Site Name</span>
                            <input
                                class="input preset-filled-surface rounded-lg p-3"
                                type="text"
                                bind:value={site.name} />
                        </div>
                        <div class="space-y-1">
                            <span
                                class="label ml-1 block text-xs font-bold tracking-wider uppercase opacity-75"
                                >Site Code</span>
                            <input
                                class="input preset-filled-surface rounded-lg p-3 font-mono"
                                type="text"
                                bind:value={site.code} />
                        </div>
                        <div class="space-y-1 md:col-span-2">
                            <span
                                class="label ml-1 block text-xs font-bold tracking-wider uppercase opacity-75"
                                >Tagline</span>
                            <input
                                class="input preset-filled-surface rounded-lg p-3"
                                type="text"
                                bind:value={site.tagline} />
                        </div>
                        <div class="space-y-1 md:col-span-2">
                            <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="2"
                                bind:value={site.description}></textarea>
                        </div>
                    </div>
                </div>

                <!-- Advanced Site JSON Config -->
                <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">
                        <Database size={18} class="text-warning-500" /> Site Settings
                        (cfg_json)
                    </h3>
                    <AE_Comp_Site_Config_Editor
                        bind:cfg_json={site.cfg_json}
                        on_save={handle_save_site} />
                </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">
                        <Key size={18} class="text-secondary-500" /> Access Control
                    </h3>
                    <div class="flex flex-col gap-4">
                        <label
                            class="group flex cursor-pointer items-center space-x-2">
                            <input
                                class="checkbox"
                                type="checkbox"
                                bind:checked={site.restrict_access} />
                            <span
                                class="text-sm font-bold opacity-70 transition-opacity group-hover:opacity-100"
                                >Restrict Access</span>
                        </label>
                        {#if site.restrict_access}
                            <div class="animate-fade-in max-w-md space-y-1">
                                <span
                                    class="label ml-1 block text-xs font-bold tracking-wider uppercase opacity-75"
                                    >Access Key</span>
                                <input
                                    class="input preset-filled-surface rounded-lg p-3 font-mono"
                                    type="text"
                                    bind:value={site.access_key} />
                            </div>
                        {/if}
                    </div>
                </div>
            </div>

            <!-- Domains Management -->
            <div class="space-y-6">
                <div
                    class="card preset-tonal-surface border-surface-500/10 space-y-4 border p-6 shadow-xl">
                    <header
                        class="border-surface-500/30 flex items-center justify-between border-b pb-2">
                        <h3 class="h4 flex items-center gap-2 font-bold">
                            <Globe size={18} class="text-tertiary-500" /> Site Domains
                        </h3>
                        <button
                            class="btn btn-icon btn-sm preset-filled-secondary shadow-md"
                            onclick={handle_add_domain}
                            title="Add Domain">
                            <Plus size={14} />
                        </button>
                    </header>

                    {#if domain_li.length === 0}
                        <p
                            class="bg-surface-500/5 border-surface-500/20 rounded-lg border-2 border-dashed py-8 text-center text-sm opacity-60">
                            No domains configured.
                        </p>
                    {:else}
                        <div class="space-y-3">
                            {#each domain_li as dom (dom.site_domain_id)}
                                <div
                                    class="card preset-tonal-surface border-surface-500/10 group flex items-center justify-between border p-3 shadow-sm">
                                    <div class="flex flex-col">
                                        <span
                                            class="flex items-center gap-1 text-sm font-bold">
                                            {dom.fqdn}
                                            <a
                                                href="https://{dom.fqdn}"
                                                target="_blank"
                                                rel="noopener noreferrer"
                                                class="opacity-30 transition-opacity group-hover:opacity-100">
                                                <ExternalLink size={12} />
                                            </a>
                                        </span>
                                        <span
                                            class="text-[10px] font-bold tracking-tighter uppercase opacity-50">
                                            Key: <code class="text-primary-500"
                                                >{dom.access_key || '--'}</code>
                                            &bull; {dom.enable
                                                ? 'Active'
                                                : 'Disabled'}
                                        </span>
                                    </div>
                                    <div class="flex items-center gap-1">
                                        <button
                                            class="btn btn-icon btn-sm {dom.enable
                                                ? 'preset-tonal-success'
                                                : 'preset-tonal-error'}"
                                            onclick={() =>
                                                handle_toggle_domain(dom)}
                                            title="Toggle Active">
                                            <Save size={14} />
                                        </button>
                                        {#if confirm_action === `delete_domain_${dom.site_domain_id}`}
                                            <span class="text-xs font-bold text-red-600">Remove {dom.fqdn}?</span>
                                            <button
                                                class="btn btn-icon btn-sm preset-filled-error"
                                                onclick={() => handle_delete_domain(dom)}
                                                title="Confirm Delete">
                                                <Trash2 size={14} />
                                            </button>
                                            <button
                                                class="btn btn-icon btn-sm preset-tonal-surface"
                                                onclick={() => (confirm_action = null)}
                                                title="Cancel">
                                                ✕
                                            </button>
                                        {:else}
                                            <button
                                                class="btn btn-icon btn-sm preset-tonal-error"
                                                onclick={() =>
                                                    handle_delete_domain(dom)}
                                                title="Delete Domain">
                                                <Trash2 size={14} />
                                            </button>
                                        {/if}
                                    </div>
                                </div>
                            {/each}
                        </div>
                    {/if}
                </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">
                        <Activity size={18} class="text-error-500" /> System Status
                    </h3>
                    <div class="space-y-4 py-2">
                        <label
                            class="group flex cursor-pointer items-center space-x-3">
                            <input
                                class="checkbox"
                                type="checkbox"
                                bind:checked={site.enable} />
                            <span
                                class="text-sm font-bold opacity-70 transition-opacity group-hover:opacity-100"
                                >Site Enabled</span>
                        </label>
                        <label
                            class="group flex cursor-pointer items-center space-x-3">
                            <input
                                class="checkbox"
                                type="checkbox"
                                bind:checked={site.hide} />
                            <span
                                class="text-sm font-bold opacity-70 transition-opacity group-hover:opacity-100"
                                >Hidden from Public</span>
                        </label>
                    </div>
                </div>
            </div>
        </div>
    {/if}
</div>
