<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 MediaThumbnailCell from '@/components/media/MediaThumbnailCell.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 { groupedTableRowNumber } from '@/lib/grouped-table';
import type {
    DataTableFilterDef,
    DataTablePagination,
    DataTablePaginationLink,
} from '@/types/data-table';
import {
    PRICE_TYPES,
    PRICE_TYPE_LABELS,
} from '@/types/product';
import type { ProductListItem, Variant } from '@/types/product';
import DataTableActions from './data-table-actions.vue';
import ProductStatusToggle from './product-status-toggle.vue';

const props = defineProps<{
    products: ProductListItem[];
    firstItem?: number;
    pagination?: DataTablePagination;
    paginationLinks?: DataTablePaginationLink[];
    filterDefs?: DataTableFilterDef[];
    filterValues?: Record<string, string>;
}>();

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

const emit = defineEmits<{
    'filter-change': [key: string, value: string];
    'filters-reset': [];
}>();

const { can } = useCan();

const showingCount = computed(() => props.products.length);
const paginationSummary = usePaginationSummary(() => props.pagination, showingCount, 'produk');

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

<template>
    <div class="space-y-4">
        <DataTableToolbar v-model:search="search" :filter-defs="filterDefs" :filter-values="filterValues"
            @filter-change="(key, value) => emit('filter-change', key, value)" @filters-reset="emit('filters-reset')" />

        <div v-if="products.length" class="space-y-4">
            <div v-for="(product, index) in products" :key="product.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-2">
                            <div class="flex flex-wrap items-center gap-2">
                                <h3 class="font-medium leading-tight">
                                    {{ product.name }}
                                </h3>
                            </div>
                            <p v-if="product.has_pending_request" class="text-sm text-amber-600">
                                Sedang menunggu verifikasi owner
                            </p>
                            <div v-if="product.categories.length" class="flex flex-wrap gap-1">
                                <Badge v-for="category in product.categories" :key="category.id" variant="outline">
                                    {{ category.name }}
                                </Badge>
                            </div>
                            <div class="flex flex-wrap items-center gap-x-4 gap-y-1 text-sm">
                                <span>
                                    Total stok bagus <strong class="text-primary">
                                        {{ product.total_stock_formatted }}
                                    </strong>
                                </span>
                                <span>
                                    Total stok reject <strong class="text-destructive">
                                        {{ product.total_reject_stock_formatted }}
                                    </strong>
                                </span>
                                <span>
                                    Total stok ecer <strong class="text-blue-600">
                                        {{ product.total_retail_stock_formatted }}
                                    </strong>
                                </span>
                            </div>
                        </div>
                    </div>

                    <div class="flex shrink-0 items-center justify-end gap-2 sm:pt-0.5">
                        <ProductStatusToggle :product="product" />
                        <DataTableActions :product="product" />
                    </div>
                </div>

                <Table>
                    <TableHeader>
                        <TableRow>
                            <TableHead>Varian</TableHead>
                            <TableHead>Foto</TableHead>
                            <TableHead>Stok Bagus</TableHead>
                            <TableHead>Stok Reject</TableHead>
                            <TableHead>Stok Ecer</TableHead>
                            <TableHead>Harga</TableHead>
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        <TableRow v-if="!product.variants.length" :key="`${product.id}-empty`">
                            <TableCell :colspan="6" class="text-muted-foreground">
                                Belum ada varian
                            </TableCell>
                        </TableRow>
                        <TableRow v-for="variant in product.variants" :key="variant.id">
                            <TableCell class="font-medium">
                                {{ variant.name }}
                            </TableCell>
                            <TableCell>
                                <MediaThumbnailCell :items="variant.images ?? []" />
                            </TableCell>
                            <TableCell class="tabular-nums">
                                {{ variant.stock_formatted }}
                            </TableCell>
                            <TableCell class="tabular-nums text-destructive">
                                {{ variant.reject_stock_formatted }}
                            </TableCell>
                            <TableCell class="tabular-nums text-blue-600">
                                {{ variant.retail_stock_formatted }}
                            </TableCell>
                            <TableCell>
                                <div v-if="variant.prices?.length" class="space-y-0.5 text-xs">
                                    <div v-for="type in PRICE_TYPES" :key="type">
                                        <div v-if="variant.prices?.find((item) => item.type === type)"
                                            class="flex items-center justify-between gap-3">
                                            <span class="text-muted-foreground">
                                                {{ PRICE_TYPE_LABELS[type] }}
                                            </span>
                                            <span class="font-medium tabular-nums">
                                                {{
                                                    variant.prices?.find((item) => item.type === type)?.price_formatted
                                                }}
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <span v-else class="text-xs text-muted-foreground">Belum ada harga</span>
                            </TableCell>
                        </TableRow>
                    </TableBody>
                </Table>
            </div>
        </div>

        <DataTableEmpty v-else />

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