<script setup lang="ts">
import { Head } from '@inertiajs/vue3';
import { computed, ref, watch } from 'vue';
import CreateButton from '@/components/button/CreateButton.vue';
import { Card, CardContent } from '@/components/ui/card';
import { useCan } from '@/composables/useCan';
import {
    useDataTableQuery,
    useDataTableQuerySync,
} from '@/composables/useDataTableQuery';
import AdminLayout from '@/layouts/AdminLayout.vue';
import { index, create } from '@/routes/admin/manage/restocks';
import type { PaginatedRestocks } from '@/types/restock';
import RestockGroupedTable from './table/RestockGroupedTable.vue';

const props = defineProps<{
    restocks: PaginatedRestocks;
    filters: {
        search: string;
        sort?: string;
        direction?: 'asc' | 'desc';
    };
}>();

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

const { setSearch, resetFilters, syncFromServer } = useDataTableQuery({
    url: index.url(),
    initial: { ...props.filters },
});

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

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

const firstItem = computed(() =>
    props.restocks.data.length > 0
        ? (props.restocks.current_page - 1) * props.restocks.per_page + 1
        : 0,
);

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

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

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

    <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">Restock</h2>
            </div>

            <CreateButton
                v-if="can('restocks.create')"
                :href="create.url()"
            />
        </div>

        <Card class="min-w-0">
            <CardContent class="min-w-0">
                <RestockGroupedTable
                    v-model:search="search"
                    :restocks="restocks.data"
                    :first-item="firstItem"
                    :pagination="tablePagination"
                    :pagination-links="restocks.links"
                    @filters-reset="resetFilters"
                />
            </CardContent>
        </Card>
    </AdminLayout>
</template>
