<script setup lang="ts">
import { Head, router, usePage } from '@inertiajs/vue3';
import debounce from 'lodash/debounce';
import { ArrowLeft, Calendar, Clock, Filter } from 'lucide-vue-next';
import { computed, ref, watch } from 'vue';
import { index } from '@/actions/App/Http/Controllers/AttendanceController';
import AdminLayout from '@/Layouts/AdminLayout.vue';
import EmployeeLayout from '@/Layouts/EmployeeLayout.vue';

const props = defineProps<{
    today: any;
    timesheet: any[] | any;
    filters: any;
}>();

const currentMonth = computed(() => new Date().toISOString().slice(0, 7));
const selectedMonth = ref(props.filters.month || currentMonth.value);

watch(selectedMonth, debounce((value) => {
    if (value > currentMonth.value) {
        selectedMonth.value = currentMonth.value;
        return;
    }

    const currentPath = window.location.pathname;
    const action = (index as any)[currentPath];
    
    if (action) {
        router.get(action.url({ query: { month: value } }), {}, {
            preserveState: true,
            replace: true,
            preserveScroll: true
        });
    }
}, 500));

const selectedMonthDate = computed(() => new Date(`${selectedMonth.value}-01T00:00:00`));
const daysInSelectedMonth = computed(() => {
    const date = selectedMonthDate.value;
    return new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
});
const monthlyTotalHours = computed(() =>
    props.timesheet.reduce((acc: number, curr: any) => acc + parseFloat(curr.total_hours || 0), 0),
);
const workedDays = computed(() => props.timesheet.filter((entry: any) => entry.clock_in).length);
const avgDailyHours = computed(() => (workedDays.value > 0 ? monthlyTotalHours.value / workedDays.value : 0));
const selectedMonthLabel = computed(() =>
    selectedMonthDate.value.toLocaleDateString([], { month: 'long', year: 'numeric' }),
);

const getStatusColor = (status: string) => {
    switch (status) {
        case 'approved': return 'bg-emerald-100 text-emerald-800 dark:bg-emerald-500/20 dark:text-emerald-400';
        case 'pending': return 'bg-amber-100 text-amber-800 dark:bg-amber-500/20 dark:text-amber-400';
        case 'rejected': return 'bg-rose-100 text-rose-800 dark:bg-rose-500/20 dark:text-rose-400';
        default: return 'bg-slate-100 text-slate-800';
    }
};

