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

defineOptions({ layout: AdminLayout });

interface AttendanceRecord {
    id: number;
    date: string;
    clock_in: string | null;
    clock_out: string | null;
    total_hours: string | number | null;
    status: string;
    in_type: string | null;
    out_type: string | null;
}

const props = defineProps<{
    employee: {
        id: number;
        name: string;
        email: string;
    };
    department: string | null;
    records: AttendanceRecord[];
    summary: {
        days_worked: number;
        total_hours: number;
        avg_daily: number;
        approved: number;
    };
    filters: {
        start_date: string;
        end_date: string;
        date?: string;
        department_id?: string;
    };
}>();

const startDate = ref(props.filters.start_date || '');
const endDate = ref(props.filters.end_date || '');

const reloadDetails = debounce(() => {
    router.get(
        employeeDetails.url(props.employee.id, {
            query: {
                start_date: startDate.value || undefined,
                end_date: endDate.value || undefined,
                date: props.filters.date || undefined,
                department_id: props.filters.department_id || undefined,
            },
        }),
        {},
        {
            preserveState: true,
            preserveScroll: true,
            replace: true,
        },
    );
}, 350);

watch([startDate, endDate], reloadDetails);

const indexAction = computed(() => attendanceIndex['/admin/attendance']);

const backUrl = computed(() => {
    return indexAction.value.url({
        query: {
            date: props.filters.date || undefined,
            department_id: props.filters.department_id || undefined,
        },
    });
});

const exportCsvUrl = computed(() => {
    const params = new URLSearchParams();
    params.set('format', 'csv');
    params.set('user_id', String(props.employee.id));

    if (startDate.value) {
        params.set('start_date', startDate.value);
    }

    if (endDate.value) {
        params.set('end_date', endDate.value);
    }

    return `/admin/attendance/export?${params.toString()}`;
});

const formatTime = (value: string | null) => {
    if (!value) {
        return '-';
    }

    return new Date(value).toLocaleTimeString([], {
        hour: '2-digit',
        minute: '2-digit',
    });
};

const formatDate = (value: string) => {
    return new Date(value).toLocaleDateString([], {
        weekday: 'short',
        year: 'numeric',
        month: 'short',
        day: 'numeric',
    });
};

const getStatusClass = (status: string) => {
    if (status === 'approved') {
        return 'bg-emerald-100 text-emerald-800 dark:bg-emerald-500/20 dark:text-emerald-400';
    }

    if (status === 'pending') {
        return 'bg-amber-100 text-amber-800 dark:bg-amber-500/20 dark:text-amber-400';
    }

    if (status === 'rejected') {
        return 'bg-rose-100 text-rose-800 dark:bg-rose-500/20 dark:text-rose-400';
    }

    return 'bg-slate-100 text-slate-700 dark:bg-slate-700/50 dark:text-slate-300';
};
</script>

