<script setup lang="ts">
import { ref, watch, computed, onMounted } from 'vue';
import { Link, usePage } from '@inertiajs/vue3';
import Sidebar from '@/Components/Admin/Sidebar.vue';
import Navbar from '@/Components/Admin/Navbar.vue';
import DemoModeBanner from '@/Components/DemoModeBanner.vue';
import { useAuth } from '@/Composables/useAuth';
import * as LucideIcons from 'lucide-vue-next';
import { X, LogOut, Sun, Moon, CheckCircle, AlertCircle } from 'lucide-vue-next';

// Synchronous local storage read to prevent layout flicker on load
const isCollapsed = ref(localStorage.getItem('admin_sidebar_collapsed') === 'true');
const isMobileOpen = ref(false);

const { settings, hasPermission, hasRole } = useAuth();
const page = usePage();

const isDark = ref(false);
onMounted(() => {
    isDark.value = document.documentElement.classList.contains('dark');
});
const toggleTheme = () => {
    if (document.documentElement.classList.contains('dark')) {
        document.documentElement.classList.remove('dark');
        localStorage.setItem('theme', 'light');
        isDark.value = false;
    } else {
        document.documentElement.classList.add('dark');
        localStorage.setItem('theme', 'dark');
        isDark.value = true;
    }
};

// Watch collapsed state to store in localStorage
watch(isCollapsed, (newVal) => {
    localStorage.setItem('admin_sidebar_collapsed', String(newVal));
});

// Close mobile sidebar on page changes (e.g. Inertia navigation)
watch(() => page.url, () => {
    isMobileOpen.value = false;
});

const toggleSidebar = () => {
    isCollapsed.value = !isCollapsed.value;
};

const toggleMobileSidebar = () => {
    isMobileOpen.value = !isMobileOpen.value;
};

// Get dynamic icon component from name string
const getIcon = (name: string | null) => {
    if (!name) return LucideIcons.HelpCircle;
    const icon = (LucideIcons as any)[name];
    return icon || LucideIcons.HelpCircle;
};

// Filtered navigation for mobile drawer
const filteredNavigation = computed(() => {
    const rawNav = (page.props.navigation as any) || [];
    return rawNav.map((group: any) => {
        const items = group.items.filter((item: any) => {
            const permissionCheck = !item.permissions || item.permissions.length === 0 || item.permissions.some((p: string) => hasPermission(p));
            const roleCheck = !item.roles || item.roles.length === 0 || item.roles.some((r: string) => hasRole(r));
            return permissionCheck && roleCheck;
        });
        return { ...group, items };
    }).filter((group: any) => group.items.length > 0);
});

const isActive = (href: string) => {
    if (href === '/admin/dashboard') {
        return page.url === '/admin/dashboard';
    }
    if (href === '/admin/settings') {
        return page.url === '/admin/settings';
    }
    return page.url.startsWith(href);
};

// Global Notifications Alert State
const activeAlert = ref<{ type: 'success' | 'error'; message: string } | null>(null);

let alertTimeoutId: ReturnType<typeof setTimeout> | null = null;

const triggerAlert = (type: 'success' | 'error', message: string) => {
    if (alertTimeoutId) clearTimeout(alertTimeoutId);
    activeAlert.value = { type, message };
    
    // Auto-dismiss after 4 seconds
    alertTimeoutId = setTimeout(() => {
        activeAlert.value = null;
    }, 4000);
};

const dismissAlert = () => {
    if (alertTimeoutId) clearTimeout(alertTimeoutId);
    activeAlert.value = null;
};

// Watch for flash updates from Inertia
watch(
    () => page.props.flash as any,
    (flash) => {
        if (flash?.success) {
            triggerAlert('success', String(flash.success));
        } else if (flash?.error) {
            triggerAlert('error', String(flash.error));
        }
    },
    { deep: true, immediate: true }
);
</script>