const page = usePage();
const isAdmin = computed(() => {
    const user = page.props.auth?.user;
    if (!user) return false;
    return user.type === 'admin' || user.type === 'super-admin';
});
const layout = computed(() => isAdmin.value ? AdminLayout : EmployeeLayout);
</script>

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

    <component :is="layout">
        <div class="space-y-6 animate-fade-in">
            <!-- Header -->
            <div class="flex items-center justify-between">
                 <div>
                    <h2 class="text-xl font-extrabold text-slate-900 dark:text-white">
                        {{ __('my_attendance') }}
                    </h2>
                    <p class="text-sm text-slate-500">{{ selectedMonthLabel }}</p>
                </div>
                <div class="flex items-center space-x-3">
                    <!-- Date Filter -->
                    <div class="relative">
                        <Calendar :size="16" class="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
                        <input 
                            type="month"
                            v-model="selectedMonth"
                            :max="currentMonth"
                            class="pl-10 pr-4 py-2 bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-xl text-sm focus:ring-2 focus:ring-sky-500/20 transition-all font-bold"
                        />
                    </div>
                </div>
            </div>


            <!-- Stats Overview -->
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
                <!-- Weekly Total Hours -->
                <div class="bg-gradient-to-br from-blue-50 to-blue-100 dark:from-blue-900/20 dark:to-blue-800/20 p-6 rounded-2xl border border-blue-200 dark:border-blue-800/50 shadow-sm">
                    <div class="flex items-center justify-between mb-3">
                        <div class="w-10 h-10 rounded-xl bg-blue-500 dark:bg-blue-600 flex items-center justify-center shadow-lg">
                            <Clock :size="20" class="text-white" />
                        </div>
                        <span class="text-xs font-bold text-blue-600 dark:text-blue-400 uppercase tracking-wide">{{ __('monthly_total') }}</span>
                    </div>
                    <div class="text-3xl font-black text-blue-900 dark:text-blue-100">
                        {{ monthlyTotalHours.toFixed(1) }}<span class="text-lg text-blue-600 dark:text-blue-400">h</span>
                    </div>
                    <p class="text-xs text-blue-600 dark:text-blue-400 mt-2 font-medium">{{ __('this_month') }}</p>
                </div>

                <!-- Days Worked -->
                <div class="bg-gradient-to-br from-emerald-50 to-emerald-100 dark:from-emerald-900/20 dark:to-emerald-800/20 p-6 rounded-2xl border border-emerald-200 dark:border-emerald-800/50 shadow-sm">
                    <div class="flex items-center justify-between mb-3">
                        <div class="w-10 h-10 rounded-xl bg-emerald-500 dark:bg-emerald-600 flex items-center justify-center shadow-lg">
                            <Calendar :size="20" class="text-white" />
                        </div>
                        <span class="text-xs font-bold text-emerald-600 dark:text-emerald-400 uppercase tracking-wide">{{ __('days_worked') }}</span>
                    </div>
                    <div class="text-3xl font-black text-emerald-900 dark:text-emerald-100">
                        {{ workedDays }}<span class="text-lg text-emerald-600 dark:text-emerald-400">/{{ daysInSelectedMonth }}</span>
                    </div>
                    <p class="text-xs text-emerald-600 dark:text-emerald-400 mt-2 font-medium">{{ __('this_month') }}</p>
                </div>

                <!-- Average Daily Hours -->
                <div class="bg-gradient-to-br from-amber-50 to-amber-100 dark:from-amber-900/20 dark:to-amber-800/20 p-6 rounded-2xl border border-amber-200 dark:border-amber-800/50 shadow-sm">
                    <div class="flex items-center justify-between mb-3">
                        <div class="w-10 h-10 rounded-xl bg-amber-500 dark:bg-amber-600 flex items-center justify-center shadow-lg">
                            <ArrowLeft :size="20" class="text-white rotate-180" />
                        </div>
                        <span class="text-xs font-bold text-amber-600 dark:text-amber-400 uppercase tracking-wide">{{ __('avg_daily') }}</span>
                    </div>
                    <div class="text-3xl font-black text-amber-900 dark:text-amber-100">
                        {{ avgDailyHours.toFixed(1) }}<span class="text-lg text-amber-600 dark:text-amber-400">h</span>
                    </div>
                    <p class="text-xs text-amber-600 dark:text-amber-400 mt-2 font-medium">{{ __('per_day') }}</p>
                </div>

                <!-- Status Summary -->
                <div class="bg-gradient-to-br from-purple-50 to-purple-100 dark:from-purple-900/20 dark:to-purple-800/20 p-6 rounded-2xl border border-purple-200 dark:border-purple-800/50 shadow-sm">
                    <div class="flex items-center justify-between mb-3">
                        <div class="w-10 h-10 rounded-xl bg-purple-500 dark:bg-purple-600 flex items-center justify-center shadow-lg">
                            <Filter :size="20" class="text-white" />
                        </div>
                        <span class="text-xs font-bold text-purple-600 dark:text-purple-400 uppercase tracking-wide">{{ __('approved') }}</span>
                    </div>
                    <div class="text-3xl font-black text-purple-900 dark:text-purple-100">
                        {{ timesheet.filter((entry: any) => entry.status === 'approved').length }}<span class="text-lg text-purple-600 dark:text-purple-400">/{{ timesheet.length }}</span>
                    </div>
                    <p class="text-xs text-purple-600 dark:text-purple-400 mt-2 font-medium">{{ __('records') }}</p>
                </div>
            </div>

            <!-- Timesheet Table -->
            <div class="bg-white dark:bg-slate-900 rounded-xl border border-slate-100 dark:border-slate-800 shadow-sm overflow-hidden text-z">
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead>
                            <tr class="bg-slate-50 dark:bg-slate-800/50">
                                <th class="text-left py-4 px-6 text-[10px] font-bold text-slate-500 uppercase tracking-widest">{{ __('date') }}</th>
                                <th class="text-left py-4 px-6 text-[10px] font-bold text-slate-500 uppercase tracking-widest">{{ __('clock_in') }}</th>
                                <th class="text-left py-4 px-6 text-[10px] font-bold text-slate-500 uppercase tracking-widest">{{ __('clock_out') }}</th>
                                <th class="text-left py-4 px-6 text-[10px] font-bold text-slate-500 uppercase tracking-widest">{{ __('hours') }}</th>
                                <th class="text-left py-4 px-6 text-[10px] font-bold text-slate-500 uppercase tracking-widest">{{ __('status') }}</th>
                                <th class="text-left py-4 px-6 text-[10px] font-bold text-slate-500 uppercase tracking-widest">{{ __('type') }}</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-50 dark:divide-slate-800/50">
                            <tr v-for="entry in timesheet" :key="entry.id" class="hover:bg-slate-50 dark:hover:bg-slate-800/30 transition-colors">
                                <td class="py-4 px-6">
                                    <div class="text-sm font-bold text-slate-900 dark:text-white">{{ new Date(entry.date).toLocaleDateString([], { weekday: 'short', month: 'short', day: 'numeric' }) }}</div>
                                </td>
                                <td class="py-4 px-6">
                                    <div class="text-sm font-bold text-slate-600 dark:text-slate-400">{{ entry.clock_in ? new Date(entry.clock_in).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : '-' }}</div>
                                </td>
                                <td class="py-4 px-6">
                                    <div class="text-sm font-bold text-slate-600 dark:text-slate-400">{{ entry.clock_out ? new Date(entry.clock_out).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : '-' }}</div>
                                </td>
                                <td class="py-4 px-6">
                                    <div class="text-sm font-black text-sky-600 dark:text-sky-400">{{ entry.total_hours || '-' }}h</div>
                                </td>
                                <td class="py-4 px-6">
                                    <span :class="['inline-flex items-center px-2.5 py-0.5 rounded-full text-[10px] font-bold', getStatusColor(entry.status)]">
                                        {{ __(entry.status) }}
                                    </span>
                                </td>
                                <td class="py-4 px-6">
                                    <div class="flex items-center space-x-1">
                                        <span class="text-[10px] font-bold text-slate-400 capitalize">{{ entry.in_type }} / {{ entry.out_type }}</span>
                                    </div>
                                </td>
                            </tr>
                            <tr v-if="timesheet.length === 0">
                                <td colspan="6" class="py-16">
                                    <div class="flex flex-col items-center justify-center text-center">
                                        <div class="w-16 h-16 rounded-full bg-slate-100 dark:bg-slate-800 flex items-center justify-center mb-4">
                                            <Calendar :size="32" class="text-slate-400" />
                                        </div>
                                        <h3 class="text-lg font-semibold text-slate-800 dark:text-slate-200 mb-2">
                                            {{ __('no_attendance_records') }}
                                        </h3>
                                        <p class="text-sm text-slate-500 dark:text-slate-400 max-w-md">
                                            {{ __('no_records_found_matching_criteria') }}
                                        </p>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </component>
</template>
