<script setup lang="ts">
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 { ActiveStatus } from '@/constants/active-status';
import { StockStatus } from '@/constants/stock-status';
import AdminLayout from '@/layouts/AdminLayout.vue';
import type { DataTableFilterDef } from '@/types/data-table';
import type { CategoryOption, PaginatedProducts } from '@/types/product';
import { Head } from '@inertiajs/vue3';
import { computed, ref, watch } from 'vue';
import { index, create } from '@/routes/admin/master/products';
import ProductGroupedTable from './table/ProductGroupedTable.vue';

const props = defineProps<{
    products: PaginatedProducts;
    categories: CategoryOption[];
    filters: {
        search: string;
        sort?: string;
        direction?: 'asc' | 'desc';
        is_active?: string;
        category_id?: string;
        stock_status?: string;
    };
}>();

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

const { query, setSearch, setFilter, resetFilters, syncFromServer } =
    useDataTableQuery({
        url: index.url(),
        initial: { ...props.filters },
        filterKeys: ['is_active', 'category_id', 'stock_status'],
    });

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

const filterDefs = computed<DataTableFilterDef[]>(() => [
    {
        key: 'category_id',
        label: 'Kategori',
        type: 'select',
        options: props.categories.map((c) => ({
            value: String(c.value),
            label: c.label,
        })),
    },
    {
        key: 'is_active',
        label: 'Status',
        type: 'select',
        options: [
            { value: ActiveStatus.ACTIVE, label: 'Aktif' },
            { value: ActiveStatus.INACTIVE, label: 'Nonaktif' },
        ],
    },
    {
        key: 'stock_status',
        label: 'Stok',
        type: 'select',
        options: [
            { value: StockStatus.OUT_OF_STOCK, label: 'Stok Habis' },
            { value: StockStatus.LOW_STOCK, label: 'Stok Menipis' },
        ],
    },
]);

const filterValues = computed(() => ({
    category_id: query.value.category_id ?? '',
    is_active: query.value.is_active ?? '',
    stock_status: query.value.stock_status ?? '',
}));

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

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

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

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

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

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

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


        <Card class="min-w-0">
            <CardContent class="min-w-0">
                <ProductGroupedTable
                    v-model:search="search"
                    :products="products.data"
                    :first-item="firstItem"
                    :pagination="pagination"
                    :pagination-links="products.links"
                    :filter-defs="filterDefs"
                    :filter-values="filterValues"
                    @filter-change="setFilter"
                    @filters-reset="resetFilters"
                />
            </CardContent>
        </Card>
    </AdminLayout>
</template>
