<script lang="ts">
import { onMount } from 'svelte';
import {
    load_ae_obj_li__site,
    create_ae_obj__site
} from '$lib/ae_core/ae_core__site';
import { ae_api, ae_loc, slct } from '$lib/stores/ae_stores';
import { goto } from '$app/navigation';
import {
    Calendar,
    ExternalLink,
    Globe,
    ListFilter,
    Plus,
    RefreshCcw,
    Search,
    ShieldCheck,
    X
} from '@lucide/svelte';
let site_li: any[] = $state([]);
let loading = $state(true);
let qry_enabled = $state('all');
let qry_hidden = $state('all');
let qry_str = $state('');

let filtered_li = $derived(
    qry_str
        ? site_li.filter(
              (s) =>
                  s.name?.toLowerCase().includes(qry_str.toLowerCase()) ||
                  s.code?.toLowerCase().includes(qry_str.toLowerCase())
          )
        : site_li
);

async function load_sites() {
    if (!$ae_loc.account_id) return;
    loading = true;
    site_li = await load_ae_obj_li__site({
        api_cfg: $ae_api,
        for_obj_id: $ae_loc.account_id,
        enabled: qry_enabled as any,
        hidden: qry_hidden as any,
        log_lvl: 1
    });
    loading = false;
}

onMount(() => {
    load_sites();
});

async function handle_add_site() {
    const name = prompt('Enter new site name:');
    if (!name) return;

    const code = prompt('Enter site code (optional):');

    const new_site = await create_ae_obj__site({
        api_cfg: $ae_api,
        account_id: $ae_loc.account_id,
        data_kv: {
            name,
            code: code || undefined,
            enable: true
        },
        log_lvl: 1
    });

    if (new_site) {
        load_sites();
    }
}
</script>

