<script setup lang="ts">
import { Head, Link } from '@inertiajs/vue3';
import { Plus } from '@lucide/vue';
import { computed, ref, watch } from 'vue';
import { columns } from './table/columns';
import { DataTable } from '@/components/data-table';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { useCan } from '@/composables/useCan';
import { ActiveStatus } from '@/constants/active-status';
import {
    useDataTableQuery,
    useDataTableQuerySync,
} from '@/composables/useDataTableQuery';
import AdminLayout from '@/layouts/AdminLayout.vue';
import type { DataTableFilterDef, DataTableSort } from '@/types/data-table';
import type { EnumOption, PaginatedEmployees } from '@/types/employee';

const props = defineProps<{
    employees: PaginatedEmployees;
    filters: {
        search: string;
        sort?: string;
        direction?: 'asc' | 'desc';
        role?: string;
        gender?: string;
        employment_status?: string;
        is_active?: string;
    };
    roles: EnumOption[];
    genders: EnumOption[];
    employmentStatuses: EnumOption[];
}>();

const { can } = useCan();
const search = ref(props.filters.search ?? '');

const { query, setSearch, setSort, setFilter, resetFilters, syncFromServer } = useDataTableQuery({
    url: '/admin/hr/employees',
    initial: { ...props.filters },
    filterKeys: ['role', 'gender', 'employment_status', 'is_active'],
});

useDataTableQuerySync(() => props.filters, syncFromServer);

const filterDefs = computed<DataTableFilterDef[]>(() => [
    {
        key: 'role',
        label: 'Role',
        type: 'select',
        options: props.roles,
    },
    {
        key: 'gender',
        label: 'Jenis Kelamin',
        type: 'select',
        options: props.genders,
    },
    {
        key: 'employment_status',
        label: 'Status Kepegawaian',
        type: 'select',
        options: props.employmentStatuses,
    },
    {
        key: 'is_active',
        label: 'Status Akun',
        type: 'select',
        options: [
            { value: ActiveStatus.ACTIVE, label: 'Aktif' },
            { value: ActiveStatus.INACTIVE, label: 'Nonaktif' },
        ],
    },
]);

const filterValues = computed(() => ({
    role: query.value.role ?? '',
    gender: query.value.gender ?? '',
    employment_status: query.value.employment_status ?? '',
    is_active: query.value.is_active ?? '',
}));

const currentSort = computed<DataTableSort | null>(() => {
    if (!query.value.sort || !query.value.direction) {
        return null;
    }

    return {
        column: query.value.sort,
        direction: query.value.direction,
    };
});

const pagination = computed(() => ({
    currentPage: props.employees.current_page,
    perPage: props.employees.per_page,
    lastPage: props.employees.last_page,
    total: props.employees.total,
}));

watch(search, (value) => {
    setSearch(value);
});

watch(
    () => props.filters.search,
    (value) => {
        search.value = value ?? '';
    },
);
</script>

<template>
    <Head title="Pegawai" />

    <AdminLayout>
        <div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
            <div class="space-y-1">
                <h2 class="text-2xl font-bold tracking-tight">Pegawai</h2>
            </div>

            <Button v-if="can('employees.create')" as-child class="shrink-0 self-start sm:self-center">
                <Link href="/admin/hr/employees/create">
                    <Plus class="size-4" />
                    Tambah
                </Link>
            </Button>
        </div>

        <Card class="min-w-0">
            <CardContent class="min-w-0">
                <DataTable
                    v-model:search="search"
                    :columns="columns"
                    :data="employees.data"
                    :pagination="pagination"
                    :pagination-links="employees.links"
                    :sort="currentSort"
                    :filter-defs="filterDefs"
                    :filter-values="filterValues"
                    @sort-change="setSort"
                    @filter-change="setFilter"
                    @filters-reset="resetFilters"
                />
            </CardContent>
        </Card>
    </AdminLayout>
</template>