<template>
    <Head :title="`${__('employee_attendance')} - ${employee.name}`" />

    <div class="animate-fade-in space-y-6">
        <div class="flex flex-col justify-between gap-4 lg:flex-row lg:items-center">
            <div class="flex items-start gap-3">
                <Link
                    :href="backUrl"
                    class="inline-flex h-10 w-10 items-center justify-center rounded-xl border border-slate-200 bg-white text-slate-600 transition-colors hover:bg-slate-50 dark:border-slate-700 dark:bg-slate-800 dark:text-slate-300"
                >
                    <ArrowLeft :size="18" />
                </Link>
                <div>
                    <h1 class="text-2xl font-extrabold text-slate-900 dark:text-white">{{ __('employee_attendance') }}</h1>
                    <p class="text-sm text-slate-500">{{ __('attendance_history_for') }} {{ employee.name }}</p>
                </div>
            </div>

            <div class="flex flex-wrap items-center gap-3">
                <div class="relative">
                    <Calendar :size="16" class="pointer-events-none absolute top-1/2 left-3 -translate-y-1/2 text-slate-400" />
                    <input
                        v-model="startDate"
                        type="date"
                        class="w-[170px] rounded-xl border border-slate-200 bg-white py-2.5 pr-3 pl-10 text-sm font-semibold text-slate-700 focus:ring-2 focus:ring-sky-500/20 focus:outline-none dark:border-slate-700 dark:bg-slate-800 dark:text-slate-200"
                    />
                </div>

                <div class="relative">
                    <Calendar :size="16" class="pointer-events-none absolute top-1/2 left-3 -translate-y-1/2 text-slate-400" />
                    <input
                        v-model="endDate"
                        type="date"
                        class="w-[170px] rounded-xl border border-slate-200 bg-white py-2.5 pr-3 pl-10 text-sm font-semibold text-slate-700 focus:ring-2 focus:ring-sky-500/20 focus:outline-none dark:border-slate-700 dark:bg-slate-800 dark:text-slate-200"
                    />
                </div>

                <a
                    :href="exportCsvUrl"
                    class="inline-flex items-center gap-2 rounded-xl border border-slate-200 bg-white px-4 py-2.5 text-sm font-bold text-slate-700 transition-colors hover:bg-slate-50 dark:border-slate-700 dark:bg-slate-800 dark:text-slate-200"
                >
                    <Download :size="16" />
                    {{ __('export_csv') }}
                </a>
            </div>
        </div>

        <div class="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-4">
            <div class="rounded-2xl border border-blue-200 bg-gradient-to-br from-blue-50 to-blue-100 p-5 shadow-sm dark:border-blue-800/50 dark:from-blue-900/20 dark:to-blue-800/20">
                <div class="mb-3 flex items-center justify-between">
                    <div class="flex h-10 w-10 items-center justify-center rounded-xl bg-blue-500 text-white shadow-lg"><User :size="19" /></div>
                    <span class="text-[10px] font-bold tracking-wider text-blue-600 uppercase">{{ __('employee') }}</span>
                </div>
                <p class="truncate text-base font-black text-blue-900 dark:text-blue-100">{{ employee.name }}</p>
                <p class="mt-1 truncate text-xs font-semibold text-blue-600">{{ department || __('unassigned') }}</p>
            </div>

            <div class="rounded-2xl border border-emerald-200 bg-gradient-to-br from-emerald-50 to-emerald-100 p-5 shadow-sm dark:border-emerald-800/50 dark:from-emerald-900/20 dark:to-emerald-800/20">
                <div class="mb-3 flex items-center justify-between">
                    <div class="flex h-10 w-10 items-center justify-center rounded-xl bg-emerald-500 text-white shadow-lg"><Calendar :size="19" /></div>
                    <span class="text-[10px] font-bold tracking-wider text-emerald-600 uppercase">{{ __('days_worked') }}</span>
                </div>
                <p class="text-3xl font-black text-emerald-900 dark:text-emerald-100">{{ summary.days_worked }}</p>
            </div>

            <div class="rounded-2xl border border-amber-200 bg-gradient-to-br from-amber-50 to-amber-100 p-5 shadow-sm dark:border-amber-800/50 dark:from-amber-900/20 dark:to-amber-800/20">
                <div class="mb-3 flex items-center justify-between">
                    <div class="flex h-10 w-10 items-center justify-center rounded-xl bg-amber-500 text-white shadow-lg"><Clock :size="19" /></div>
                    <span class="text-[10px] font-bold tracking-wider text-amber-600 uppercase">{{ __('total_hours') }}</span>
                </div>
                <p class="text-3xl font-black text-amber-900 dark:text-amber-100">{{ summary.total_hours }}<span class="text-lg">h</span></p>
            </div>

            <div class="rounded-2xl border border-purple-200 bg-gradient-to-br from-purple-50 to-purple-100 p-5 shadow-sm dark:border-purple-800/50 dark:from-purple-900/20 dark:to-purple-800/20">
                <div class="mb-3 flex items-center justify-between">
                    <div class="flex h-10 w-10 items-center justify-center rounded-xl bg-purple-500 text-white shadow-lg"><Filter :size="19" /></div>
                    <span class="text-[10px] font-bold tracking-wider text-purple-600 uppercase">{{ __('avg_daily') }}</span>
                </div>
                <p class="text-3xl font-black text-purple-900 dark:text-purple-100">{{ summary.avg_daily }}<span class="text-lg">h</span></p>
            </div>
        </div>

        <div class="overflow-hidden rounded-2xl border border-slate-100 bg-white shadow-sm dark:border-slate-800 dark:bg-slate-900">
            <div class="overflow-x-auto">
                <table class="w-full text-sm">
                    <thead>
                        <tr class="bg-slate-50 dark:bg-slate-800/50">
                            <th class="px-6 py-4 text-left text-[10px] font-bold tracking-widest text-slate-500 uppercase">{{ __('date') }}</th>
                            <th class="px-6 py-4 text-left text-[10px] font-bold tracking-widest text-slate-500 uppercase">{{ __('clock_in') }}</th>
                            <th class="px-6 py-4 text-left text-[10px] font-bold tracking-widest text-slate-500 uppercase">{{ __('clock_out') }}</th>
                            <th class="px-6 py-4 text-left text-[10px] font-bold tracking-widest text-slate-500 uppercase">{{ __('hours') }}</th>
                            <th class="px-6 py-4 text-left text-[10px] font-bold tracking-widest text-slate-500 uppercase">{{ __('status') }}</th>
                            <th class="px-6 py-4 text-left text-[10px] font-bold tracking-widest text-slate-500 uppercase">{{ __('type') }}</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-100 dark:divide-slate-800/80">
                        <tr v-for="record in records" :key="record.id" class="transition-colors hover:bg-slate-50 dark:hover:bg-slate-800/30">
                            <td class="px-6 py-4 font-semibold text-slate-700 dark:text-slate-300">{{ formatDate(record.date) }}</td>
                            <td class="px-6 py-4 font-semibold text-slate-700 dark:text-slate-300">{{ formatTime(record.clock_in) }}</td>
                            <td class="px-6 py-4 font-semibold text-slate-700 dark:text-slate-300">{{ formatTime(record.clock_out) }}</td>
                            <td class="px-6 py-4 font-black text-sky-600 dark:text-sky-400">{{ record.total_hours || 0 }}h</td>
                            <td class="px-6 py-4">
                                <span :class="['inline-flex rounded-full px-2.5 py-0.5 text-[10px] font-bold uppercase tracking-wide', getStatusClass(record.status)]">
                                    {{ __(record.status) }}
                                </span>
                            </td>
                            <td class="px-6 py-4 text-xs font-semibold text-slate-500 capitalize dark:text-slate-400">
                                {{ record.in_type || 'auto' }} / {{ record.out_type || 'auto' }}
                            </td>
                        </tr>

                        <tr v-if="records.length === 0">
                            <td colspan="6" class="px-6 py-16 text-center">
                                <div class="mx-auto max-w-md">
                                    <div class="mx-auto mb-3 flex h-14 w-14 items-center justify-center rounded-full bg-slate-100 dark:bg-slate-800">
                                        <Calendar :size="28" class="text-slate-400" />
                                    </div>
                                    <h3 class="text-base font-bold text-slate-800 dark:text-slate-200">{{ __('no_attendance_records') }}</h3>
                                    <p class="mt-1 text-sm text-slate-500">{{ __('no_records_found_matching_criteria') }}</p>
                                </div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</template>
