<script setup lang="ts">
import { computed } from 'vue';
import { DataTableEmpty } from '@/components/data-table';
import DataTableToolbar from '@/components/data-table/DataTableToolbar.vue';
import GroupedTableFooter from '@/components/data-table/GroupedTableFooter.vue';
import { Badge } from '@/components/ui/badge';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { useCan } from '@/composables/useCan';
import { usePaginationSummary } from '@/composables/usePaginationSummary';
import { cn } from '@/lib/utils';
import { groupedTableRowNumber } from '@/lib/grouped-table';
import {
    stokOpnameDifference,
    stokOpnameDifferenceClass,
    stokOpnameDifferenceText,
} from '@/lib/stok-opname-display';
import { stokOpnameStatusBadgeVariant } from '@/constants/stok-opname-status';
import type {
    DataTablePagination,
    DataTablePaginationLink,
} from '@/types/data-table';
import type { StokOpnameListItem } from '@/types/stok-opname';
import DataTableActions from './data-table-actions.vue';

const props = defineProps<{
    stokOpnames: StokOpnameListItem[];
    firstItem?: number;
    pagination?: DataTablePagination;
    paginationLinks?: DataTablePaginationLink[];
}>();

const search = defineModel<string>('search', { default: '' });

const emit = defineEmits<{
    edit: [item: StokOpnameListItem];
    submit: [item: StokOpnameListItem];
    verify: [item: StokOpnameListItem];
    reject: [item: StokOpnameListItem];
    'filters-reset': [];
}>();

const { can } = useCan();

const showingCount = computed(() => props.stokOpnames.length);
const paginationSummary = usePaginationSummary(() => props.pagination, showingCount, 'stok opname');

function rowNumber(index: number): number {
    return groupedTableRowNumber(props.firstItem, index);
}
</script>

<template>
    <div class="space-y-4">
        <DataTableToolbar v-model:search="search" search-placeholder="Cari stok opname..."
            @filters-reset="emit('filters-reset')" />

        <div v-if="stokOpnames.length" class="space-y-4">
            <div v-for="(stokOpname, index) in stokOpnames" :key="stokOpname.id" class="overflow-hidden rounded-md border">
                <div
                    class="flex flex-col gap-3 border-b bg-muted/30 px-4 py-3 sm:flex-row sm:items-start sm:justify-between">
                    <div class="flex min-w-0 items-start gap-3">
                        <span class="text-muted-foreground w-8 shrink-0 pt-0.5 text-center text-sm tabular-nums">
                            {{ rowNumber(index) }}
                        </span>
                        <div class="min-w-0 space-y-1">
                            <div class="flex flex-wrap items-center gap-2">
                                <h3 class="font-medium leading-tight">
                                    {{ stokOpname.opname_date_formatted }}
                                </h3>
                                <Badge
                                    :variant="stokOpnameStatusBadgeVariant(stokOpname.status)"
                                    :class="cn(stokOpname.status === 'verified' && 'bg-green-600 text-white')"
                                >
                                    {{ stokOpname.status_label }}
                                </Badge>
                            </div>
                            <div class="flex flex-wrap items-center gap-x-4 gap-y-1 text-sm text-muted-foreground">
                                <span>Oleh <strong class="text-foreground">{{ stokOpname.created_by_name }}</strong></span>
                                <span>{{ stokOpname.created_at_formatted }}</span>
                            </div>
                            <p v-if="stokOpname.notes" class="text-sm text-muted-foreground">
                                {{ stokOpname.notes }}
                            </p>
                            <p v-if="stokOpname.verification_notes" class="text-sm text-amber-600">
                                Catatan verifikasi: {{ stokOpname.verification_notes }}
                            </p>
                        </div>
                    </div>

                    <div class="flex shrink-0 items-center justify-end gap-2 sm:pt-0.5">
                        <DataTableActions
                            :stok-opname="stokOpname"
                            @edit="emit('edit', stokOpname)"
                            @submit="emit('submit', stokOpname)"
                            @verify="emit('verify', stokOpname)"
                            @reject="emit('reject', stokOpname)"
                        />
                    </div>
                </div>

                <Table>
                    <TableHeader>
                        <TableRow>
                            <TableHead class="w-12 text-center">No.</TableHead>
                            <TableHead>Produk</TableHead>
                            <TableHead>Varian</TableHead>
                            <TableHead class="text-right">Stok Sistem</TableHead>
                            <TableHead class="text-right">Stok Fisik</TableHead>
                            <TableHead class="text-right">Selisih</TableHead>
                            <TableHead>Catatan</TableHead>
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        <TableRow v-if="!stokOpname.items?.length" :key="`${stokOpname.id}-empty`">
                            <TableCell :colspan="7" class="text-muted-foreground text-center">
                                Belum ada item
                            </TableCell>
                        </TableRow>
                        <TableRow v-for="(item, rIdx) in stokOpname.items" :key="item.id">
                            <TableCell class="text-center text-muted-foreground tabular-nums">
                                {{ rIdx + 1 }}
                            </TableCell>
                            <TableCell class="font-medium">
                                {{ item.product_name }}
                            </TableCell>
                            <TableCell>
                                {{ item.variant_name }}
                            </TableCell>
                            <TableCell class="text-right tabular-nums">
                                {{ item.system_stock }}
                            </TableCell>
                            <TableCell class="text-right tabular-nums">
                                {{ item.physical_stock }}
                            </TableCell>
                            <TableCell class="text-right tabular-nums">
                                <span :class="stokOpnameDifferenceClass(stokOpnameDifference(item.physical_stock, item.system_stock))">
                                    {{ stokOpnameDifferenceText(stokOpnameDifference(item.physical_stock, item.system_stock)) }}
                                </span>
                            </TableCell>
                            <TableCell class="text-muted-foreground">
                                {{ item.notes || '-' }}
                            </TableCell>
                        </TableRow>
                    </TableBody>
                </Table>
            </div>
        </div>

        <DataTableEmpty v-else />

        <GroupedTableFooter
            :summary="paginationSummary"
            :pagination="pagination"
            :pagination-links="paginationLinks"
        />
    </div>
</template>
