<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 { stokOpnameStatusBadgeVariant } from '@/constants/stok-opname-status';
import { groupedTableRowNumber } from '@/lib/grouped-table';
import {
    stokOpnameDifference,
    stokOpnameDifferenceClass,
    stokOpnameDifferenceText,
} from '@/lib/stok-opname-display';
import { cn } from '@/lib/utils';
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);
}

interface GroupedVariantItem {
    variant_id: number;
    variant_name: string;
    product_name: string;
    qualities: Array<{
        id: number;
        quality_label: string;
        quality_key: string;
        system_stock: number;
        physical_stock: number;
        difference: number;
        notes: string | null;
    }>;
}

function getGroupedItems(items: any[]): GroupedVariantItem[] {
    const groups: Record<string, GroupedVariantItem> = {};

    items.forEach((item) => {
        const variantName = item.product_variant?.name || item.variant_name.replace(/\s*\([^)]*\)$/, '');
        const key = `${item.product_variant_id}`;

        if (!groups[key]) {
            groups[key] = {
                variant_id: item.product_variant_id,
                variant_name: variantName,
                product_name: item.product_name,
                qualities: [],
            };
        }

        const label = item.stock_quality === 'good' ? 'Bagus' : (item.stock_quality === 'retail' ? 'Eceran' : 'Reject');

        groups[key].qualities.push({
            id: item.id,
            quality_key: item.stock_quality,
            quality_label: label,
            system_stock: item.system_stock,
            physical_stock: item.physical_stock,
            difference: item.difference,
            notes: item.notes,
        });
    });

    return Object.values(groups);
}
</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 class="bg-muted/10">
                            <TableHead class="w-12 text-center border-r">No.</TableHead>
                            <TableHead class="border-r">Produk</TableHead>
                            <TableHead class="border-r">Varian</TableHead>
                            <TableHead class="border-r w-28">Kualitas</TableHead>
                            <TableHead class="text-right border-r w-28">Stok Sistem</TableHead>
                            <TableHead class="text-right border-r w-28">Stok Fisik</TableHead>
                            <TableHead class="text-right border-r w-28">Selisih</TableHead>
                            <TableHead>Catatan</TableHead>
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        <TableRow v-if="!stokOpname.items?.length" :key="`${stokOpname.id}-empty`">
                            <TableCell :colspan="8" class="text-muted-foreground text-center">
                                Belum ada item
                            </TableCell>
                        </TableRow>
                        <template v-else v-for="(vGroup, vIdx) in getGroupedItems(stokOpname.items)" :key="vGroup.variant_id">
                            <TableRow
                                v-for="(qRow, qIdx) in vGroup.qualities"
                                :key="qRow.id"
                                class="border-b hover:bg-muted/10"
                            >
                                <td
                                    v-if="qIdx === 0"
                                    :rowspan="vGroup.qualities.length"
                                    class="text-center text-muted-foreground tabular-nums border-r align-middle font-medium"
                                >
                                    {{ vIdx + 1 }}
                                </td>
                                <td
                                    v-if="qIdx === 0"
                                    :rowspan="vGroup.qualities.length"
                                    class="font-semibold border-r align-middle"
                                >
                                    {{ vGroup.product_name }}
                                </td>
                                <td
                                    v-if="qIdx === 0"
                                    :rowspan="vGroup.qualities.length"
                                    class="font-medium border-r align-middle bg-muted/5"
                                >
                                    {{ vGroup.variant_name }}
                                </td>

                                <td class="p-3 border-r text-left font-medium">
                                    <Badge :variant="qRow.quality_key === 'good' ? 'outline' : (qRow.quality_key === 'retail' ? 'secondary' : 'destructive')" class="text-xs font-normal">
                                        {{ qRow.quality_label }}
                                    </Badge>
                                </td>
                                <td class="p-3 border-r text-right tabular-nums">
                                    {{ qRow.system_stock }}
                                </td>
                                <td class="p-3 border-r text-right tabular-nums">
                                    {{ qRow.physical_stock }}
                                </td>
                                <td class="p-3 border-r text-right tabular-nums font-semibold">
                                    <span :class="stokOpnameDifferenceClass(qRow.difference)">
                                        {{ stokOpnameDifferenceText(qRow.difference) }}
                                    </span>
                                </td>
                                <td class="p-3 text-muted-foreground">
                                    {{ qRow.notes || '-' }}
                                </td>
                            </TableRow>
                        </template>
                    </TableBody>
                </Table>
            </div>
        </div>

        <DataTableEmpty v-else />

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