<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 { Plus, Search, Globe, ListFilter, RefreshCcw, X, ExternalLink, Calendar, ShieldCheck } 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 p-4 space-y-6">
    <header class="flex flex-wrap justify-between items-center bg-surface-50-900-token p-4 rounded-xl shadow-lg border border-surface-500/10 gap-4">
        <div class="flex items-center gap-3">
            <div class="p-2 bg-primary-500/10 rounded-lg">
                <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 opacity-50 uppercase tracking-widest">Digital Properties & Domains</p>
            </div>
        </div>
        <button class="btn btn-sm variant-filled-primary font-bold shadow-lg" onclick={handle_add_site}>
            <Plus size={16} class="mr-2" /> Add Site
        </button>
    </header>

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

            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div class="space-y-1">
                    <span class="label block text-xs font-bold opacity-75 uppercase tracking-wider ml-1">Status</span>
                    <select class="select variant-filled-surface rounded-lg text-sm border border-surface-500/20 p-2" 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 block text-xs font-bold opacity-75 uppercase tracking-wider ml-1">Visibility</span>
                    <select class="select variant-filled-surface rounded-lg text-sm border border-surface-500/20 p-2" 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 p-8 flex justify-center items-center h-64">
            <div class="placeholder animate-pulse w-full h-full rounded-2xl"></div>
        </div>
    {:else if filtered_li.length === 0}
        <div class="card p-12 text-center variant-glass-surface border-2 border-dashed border-surface-500/20 rounded-2xl">
            <Globe size={48} class="mx-auto mb-4 opacity-20" />
            <h3 class="h3 font-bold opacity-50">No Sites Found</h3>
            <p class="opacity-60 max-w-xs mx-auto mt-2">Sites for this account will appear here. Add your first site to get started.</p>
        </div>
    {:else}
        <div class="card p-6 variant-glass-surface shadow-xl border border-surface-500/10">
            <h3 class="h4 font-bold border-b border-surface-500/30 pb-2 mb-6 flex items-center gap-2">
                <ListFilter size={18} class="text-secondary-500" />
                Linked Properties
                <span class="badge variant-soft-secondary ml-auto">{filtered_li.length} found</span>
            </h3>

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

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

                        <div class="space-y-2 text-xs opacity-70">
                            <div class="flex items-center gap-2 bg-black/5 p-2 rounded-lg">
                                <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 bg-black/5 p-2 rounded-lg">
                                <ShieldCheck size={14} class="text-secondary-500 shrink-0" />
                                <span class="font-mono truncate">{site.site_id_random}</span>
                            </div>
                        </div>

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