<script setup lang="ts">
import { computed, ref } from 'vue';
import { RowEditAction, RowHistoryAction } from '@/components/button';
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 { usePaginationSummary } from '@/composables/usePaginationSummary';
import { groupedTableRowNumber } from '@/lib/grouped-table';
import type {
    DataTableFilterDef,
    DataTablePagination,
    DataTablePaginationLink,
} from '@/types/data-table';
import type { RawMaterialListItem, RawMaterialPrice } from '@/types/raw-material';
import RawMaterialVariantEditModal from '../form/RawMaterialVariantEditModal.vue';
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>;
    loading?: boolean;
}>();

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 = usePaginationSummary(() => props.pagination, showingCount, 'bahan baku');

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

function allVariantImageUrls(material: RawMaterialListItem): string[] {
    return material.prices.flatMap((price) => (price.images ?? []).map((img) => img.url));
}

function allVariantImageTitles(material: RawMaterialListItem): string[] {
    return material.prices.flatMap((price) =>
        (price.images ?? []).map(() => `${material.name} - ${price.variant}`)
    );
}

function allVariantImageStocks(material: RawMaterialListItem): string[] {
    return material.prices.flatMap((price) =>
        (price.images ?? []).map(() => `Stok: ${price.stock_formatted}`)
    );
}

import { history as stockHistory } from '@/routes/admin/manage/stock';

// ─── Modal Edit Varian State ─────────────────────────────────────────────────
const isEditing = ref(false);
const editingMaterial = ref<RawMaterialListItem | null>(null);
const editingPrice = ref<RawMaterialPrice | null>(null);

function openEditModal(price: RawMaterialPrice, material: RawMaterialListItem) {
    editingMaterial.value = material;
    editingPrice.value = price;
    isEditing.value = true;
}
</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 class="relative min-h-[100px]">
            <!-- Subtle loading bar — tidak ganggu layout -->
            <div v-if="loading" class="absolute top-0 left-0 right-0 h-0.5 z-10 overflow-hidden bg-primary/10">
                <div class="h-full w-1/3 animate-[loading-bar_1.2s_ease-in-out_infinite] bg-primary rounded-full" />
            </div>

            <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 bg-background">
                    <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-semibold leading-tight text-foreground text-base">
                                        {{ material.name }}
                                    </h3>
                                    <Badge variant="secondary">
                                        {{ material.unit_label }}
                                    </Badge>
                                </div>
                                <div class="flex flex-wrap items-center gap-x-4 gap-y-1 text-sm text-muted-foreground">
                                    <span>
                                        Total stok <strong class="text-primary font-semibold">
                                            {{ material.total_stock_formatted }}
                                        </strong>
                                    </span>
                                    <span>
                                        Total harga <strong class="text-primary font-semibold">
                                            {{ material.total_inventory_value_formatted }}
                                        </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 class="w-10">#</TableHead>
                                <TableHead>Varian</TableHead>
                                <TableHead>Foto</TableHead>
                                <TableHead>Stok</TableHead>
                                <TableHead>Harga per Satuan</TableHead>
                                <TableHead class="w-24 text-center">Aksi</TableHead>
                            </TableRow>
                        </TableHeader>
                        <TableBody>
                            <TableRow v-if="!material.prices.length" :key="`${material.id}-empty`">
                                <TableCell colspan="6" class="text-muted-foreground text-center">
                                    Belum ada varian
                                </TableCell>
                            </TableRow>
                            <TableRow v-for="(price, priceIndex) in material.prices" :key="price.id">
                                <TableCell class="text-muted-foreground tabular-nums text-center">
                                    {{ priceIndex + 1 }}
                                </TableCell>
                                <TableCell class="font-medium">
                                    {{ price.variant }}
                                </TableCell>
                                <TableCell>
                                    <MediaThumbnailCell :items="price.images ?? []" :max-visible="1"
                                        :title="`${material.name} - ${price.variant}`"
                                        :all-urls="allVariantImageUrls(material)"
                                        :all-titles="allVariantImageTitles(material)"
                                        :all-stocks="allVariantImageStocks(material)" />
                                </TableCell>
                                <TableCell class="tabular-nums">
                                    {{ price.stock_formatted }}
                                </TableCell>
                                <TableCell class="tabular-nums">
                                    {{ price.price_formatted }}
                                </TableCell>
                                <TableCell class="text-center">
                                    <div class="flex items-center justify-center gap-1">
                                        <RowHistoryAction
                                            :href="stockHistory.url({ query: { stockable_type: 'raw-material-price', stockable_id: price.id } })"
                                            tooltip="Riwayat Stok" />
                                        <RowEditAction tooltip="Ubah Varian"
                                            @click="openEditModal(price, material)" />
                                    </div>
                                </TableCell>
                            </TableRow>
                        </TableBody>
                    </Table>
                </div>
            </div>

            <DataTableEmpty v-else />
        </div>

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

        <!-- Dialog Modal Edit Varian -->
        <RawMaterialVariantEditModal
            v-model:open="isEditing"
            :price="editingPrice"
            :material="editingMaterial"
        />
    </div>
</template>
