<script setup lang="ts">
import CreateButton from '@/components/button/CreateButton.vue';
import ConfirmDialog from '@/components/ConfirmDialog.vue';
import { DataTable } from '@/components/data-table';
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 { DataTableSort } from '@/types/data-table';
import type { PaginatedStokOpnames, StokOpnameListItem } from '@/types/stok-opname';
import { Head, router } from '@inertiajs/vue3';
import { computed, ref, watch } from 'vue';
import { createColumns } from './table/columns';
import { index, create, edit, submit, verify, reject, destroy } from '@/routes/admin/manage/stok-opnames';

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

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

const submitDialogOpen = ref(false);
const verifyDialogOpen = ref(false);
const rejectDialogOpen = ref(false);
const selectedStokOpname = ref<StokOpnameListItem | null>(null);
const rejectReason = ref('');

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

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

const currentSort = computed<DataTableSort | null>(() => {
    if (!query.value.sort || !query.value.direction) {
        return null;
    }
    return {
        column: query.value.sort,
        direction: query.value.direction,
    };
});

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

function openEdit(item: StokOpnameListItem) {
    router.get(edit.url(item.id));
}

function openSubmitDialog(item: StokOpnameListItem) {
    selectedStokOpname.value = item;
    submitDialogOpen.value = true;
}

function openVerifyDialog(item: StokOpnameListItem) {
    selectedStokOpname.value = item;
    verifyDialogOpen.value = true;
}

function openRejectDialog(item: StokOpnameListItem) {
    selectedStokOpname.value = item;
    rejectReason.value = '';
    rejectDialogOpen.value = true;
}

function confirmSubmit() {
    if (!selectedStokOpname.value) return;
    router.post(submit.url(selectedStokOpname.value.id));
    submitDialogOpen.value = false;
}

function confirmVerify() {
    if (!selectedStokOpname.value) return;
    router.post(verify.url(selectedStokOpname.value.id));
    verifyDialogOpen.value = false;
}

function confirmReject() {
    if (!selectedStokOpname.value || !rejectReason.value.trim()) return;
    router.post(reject.url(selectedStokOpname.value.id), {
        reason: rejectReason.value,
    });
    rejectDialogOpen.value = false;
}

const columns = computed(() =>
    createColumns(openEdit, openSubmitDialog, openVerifyDialog, openRejectDialog)
);

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

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

<template>
    <Head title="Stok Opname" />

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

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

        <Card class="min-w-0">
            <CardContent class="min-w-0">
                <DataTable
                    v-model:search="search"
                    :columns="columns"
                    :data="stokOpnames.data"
                    :pagination="pagination"
                    :pagination-links="stokOpnames.links"
                    :sort="currentSort"
                    @sort-change="setSort"
                    @filters-reset="resetFilters"
                />
            </CardContent>
        </Card>

        <ConfirmDialog
            v-model:open="submitDialogOpen"
            title="Ajukan Verifikasi"
            description="Stok opname akan diajukan untuk diverifikasi. Lanjutkan?"
            confirm-label="Ajukan"
            @confirm="confirmSubmit"
        />

        <ConfirmDialog
            v-model:open="verifyDialogOpen"
            title="Verifikasi Stok Opname"
            description="Stok opname akan diverifikasi dan stok gudang akan disesuaikan. Lanjutkan?"
            confirm-label="Verifikasi"
            @confirm="confirmVerify"
        />

        <ConfirmDialog
            v-model:open="rejectDialogOpen"
            title="Tolak Stok Opname"
            description="Masukkan alasan penolakan:"
            confirm-label="Tolak"
            @confirm="confirmReject"
        >
            <template #content>
                <textarea
                    v-model="rejectReason"
                    class="border-input bg-background ring-offset-background placeholder:text-muted-foreground focus-visible:ring-ring flex min-h-[80px] w-full rounded-md border px-3 py-2 text-sm focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50"
                    placeholder="Alasan penolakan..."
                />
            </template>
        </ConfirmDialog>
    </AdminLayout>
</template>
