<script setup lang="ts">
import { Link } from '@inertiajs/vue3';
import { computed } from 'vue';
import DataTableActions from '@/components/admin/manage/purchases/data-table-actions.vue';
import DataTableToolbar from '@/components/data-table/DataTableToolbar.vue';
import MediaThumbnailCell from '@/components/media/MediaThumbnailCell.vue';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
    Empty,
    EmptyDescription,
    EmptyHeader,
    EmptyTitle,
} from '@/components/ui/empty';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import type {
    DataTablePagination,
    DataTablePaginationLink,
} from '@/types/data-table';
import type { PurchaseListItem } from '@/types/purchase';

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 = computed(() => {
    if (!props.pagination) {
        return null;
    }

    const { total } = props.pagination;

    if (total === 0) {
        return 'Menampilkan 0 belanja';
    }

    return `Menampilkan ${showingCount.value} belanja dari ${total}`;
});

function rowNumber(index: number): number {
    return (props.firstItem ?? 1) + index;
}

interface GroupedPurchaseItems {
    rawMaterialId: number;
    rawMaterialName: string;
    unitLabel?: string;
    items: any[];
}

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

    items.forEach((item) => {
        const rawMaterial = item.raw_material_price?.raw_material;
        const rawMaterialId = rawMaterial?.id ?? 0;
        const rawMaterialName = rawMaterial?.name ?? 'Bahan Baku Tidak Diketahui';
        const unitLabel = rawMaterial?.unit_label;

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

    return Object.values(groups);
}
</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">
                                {{ purchase.supplier?.name }}
                            </h3>
                            <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>Subtotal <strong class="text-foreground">{{ purchase.subtotal_formatted
                                }}</strong></span>
                                <span>Diskon <strong class="text-foreground">{{ purchase.discount_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>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="4" class="text-muted-foreground">
                                Belum ada item
                            </TableCell>
                        </TableRow>
                        <template v-else v-for="group in getGroupedItems(purchase.items)" :key="group.rawMaterialId">
                            <TableRow class="bg-muted/20 hover:bg-muted/20">
                                <TableCell colspan="4" class="font-semibold text-foreground">
                                    {{ group.rawMaterialName }}
                                    <Badge v-if="group.unitLabel" variant="secondary" class="ml-2 font-normal">
                                        {{ group.unitLabel }}
                                    </Badge>
                                </TableCell>
                            </TableRow>
                            <TableRow v-for="item in group.items" :key="item.id">
                                <TableCell class="pl-6 font-medium">
                                    {{ item.raw_material_price?.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>

        <div v-if="pagination" class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
            <p class="text-muted-foreground text-sm">
                {{ paginationSummary }}
            </p>

            <div v-if="paginationLinks?.length && pagination.lastPage > 1"
                class="flex flex-wrap items-center justify-center gap-1 sm:justify-end">
                <Button v-for="link in paginationLinks" :key="`${link.label}-${link.url}`" variant="outline" size="sm"
                    :disabled="!link.url || link.active" as-child>
                    <Link v-if="link.url" :href="link.url" preserve-scroll>
                        <span v-html="link.label" />
                    </Link>
                    <span v-else v-html="link.label" />
                </Button>
            </div>
        </div>
    </div>
</template>
