<script setup lang="ts">
import { computed, ref } from 'vue';
import DataTableToolbar from '@/components/data-table/DataTableToolbar.vue';
import GroupedTableFooter from '@/components/data-table/GroupedTableFooter.vue';
import MediaThumbnailCell from '@/components/media/MediaThumbnailCell.vue';
import VerificationDetailModal from '@/components/owner-verification/VerificationDetailModal.vue';
import { Badge } from '@/components/ui/badge';
import {
    Empty,
    EmptyDescription,
    EmptyHeader,
    EmptyTitle,
} from '@/components/ui/empty';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { usePaginationSummary } from '@/composables/usePaginationSummary';
import { groupedTableRowNumber } from '@/lib/grouped-table';
import type {
    DataTablePagination,
    DataTablePaginationLink,
} from '@/types/data-table';
import type { PurchaseItemDetail, PurchaseListItem } from '@/types/purchase';
import DataTableActions from './data-table-actions.vue';

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

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

const emit = defineEmits<{
    'filters-reset': [];
}>();

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

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

interface ProductInfo {
    name: string;
    unitLabel?: string;
}

function productInfos(items: PurchaseItemDetail[]): ProductInfo[] {
    const map = new Map<number, ProductInfo>();

    items.forEach((item) => {
        const id = item.raw_material_id ?? 0;
        if (id && !map.has(id)) {
            map.set(id, {
                name: item.raw_material_name || 'Bahan Baku Tidak Diketahui',
                unitLabel: item.raw_material_unit_label,
            });
        }
    });

    return [...map.values()];
}

interface GroupedPurchaseItems {
    rawMaterialId: number;
    rawMaterialName: string;
    unitLabel?: string;
    items: (PurchaseItemDetail & { item_number: number })[];
}

function getGroupedItems(items: PurchaseItemDetail[]): GroupedPurchaseItems[] {
    const groups: Record<number, GroupedPurchaseItems> = {};
    let itemCounter = 0;

    items.forEach((item) => {
        const rawMaterialId = item.raw_material_id ?? 0;
        const rawMaterialName = item.raw_material_name || 'Bahan Baku Tidak Diketahui';
        const unitLabel = item.raw_material_unit_label;

        if (!groups[rawMaterialId]) {
            groups[rawMaterialId] = {
                rawMaterialId,
                rawMaterialName,
                unitLabel,
                items: [],
            };
        }

        itemCounter++;
        groups[rawMaterialId].items.push({ ...item, item_number: itemCounter });
    });

    return Object.values(groups);
}

const verificationModalOpen = ref(false);
const selectedRequestId = ref<number | null>(null);

function openVerificationDetail(requestId: number | undefined) {
    if (requestId) {
        selectedRequestId.value = requestId;
        verificationModalOpen.value = true;
    }
}
</script>

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

        <div v-if="purchases.length" class="space-y-4">
            <div v-for="(purchase, index) in purchases" :key="purchase.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">
                            <h3 class="font-medium leading-tight flex flex-wrap items-center gap-x-1">
                                <template v-for="(product, pIdx) in productInfos(purchase.items)" :key="pIdx">
                                    <span>{{ product.name }}</span>
                                    <Badge v-if="product.unitLabel" variant="secondary" class="font-normal">{{ product.unitLabel }}</Badge>
                                    <span v-if="pIdx < productInfos(purchase.items).length - 1" class="text-muted-foreground">,&nbsp;</span>
                                </template>
                            </h3>
                            <p class="text-muted-foreground text-sm">
                                Supplier: {{ purchase.supplier?.name }}
                            </p>
                            <p v-if="purchase.has_pending_request" class="text-sm text-amber-600">
                                {{ purchase.pending_request_submitted_by_name }} mengajukan {{ purchase.pending_request_action_label?.toLowerCase() }} belanja ini —
                                <button type="button" class="underline-offset-2 hover:underline" @click="openVerificationDetail(purchase.pending_request_id)">lihat</button>
                            </p>
                            <div class="text-muted-foreground space-y-1 text-sm">
                                <p>{{ purchase.created_at_formatted }}</p>
                                <p>Oleh {{ purchase.created_by?.profile?.full_name ?? purchase.created_by?.username }}
                                </p>
                            </div>
                            <div class="flex flex-wrap gap-x-4 gap-y-1 text-sm">
                                <span v-if="purchase.total_quantity_formatted">Total Jumlah
                                    <strong class="text-primary">{{ purchase.total_quantity_formatted }}</strong></span>
                                <span>Subtotal <strong class="text-primary">{{ purchase.subtotal_formatted
                                        }}</strong></span>
                                <span>Diskon <strong class="text-primary">{{ purchase.discount_formatted
                                        }}</strong></span>
                                <span v-if="purchase.shipping_cost > 0">Ongkir <strong class="text-primary">{{
                                    purchase.shipping_cost_formatted }}</strong></span>
                                <span>Total <strong class="text-primary">{{ purchase.total_formatted }}</strong></span>
                            </div>
                            <p v-if="purchase.notes" class="text-muted-foreground text-sm">
                                {{ purchase.notes }}
                            </p>
                        </div>
                    </div>

                    <div class="flex shrink-0 items-center justify-end gap-2 sm:pt-0.5">
                        <MediaThumbnailCell :items="purchase.photos ? [purchase.photos] : []" />
                        <DataTableActions :purchase="purchase" />
                    </div>
                </div>

                <Table>
                    <TableHeader>
                        <TableRow>
                            <TableHead class="w-8">#</TableHead>
                            <TableHead>Varian</TableHead>
                            <TableHead>Jumlah</TableHead>
                            <TableHead>Harga Satuan</TableHead>
                            <TableHead>Subtotal</TableHead>
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        <TableRow v-if="!purchase.items.length" :key="`${purchase.id}-empty`">
                            <TableCell colspan="5" class="text-muted-foreground">
                                Belum ada item
                            </TableCell>
                        </TableRow>
                        <template v-else v-for="group in getGroupedItems(purchase.items)" :key="group.rawMaterialId">
                            <TableRow v-for="item in group.items" :key="item.id">
                                <TableCell class="pl-6 text-center text-muted-foreground tabular-nums">
                                    {{ item.item_number }}
                                </TableCell>
                                <TableCell class="pl-6 font-medium">
                                    {{ item.variant }}
                                </TableCell>
                                <TableCell class="tabular-nums">
                                    {{ item.quantity_formatted }}
                                </TableCell>
                                <TableCell class="tabular-nums">
                                    {{ item.unit_price_formatted }}
                                </TableCell>
                                <TableCell class="tabular-nums font-medium">
                                    {{ item.subtotal_formatted }}
                                </TableCell>
                            </TableRow>
                        </template>
                    </TableBody>
                </Table>
            </div>
        </div>

        <div v-else class="rounded-md border px-6 py-10">
            <Empty>
                <EmptyHeader>
                    <EmptyTitle>Data tidak ditemukan</EmptyTitle>
                    <EmptyDescription>
                        Silakan lakukan pencarian untuk menemukan data yang Anda cari.
                    </EmptyDescription>
                </EmptyHeader>
            </Empty>
        </div>

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

        <VerificationDetailModal v-model:open="verificationModalOpen" :request-id="selectedRequestId" />
    </div>
</template>