<div class="container mx-auto space-y-6 p-4">
    <header
        class="bg-surface-50-900-token border-surface-500/10 flex flex-wrap items-center justify-between gap-4 rounded-xl border p-4 shadow-lg">
        <div class="flex items-center gap-3">
            <div class="bg-primary-500/10 rounded-lg p-2">
                <Globe size={24} class="text-primary-500" />
            </div>
            <div>
                <h1 class="h2 font-black tracking-tight">Site Management</h1>
                <p
                    class="text-xs font-bold tracking-widest uppercase opacity-50">
                    Digital Properties & Domains
                </p>
            </div>
        </div>
        <button
            class="btn btn-sm preset-filled-primary font-bold shadow-lg"
            onclick={handle_add_site}>
            <Plus size={16} class="mr-2" /> Add Site
        </button>
    </header>

    <div
        class="card preset-tonal-surface border-surface-500/10 space-y-4 border p-6 shadow-xl">
        <div class="flex flex-wrap items-end gap-6">
            <div class="min-w-[280px] flex-1 space-y-1">
                <span
                    class="label ml-1 block text-xs font-bold tracking-wider uppercase opacity-75"
                    >Search Sites</span>
                <div
                    class="bg-surface-200-700-token border-surface-500/20 group focus-within:ring-primary-500/50 flex overflow-hidden rounded-lg border shadow-inner transition-all focus-within:ring-2">
                    <div
                        class="bg-surface-300-600-token border-surface-500/20 flex items-center justify-center border-r px-4">
                        <Search size={18} class="opacity-50" />
                    </div>
                    <input
                        class="grow border-0 bg-transparent p-3 ring-0 placeholder:opacity-50 focus:ring-0"
                        type="search"
                        bind:value={qry_str}
                        placeholder="Search by name or code..." />
                    <button
                        class="preset-filled-primary border-surface-500/20 flex min-w-[100px] items-center justify-center border-l px-10 py-3 font-bold transition-all hover:brightness-110"
                        onclick={load_sites}
                        disabled={loading}>
                        {#if loading}
                            <span class="animate-spin text-xl">⏳</span>
                        {:else}
                            <span class="tracking-wide whitespace-nowrap"
                                >Refresh</span>
                        {/if}
                    </button>
                </div>
            </div>

            <div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
                <div class="space-y-1">
                    <span
                        class="label ml-1 block text-xs font-bold tracking-wider uppercase opacity-75"
                        >Status</span>
                    <select
                        class="select preset-filled-surface border-surface-500/20 rounded-lg border p-2 text-sm"
                        bind:value={qry_enabled}
                        onchange={load_sites}>
                        <option value="all">All Statuses</option>
                        <option value="enabled">Enabled Only</option>
                        <option value="not_enabled">Disabled Only</option>
                    </select>
                </div>

                <div class="space-y-1">
                    <span
                        class="label ml-1 block text-xs font-bold tracking-wider uppercase opacity-75"
                        >Visibility</span>
                    <select
                        class="select preset-filled-surface border-surface-500/20 rounded-lg border p-2 text-sm"
                        bind:value={qry_hidden}
                        onchange={load_sites}>
                        <option value="all">All Visibility</option>
                        <option value="not_hidden">Not Hidden Only</option>
                        <option value="hidden">Hidden Only</option>
                    </select>
                </div>
            </div>
        </div>
    </div>

    {#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 filtered_li.length === 0}
        <div
            class="card preset-tonal-surface border-surface-500/20 rounded-2xl border-2 border-dashed p-12 text-center">
            <Globe size={48} class="mx-auto mb-4 opacity-20" />
            <h3 class="h3 font-bold opacity-50">No Sites Found</h3>
            <p class="mx-auto mt-2 max-w-xs opacity-60">
                Sites for this account will appear here. Add your first site to
                get started.
            </p>
        </div>
    {:else}
        <div
            class="card preset-tonal-surface border-surface-500/10 border p-6 shadow-xl">
            <h3
                class="h4 border-surface-500/30 mb-6 flex items-center gap-2 border-b pb-2 font-bold">
                <ListFilter size={18} class="text-secondary-500" />
                Linked Properties
                <span class="badge preset-tonal-secondary ml-auto"
                    >{filtered_li.length} found</span>
            </h3>

            <div class="grid grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-3">
                {#each filtered_li as site (site.site_id)}
                    <div
                        class="card preset-tonal-surface border-surface-500/10 hover:border-primary-500/30 group relative space-y-4 border p-5 shadow-md transition-all">
                        <div class="absolute top-4 right-4 flex gap-1">
                            {#if site.hide}
                                <span
                                    class="badge preset-filled-warning text-[8px] font-bold uppercase shadow-sm"
                                    >Hidden</span>
                            {/if}
                            <span
                                class="badge {site.enable
                                    ? 'preset-filled-success'
                                    : 'preset-filled-error'} text-[8px] font-bold uppercase shadow-sm">
                                {site.enable ? 'Active' : 'Disabled'}
                            </span>
                        </div>

                        <header class="flex items-center gap-3">
                            <div
                                class="avatar preset-filled-primary flex h-12 w-12 items-center justify-center rounded-lg shadow-inner transition-transform group-hover:scale-110">
                                <Globe size={24} />
                            </div>
                            <div class="pr-12">
                                <p class="truncate font-black tracking-tight">
                                    {site.name}
                                </p>
                                <p
                                    class="font-mono text-[10px] font-bold tracking-tighter uppercase opacity-50">
                                    Code: {site.code || '--'}
                                </p>
                            </div>
                        </header>

                        <div class="space-y-2 text-xs opacity-70">
                            <div
                                class="flex items-center gap-2 rounded-lg bg-black/5 p-2">
                                <Calendar
                                    size={14}
                                    class="text-primary-500 shrink-0" />
                                <span
                                    >Created: {new Date(
                                        site.created_on
                                    ).toLocaleDateString()}</span>
                            </div>
                            <div
                                class="flex items-center gap-2 rounded-lg bg-black/5 p-2">
                                <ShieldCheck
                                    size={14}
                                    class="text-secondary-500 shrink-0" />
                                <span class="truncate font-mono"
                                    >{site.site_id}</span>
                            </div>
                        </div>

                        <a
                            class="btn btn-sm preset-filled-primary w-full font-bold shadow-lg transition-all group-hover:brightness-110"
                            href="/core/sites/{site.site_id}">
                            Manage Site
                        </a>
                    </div>
                {/each}
            </div>
        </div>
    {/if}
</div>
