<script setup lang="ts">
import { Link } from '@inertiajs/vue3';
import { computed } from 'vue';
import { DataTableEmpty } from '@/components/data-table';
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 {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { formatRupiah } from '@/lib/rupiah';
import type {
    DataTableFilterDef,
    DataTablePagination,
    DataTablePaginationLink,
} from '@/types/data-table';
import type { RawMaterialListItem } from '@/types/raw-material';
import DataTableActions from './data-table-actions.vue';
import RawMaterialStatusToggle from './raw-material-status-toggle.vue';

const props = defineProps<{
    materials: RawMaterialListItem[];
    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 showingCount = computed(() => props.materials.length);

const paginationSummary = computed(() => {
    if (!props.pagination) {
        return null;
    }

    const { total } = props.pagination;

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

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

function rowNumber(index: number): number {
    return (props.firstItem ?? 1) + 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="materials.length" class="space-y-4">
            <div v-for="(material, index) in materials" :key="material.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">
                                    {{ material.name }}
                                </h3>
                                <Badge variant="secondary">
                                    {{ material.unit_label }}
                                </Badge>
                            </div>
                            <p v-if="material.has_pending_request" class="text-sm text-amber-600">
                                Sedang menunggu verifikasi owner
                            </p>
                            <div class="flex flex-wrap items-center gap-x-4 gap-y-1 text-sm">
                                <span>
                                    Total stok <strong class="text-primary"> {{material.prices.reduce((acc, price) =>
                                        acc +
                                        Number(price.stock), 0)
                                    }}
                                        {{ material.unit_abbreviation }}
                                    </strong>
                                </span>
                                <span>
                                    Total harga <strong class="text-primary"> Rp
                                        {{formatRupiah(material.prices.reduce((acc, price) => acc +
                                            Number(price.stock) * Number(price.price), 0))
                                        }}
                                    </strong>
                                </span>
                            </div>
                        </div>
                    </div>

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

                <Table>
                    <TableHeader>
                        <TableRow>
                            <TableHead>Varian</TableHead>
                            <TableHead>Foto</TableHead>
                            <TableHead>Stok</TableHead>
                            <TableHead>Harga per Satuan</TableHead>
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        <TableRow v-if="!material.prices.length" :key="`${material.id}-empty`">
                            <TableCell colspan="4" class="text-muted-foreground">
                                Belum ada varian
                            </TableCell>
                        </TableRow>
                        <TableRow v-for="price in material.prices" :key="price.id">
                            <TableCell class="font-medium">
                                {{ price.variant }}
                            </TableCell>
                            <TableCell>
                                <MediaThumbnailCell :items="price.images ?? []" />
                            </TableCell>
                            <TableCell class="tabular-nums">
                                {{ price.stock_formatted }}
                            </TableCell>
                            <TableCell class="tabular-nums">
                                {{ price.price_formatted }}
                            </TableCell>
                        </TableRow>
                    </TableBody>
                </Table>
            </div>
        </div>

        <DataTableEmpty v-else />

        <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>