<template>
    <div class="min-h-screen bg-slate-50 dark:bg-slate-900 text-slate-900 dark:text-slate-100 flex">
        <!-- Global Notification Toast -->
        <transition name="toast-slide">
            <div
                v-if="activeAlert"
                class="fixed top-6 right-6 z-[100] w-full max-w-sm overflow-hidden rounded-xl border bg-white/95 dark:bg-slate-950/95 backdrop-blur-md shadow-lg transition-all duration-300 pointer-events-auto select-none"
                :class="activeAlert.type === 'success' ? 'border-emerald-500/30' : 'border-rose-500/30'"
            >
                <div class="p-4 flex items-start gap-3 relative">
                    <!-- Indicator border -->
                    <div 
                        class="absolute left-0 top-0 bottom-0 w-1"
                        :class="activeAlert.type === 'success' ? 'bg-emerald-500' : 'bg-rose-500'"
                    />

                    <!-- Icon -->
                    <div class="flex-shrink-0 mt-0.5">
                        <component 
                            :is="activeAlert.type === 'success' ? CheckCircle : AlertCircle"
                            :class="['h-5 w-5', activeAlert.type === 'success' ? 'text-emerald-500' : 'text-rose-500']"
                        />
                    </div>

                    <!-- Message text -->
                    <div class="flex-1 min-w-0 pr-2 font-sans">
                        <p class="text-[10px] font-extrabold uppercase tracking-widest leading-none mb-1.5" :class="activeAlert.type === 'success' ? 'text-emerald-600 dark:text-emerald-400' : 'text-rose-600 dark:text-rose-400'">
                            {{ activeAlert.type === 'success' ? 'Berhasil' : 'Peringatan' }}
                        </p>
                        <p class="text-xs text-slate-700 dark:text-slate-300 font-bold leading-normal">
                            {{ activeAlert.message }}
                        </p>
                    </div>

                    <!-- Dismiss button -->
                    <button 
                        @click="dismissAlert"
                        class="flex-shrink-0 p-1 hover:bg-slate-100 dark:hover:bg-slate-900 rounded-lg text-slate-400 dark:text-slate-500 hover:text-slate-700 dark:hover:text-slate-300 transition-colors cursor-pointer"
                    >
                        <X class="h-4 w-4" />
                    </button>
                </div>
            </div>
        </transition>
        <!-- Desktop Sidebar -->
        <Sidebar 
            v-if="!$page.props.auth.user.roles.includes('Kasir')"
            :is-collapsed="isCollapsed" 
            @toggle="toggleSidebar"
        />

        <!-- Main Workspace Wrapper -->
        <div 
            :class="[
                'flex-1 flex flex-col min-w-0 min-h-screen transition-all duration-300 ease-in-out',
                !$page.props.auth.user.roles.includes('Kasir') ? (isCollapsed ? 'md:pl-16' : 'md:pl-64') : ''
            ]"
        >
            <DemoModeBanner />

            <!-- Top Navbar -->
            <Navbar 
                v-if="!$page.props.auth.user.roles.includes('Kasir')"
                :is-sidebar-collapsed="isCollapsed"
                @toggle-sidebar="toggleSidebar"
                @toggle-mobile-sidebar="toggleMobileSidebar"
            />

            <!-- Cashier-specific Header -->
            <header v-else class="h-16 border-b border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-950 px-6 flex items-center justify-between flex-shrink-0 shadow-sm z-10 select-none w-full">
                <!-- Left: Brand Logo & Title -->
                <div class="flex items-center gap-3">
                    <div v-if="settings().site_logo" class="h-9 w-9 rounded-lg overflow-hidden border border-slate-105 dark:border-slate-800 flex items-center justify-center bg-slate-50">
                        <img :src="settings().site_logo ?? undefined" alt="Logo" class="max-h-7 object-contain" />
                    </div>
                    <div v-else class="h-9 w-9 rounded-lg bg-red-600 flex items-center justify-center flex-shrink-0 text-white font-bold text-lg">
                        <span>{{ settings().site_name?.charAt(0) ?? 'C' }}</span>
                    </div>
                    <div class="flex flex-col">
                        <span class="font-extrabold text-sm tracking-wider uppercase leading-none">{{ settings().site_name }}</span>
                        <span class="text-[9px] text-slate-400 dark:text-slate-500 mt-1 leading-none">Terminal Kasir</span>
                    </div>
                </div>

                <!-- Right: Navigation actions -->
                <div class="flex items-center gap-4">
                    <div class="flex items-center gap-2">
                        <Link
                            :href="route('pos.index')"
                            class="px-3 py-1.5 border border-slate-200 dark:border-slate-800 rounded-lg text-xs font-semibold hover:bg-slate-50 dark:hover:bg-slate-900 transition-colors cursor-pointer text-slate-700 dark:text-slate-300"
                        >
                            Kembali ke Kasir
                        </Link>
                        <!-- Theme Toggle Button -->
                        <button
                            @click="toggleTheme"
                            class="h-8 w-8 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-900 flex items-center justify-center text-slate-550 dark:text-slate-400 cursor-pointer transition-colors"
                            aria-label="Toggle Theme"
                        >
                            <Sun v-if="isDark" class="h-4.5 w-4.5 text-amber-500" />
                            <Moon v-else class="h-4.5 w-4.5 text-slate-600 dark:text-slate-400" />
                        </button>
                        <Link
                            :href="route('logout')"
                            method="post"
                            as="button"
                            class="px-3 py-1.5 bg-rose-600 hover:bg-rose-500 text-white rounded-lg text-xs font-semibold transition-colors cursor-pointer"
                        >
                            Keluar
                        </Link>
                    </div>
                </div>
            </header>

            <!-- Page Main Content Slot -->
            <main class="flex-1 p-6 md:p-8">
                <!-- Page contents slide/fade in smoothly -->
                <div class="animate-in fade-in slide-in-from-bottom-2 duration-300">
                    <slot />
                </div>
            </main>
        </div>

        <!-- Mobile Drawer Portal -->
        <div v-if="isMobileOpen" class="md:hidden fixed inset-0 z-50 flex">
            <!-- Backdrop -->
            <div 
                @click="isMobileOpen = false"
                class="fixed inset-0 bg-slate-950/60 backdrop-blur-sm animate-in fade-in duration-200"
            />

            <!-- Drawer Container -->
            <div 
                class="relative flex flex-col w-full max-w-xs bg-white dark:bg-slate-950 border-r border-slate-200 dark:border-slate-800 shadow-2xl animate-in slide-in-from-left duration-300"
            >
                <!-- Close Button & Site Info -->
                <div class="h-16 flex items-center justify-between px-4 border-b border-slate-200 dark:border-slate-800">
                    <Link :href="route('dashboard')" class="flex items-center gap-3 overflow-hidden w-full">
                        <img 
                            v-if="settings().site_logo" 
                            :src="settings().site_logo ?? undefined" 
                            alt="Logo" 
                            class="h-9 w-9 object-contain flex-shrink-0"
                        />
                        <div 
                            v-else 
                            class="h-9 w-9 rounded-lg bg-red-600 flex items-center justify-center flex-shrink-0 text-white font-bold text-lg"
                        >
                            <span>{{ settings().site_name?.charAt(0) ?? 'L' }}</span>
                        </div>
                        <div class="flex flex-col min-w-0">
                            <span class="font-semibold text-sm leading-none truncate">{{ settings().site_name }}</span>
                            <span class="text-[10px] text-slate-400 dark:text-slate-500 truncate mt-1 leading-none">{{ settings().site_description }}</span>
                        </div>
                    </Link>
                    <button 
                        @click="isMobileOpen = false"
                        class="h-8 w-8 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-900 flex items-center justify-center text-slate-500 dark:text-slate-400 cursor-pointer flex-shrink-0"
                    >
                        <X class="h-5 w-5" />
                    </button>
                </div>

                <!-- Scrollable Navigation Area -->
                <div class="flex-1 overflow-y-auto py-4 px-3 space-y-6">
                    <div v-for="(group, gIdx) in filteredNavigation" :key="gIdx" class="space-y-1">
                        <h3 class="px-2 text-[10px] font-semibold tracking-wider text-slate-400 dark:text-slate-500 uppercase mb-2">
                            {{ group.groupName }}
                        </h3>
                        <div class="space-y-1">
                            <Link
                                v-for="(item, iIdx) in group.items"
                                :key="iIdx"
                                :href="item.href"
                                :class="[
                                    'flex items-center gap-3 px-3 py-2 rounded-lg text-sm font-medium transition-all duration-200 group relative',
                                    isActive(item.href) 
                                        ? 'bg-red-50 dark:bg-red-950/40 text-red-600 dark:text-red-400' 
                                        : 'hover:bg-slate-100 dark:hover:bg-slate-900 text-slate-600 dark:text-slate-400 hover:text-slate-900 dark:hover:text-slate-100'
                                ]"
                            >
                                <component :is="getIcon(item.icon)" class="h-5 w-5 flex-shrink-0 text-slate-400" />
                                <span>{{ item.title }}</span>
                            </Link>
                        </div>
                    </div>
                </div>

                <!-- Mobile Drawer Footer -->
                <div class="p-3 border-t border-slate-200 dark:border-slate-800">
                    <Link
                        :href="route('logout')"
                        method="post"
                        as="button"
                        class="flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg text-sm font-semibold border border-slate-200 dark:border-slate-800 text-rose-600 hover:bg-rose-50 dark:hover:bg-rose-950/20 transition-all cursor-pointer w-full"
                    >
                        <LogOut class="h-4 w-4" />
                        <span>Log Out</span>
                    </Link>
                </div>
            </div>
        </div>
    </div>
</template>

<style scoped>
.toast-slide-enter-active,
.toast-slide-leave-active {
    transition: all 0.4s cubic-bezier(0.16, 1, 0.3, 1);
}
.toast-slide-enter-from {
    opacity: 0;
    transform: translateX(40px) scale(0.95);
}
.toast-slide-leave-to {
    opacity: 0;
    transform: translateX(40px) scale(0.95);
}
</style>
