<script setup lang="ts">
import { Head, Link } from '@inertiajs/vue3';
import { Plus } from '@lucide/vue';
import { computed, ref, watch } from 'vue';
import CuttingGroupedTable from '@/components/admin/manage/cuttings/CuttingGroupedTable.vue';
import CuttingInProgressSection from '@/components/admin/manage/cuttings/CuttingInProgressSection.vue';
import { Button } from '@/components/ui/button';
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 type { PaginatedCuttings, CuttingListItem } from '@/types/cutting';

const props = defineProps<{
    cuttings: PaginatedCuttings;
    inProgressCuttings: CuttingListItem[];
    filters: {
        search: string;
        sort?: string;
        direction?: 'asc' | 'desc';
    };
}>();

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

const { setSearch, resetFilters, syncFromServer } = useDataTableQuery({
    url: '/admin/manage/cuttings',
    initial: { ...props.filters },
});

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

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

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

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

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

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

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

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

        <CuttingInProgressSection :cuttings="inProgressCuttings" />

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