<script setup lang="ts">
import { Head, Link, usePage } from '@inertiajs/vue3';
import { CalendarClock, ClipboardCheck } from 'lucide-vue-next';
import { computed, onMounted, onUnmounted, ref } from 'vue';
import LogHistory from '@/Components/Employee/LogHistory.vue';
import MonthlyGoal from '@/Components/Employee/MonthlyGoal.vue';
import ShiftControls from '@/Components/Employee/ShiftControls.vue';
import StatsGrid from '@/Components/Employee/StatsGrid.vue';
import EmployeeLayout from '@/Layouts/EmployeeLayout.vue';
import employee from '@/routes/employee';

const props = defineProps<{
    today_attendance: any;
    stats: any;
    history: any[];
    filters: any;
    quick_access: {
        attendance_approvals: {
            has_access: boolean;
            total_count: number;
            pending_count: number;
        };
        leave_approvals: {
            has_access: boolean;
            total_count: number;
            pending_count: number;
        };
    };
}>();

const page = usePage();
const user = computed(() => page.props.auth.user);
const currentTime = ref(new Date());

const isManualEntryEnabled = computed(() => {
    const settings = (page.props.branding as any)?.business_settings;
    if (!settings) return false;
    const val = settings.manual_entry_enabled ?? settings.manual_attendance_enabled;
    return String(val) === '1' || val === true;
});

const quickAccessCards = computed(() => {
    return [
        {
            key: 'attendance_approvals',
            titleKey: 'attendance_approvals',
            subtitleKey: 'review_attendance_anomalies_for_your_team',
            icon: CalendarClock,
            href: employee.manager.attendance.approvals.url(),
            hasAccess: props.quick_access.attendance_approvals.has_access,
            totalCount: props.quick_access.attendance_approvals.total_count,
            pendingCount: props.quick_access.attendance_approvals.pending_count,
            style: 'from-amber-50 to-amber-100 border-amber-200 text-amber-700 dark:from-amber-900/20 dark:to-amber-800/20 dark:border-amber-800/50',
            badgeStyle: 'bg-amber-500',
        },
        {
            key: 'leave_approvals',
            titleKey: 'leave_approvals',
            subtitleKey: 'review_leave_requests_for_your_team',
            icon: ClipboardCheck,
            href: employee.manager.leave.approvals.url(),
            hasAccess: props.quick_access.leave_approvals.has_access,
            totalCount: props.quick_access.leave_approvals.total_count,
            pendingCount: props.quick_access.leave_approvals.pending_count,
            style: 'from-emerald-50 to-emerald-100 border-emerald-200 text-emerald-700 dark:from-emerald-900/20 dark:to-emerald-800/20 dark:border-emerald-800/50',
            badgeStyle: 'bg-emerald-500',
        },
    ].filter((card) => card.hasAccess);
});

let timeInterval: any = null;

onMounted(() => {
    console.log('Dashboard Component Mounted');
    timeInterval = setInterval(() => {
        currentTime.value = new Date();
    }, 1000);
});

onUnmounted(() => {
    if (timeInterval) clearInterval(timeInterval);
});

// Helper to access nested branding config safely (fallback to admin if employee specific not set)
const t = (section: string, key: string) => {
    return page.props.branding?.employee?.dashboard?.[section]?.[key] || page.props.branding?.admin?.dashboard?.[section]?.[key] || key;
}
</script>

<template>
    <Head :title="__('dashboard')" />

    <EmployeeLayout>
        
        <!-- DASHBOARD (EMPLOYEE PANEL) -->
        <div class="space-y-6 animate-fade-in">

            <!-- Welcome & Header -->
            <div class="flex items-center justify-between">
                 <div>
                    <h2 class="text-xl font-bold text-slate-900 dark:text-white">{{ __(t('overview', 'welcome_back')) }}, {{ user.name }}</h2>
                    <p class="text-slate-500 dark:text-slate-400 text-sm">{{ __(t('overview', 'subtitle') || 'Here is what is happening with your workspace.') }}</p>
                 </div>
                 <div class="hidden sm:block text-right">
                    <p class="text-sm font-bold leading-none text-slate-800 dark:text-slate-200">{{ currentTime.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit', second: '2-digit'}) }}</p>
                    <p class="text-[10px] text-slate-500 uppercase font-semibold mt-1">{{ currentTime.toLocaleDateString([], {weekday: 'short', month: 'short', day: 'numeric'}) }}</p>
                 </div>
            </div>
            
            <!-- Action Row - The Core Practical Feature -->
            <div class="grid grid-cols-1 xl:grid-cols-4 gap-6">
                <!-- Quick Summary Card -->
                <MonthlyGoal :stats="stats" />

                <!-- Real-time Status Card & Controls -->
                <ShiftControls v-if="isManualEntryEnabled" :today="today_attendance" />
            </div>

            <!-- Stats Grid - High Information Density -->
            <div v-if="quickAccessCards.length > 0" class="space-y-3">
                <div class="flex items-center justify-between">
                    <h3 class="text-sm font-extrabold tracking-wide text-slate-900 uppercase dark:text-white">
                        {{ __('quick_access') }}
                    </h3>
                    <p class="text-xs font-semibold text-slate-500">{{ __('jump_to_frequent_actions') }}</p>
                </div>

                <div class="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3">
                    <Link
                        v-for="card in quickAccessCards"
                        :key="card.key"
                        :href="card.href"
                        class="group rounded-2xl border bg-gradient-to-br p-5 shadow-sm transition-all hover:-translate-y-0.5 hover:shadow-md"
                        :class="card.style"
                    >
                        <div class="flex items-start justify-between">
                            <div class="flex h-10 w-10 items-center justify-center rounded-xl text-white shadow-lg" :class="card.badgeStyle">
                                <component :is="card.icon" :size="18" />
                            </div>
                            <span class="rounded-full bg-white/70 px-2.5 py-0.5 text-[10px] font-black tracking-wider uppercase dark:bg-slate-900/40">
                                {{ __('total') }}: {{ card.totalCount }}
                            </span>
                        </div>

                        <div class="mt-4">
                            <h4 class="text-sm font-extrabold text-slate-900 dark:text-white">{{ __(card.titleKey) }}</h4>
                            <p class="mt-1 text-xs font-medium text-slate-600 dark:text-slate-300">{{ __(card.subtitleKey) }}</p>
                        </div>

                        <div class="mt-4 flex items-center justify-between">
                            <p class="text-xs font-semibold text-slate-600 dark:text-slate-300">
                                {{ __('pending') }}: <span class="font-black">{{ card.pendingCount }}</span>
                            </p>
                            <span class="text-xs font-black text-slate-700 transition-colors group-hover:text-slate-900 dark:text-slate-200 dark:group-hover:text-white">
                                {{ __('open') }}
                            </span>
                        </div>
                    </Link>
                </div>
            </div>

            <StatsGrid :stats="stats" />

            <!-- Practical Table Section -->
            <!-- Practical Table Section -->
            <LogHistory :history="history" :filters="filters" />

        </div>
    </EmployeeLayout>
</template>
