<script setup lang="ts">
import { Head, Link } from '@inertiajs/vue3';
import { Plus } from '@lucide/vue';
import { computed, ref, watch } from 'vue';
import MasterOutOfStockCatalogSection from '@/components/admin/master/MasterOutOfStockCatalogSection.vue';
import RawMaterialGroupedTable from '@/components/admin/master/raw-materials/RawMaterialGroupedTable.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 { DataTableFilterDef } from '@/types/data-table';
import type { MasterOutOfStockGroup } from '@/types/master-inventory';
import type { PaginatedRawMaterials } from '@/types/raw-material';

const props = defineProps<{
    rawMaterials: PaginatedRawMaterials;
    outOfStockGroups: MasterOutOfStockGroup[];
    stockWarningGroups: MasterOutOfStockGroup[];
    filters: {
        search: string;
        sort?: string;
        direction?: 'asc' | 'desc';
        is_active?: string;
    };
}>();

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

const { query, setSearch, setFilter, resetFilters, syncFromServer } = useDataTableQuery({
    url: '/admin/master/raw-materials',
    initial: { ...props.filters },
    filterKeys: ['is_active'],
});

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

const filterDefs = computed<DataTableFilterDef[]>(() => [
    {
        key: 'is_active',
        label: 'Status',
        type: 'select',
        options: [
            { value: '1', label: 'Aktif' },
            { value: '0', label: 'Nonaktif' },
        ],
    },
]);

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

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

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

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

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

<template>

    <Head title="Bahan Baku" />

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

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

        <MasterOutOfStockCatalogSection
            severity="warning"
            title="Bahan Baku Stok Menipis"
            description="Stok masih ada, tapi di bawah batas minimum satuan · klik kartu atau varian untuk edit"
            empty-title="Tidak ada peringatan stok"
            empty-description="Semua varian masih berada di atas batas stok minimum."
            :groups="stockWarningGroups"
        />

        <MasterOutOfStockCatalogSection
            title="Bahan Baku Stok Habis"
            description="Klik kartu atau varian untuk membuka halaman edit"
            :groups="outOfStockGroups"
        />

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