<script lang="ts">
import { onMount } from 'svelte';
import { ae_api, ae_loc } from '$lib/stores/ae_stores';
import { goto } from '$app/navigation';
import {
    Clock,
    Globe,
    Info,
    Landmark,
    List,
    ListFilter,
    MapPin,
    RefreshCcw,
    Star
} from '@lucide/svelte';
import { api } from '$lib/ae_api/api';

let loading = $state(true);
let tz_only_priority = $state(false);
let lookups: any = $state({
    countries: [],
    time_zones: [],
    subdivisions: []
});

async function load_lookups() {
    loading = true;
    try {
        const [countries, subdivisions, time_zones] = await Promise.all([
            api.get_ae_obj_li_for_lu({
                api_cfg: $ae_api,
                for_lu_type: 'country',
                log_lvl: 1
            }),
            api.get_ae_obj_li_for_lu({
                api_cfg: $ae_api,
                for_lu_type: 'country_subdivision',
                log_lvl: 1
            }),
            api.get_ae_obj_li_for_lu({
                api_cfg: $ae_api,
                for_lu_type: 'time_zone',
                only_priority: tz_only_priority,
                log_lvl: 1
            })
        ]);

        console.log('Lookup Results - Countries:', countries);
        console.log('Lookup Results - Subdivisions:', subdivisions);
        console.log('Lookup Results - Time Zones:', time_zones);

        lookups.countries = countries || [];
        lookups.subdivisions = subdivisions || [];
        lookups.time_zones = time_zones || [];
    } catch (error) {
        console.error('Failed to load lookups:', error);
    } finally {
        loading = false;
    }
}

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

// Handle TZ priority toggle
function toggle_tz_priority() {
    tz_only_priority = !tz_only_priority;
    load_lookups();
}
</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">
                <List size={24} class="text-primary-500" />
            </div>
            <div>
                <h1 class="h2 font-black tracking-tight">System Lookups</h1>
                <p
                    class="text-xs font-bold tracking-widest uppercase opacity-50">
                    Global Reference Data
                </p>
            </div>
        </div>
        <div class="flex gap-2">
            <button
                class="btn btn-sm preset-filled-primary font-bold shadow-lg"
                onclick={load_lookups}
                disabled={loading}>
                {#if loading}
                    <RefreshCcw size={16} class="mr-2 animate-spin" /> Loading...
                {:else}
                    <RefreshCcw size={16} class="mr-2" /> Refresh Data
                {/if}
            </button>
        </div>
    </header>

    {#if loading && !lookups.countries.length}
        <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}
        <div class="animate-fade-in space-y-6">
            <!-- 1. Countries -->
            <div
                class="card preset-tonal-surface border-surface-500/10 space-y-6 border p-6 shadow-xl">
                <h3
                    class="h4 border-surface-500/30 flex items-center gap-2 border-b pb-2 font-bold">
                    <Globe size={20} class="text-secondary-500" />
                    Country Reference
                    <span
                        class="badge preset-tonal-secondary ml-auto text-[10px] font-bold uppercase"
                        >{lookups.countries.length} Records</span>
                </h3>

                <div
                    class="table-container border-surface-500/10 max-h-[400px] overflow-auto rounded-lg border">
                    <table class="table-hover table-compact table">
                        <thead>
                            <tr
                                class="text-[10px] tracking-widest uppercase opacity-60">
                                <th>Name</th>
                                <th class="text-center">ISO Alpha-2</th>
                            </tr>
                        </thead>
                        <tbody>
                            {#each lookups.countries as c (c.alpha_2_code)}
                                <tr class="transition-colors">
                                    <td class="font-bold"
                                        >{c.name || c.english_short_name}</td>
                                    <td class="text-center"
                                        ><span
                                            class="badge preset-tonal-surface text-primary-500 font-mono"
                                            >{c.alpha_2_code}</span
                                        ></td>
                                </tr>
                            {/each}
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- 2. Subdivisions -->
            <div
                class="card preset-tonal-surface border-surface-500/10 space-y-6 border p-6 shadow-xl">
                <h3
                    class="h4 border-surface-500/30 flex items-center gap-2 border-b pb-2 font-bold">
                    <MapPin size={20} class="text-primary-500" />
                    Country Subdivisions (States/Provinces)
                    <span
                        class="badge preset-tonal-secondary ml-auto text-[10px] font-bold uppercase"
                        >{lookups.subdivisions.length} Records</span>
                </h3>

                <div
                    class="table-container border-surface-500/10 max-h-[500px] overflow-auto rounded-lg border">
                    <table class="table-hover table-compact table">
                        <thead>
                            <tr
                                class="text-[10px] tracking-widest uppercase opacity-60">
                                <th>Country</th>
                                <th>Name</th>
                                <th class="text-center">Code</th>
                            </tr>
                        </thead>
                        <tbody>
                            {#each lookups.subdivisions as s, i (i)}
                                <tr class="transition-colors">
                                    <td class="opacity-60"
                                        >{s.country_alpha_2_code}</td>
                                    <td class="font-bold">{s.name}</td>
                                    <td class="text-center"
                                        ><span
                                            class="badge preset-tonal-surface font-mono"
                                            >{s.code}</span
                                        ></td>
                                </tr>
                            {/each}
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- 3. Time Zones -->
            <div
                class="card preset-tonal-surface border-surface-500/10 space-y-6 border p-6 shadow-xl">
                <div
                    class="border-surface-500/30 flex flex-wrap items-center justify-between gap-4 border-b pb-2">
                    <h3 class="h4 flex items-center gap-2 font-bold">
                        <Clock size={20} class="text-tertiary-500" />
                        Time Zone Reference
                        <span
                            class="badge preset-tonal-secondary text-[10px] font-bold uppercase"
                            >{lookups.time_zones.length} Zones</span>
                    </h3>
                    <button
                        class="btn btn-sm transition-all {tz_only_priority
                            ? 'preset-filled-warning'
                            : 'preset-tonal-surface'}"
                        onclick={toggle_tz_priority}
                        disabled={loading}>
                        <Star
                            size={14}
                            class="mr-2 {tz_only_priority
                                ? 'fill-current'
                                : ''}" />
                        {tz_only_priority
                            ? 'Showing Priority'
                            : 'Show Only Priority'}
                    </button>
                </div>

                <div
                    class="table-container border-surface-500/10 max-h-[500px] overflow-auto rounded-lg border">
                    <table class="table-hover table-compact table">
                        <thead>
                            <tr
                                class="text-[10px] tracking-widest uppercase opacity-60">
                                <th>Zone Name</th>
                                <th class="text-right">Offset (Hours)</th>
                            </tr>
                        </thead>
                        <tbody>
                            {#each lookups.time_zones as tz (tz.name)}
                                <tr class="transition-colors">
                                    <td class="font-bold">{tz.name}</td>
                                    <td class="text-right"
                                        ><span
                                            class="badge preset-tonal-surface font-mono"
                                            >{tz.offset_seconds / 3600}h</span
                                        ></td>
                                </tr>
                            {/each}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div
            class="card preset-tonal-surface border-surface-500/10 flex items-center gap-3 border p-4">
            <Info size={16} class="text-primary-500" />
            <p class="text-xs opacity-70">
                Lookup data is synchronized with the global system database and
                used for addresses, event scheduling, and localized displays.
            </p>
        </div>
    {/if}
</div>
