<script setup lang="ts">
import OrderGroupedTable from '@/components/admin/manage/orders/OrderGroupedTable.vue';
import ThermalPrinterConnectButton from '@/components/admin/manage/orders/ThermalPrinterConnectButton.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 { PaginatedOrders } from '@/types/order';
import { Head, Link } from '@inertiajs/vue3';
import { Plus } from '@lucide/vue';
import { computed, ref, watch } from 'vue';

const props = defineProps<{
    orders: PaginatedOrders;
    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/orders',
    initial: { ...props.filters },
});

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

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

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

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

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

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

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

            <div
                class="flex shrink-0 items-center gap-2 self-start sm:self-center"
                v-if="can('orders.create')"
            >
                <ThermalPrinterConnectButton />

                <Button as-child>
                    <Link href="/admin/manage/orders/create">
                        <Plus class="size-4" />
                        Tambah
                    </Link>
                </Button>
            </div>
        </div>

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