<script setup lang="ts">
import MediaThumbnailCell from '@/components/media/MediaThumbnailCell.vue';
import OwnerVerificationRowActions from '@/components/owner-verification/OwnerVerificationRowActions.vue';
import { Badge } from '@/components/ui/badge';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import type { CuttingListItem } from '@/types/cutting';

interface GroupedCuttingMaterials {
    rawMaterialId: number;
    rawMaterialName: string;
    unitLabel?: string;
    items: any[];
    isCombination?: boolean;
}

defineProps<{
    cuttings: CuttingListItem[];
}>();

function getGroupedMaterials(materials: any[]): GroupedCuttingMaterials[] {
    const combinationGroups: Record<number, any[]> = {};
    const nonCombinationItems: any[] = [];

    materials.forEach((item) => {
        if (item.combination_id) {
            if (!combinationGroups[item.combination_id]) {
                combinationGroups[item.combination_id] = [];
            }

            combinationGroups[item.combination_id].push(item);
        } else {
            nonCombinationItems.push(item);
        }
    });

    const result: GroupedCuttingMaterials[] = [];

    Object.entries(combinationGroups).forEach(([combinationId, items]) => {
        const firstItem = items[0];
        const rawMaterialName = firstItem.raw_material_name || 'Bahan Baku Tidak Diketahui';
        const unitLabel = firstItem.raw_material_unit_label;

        result.push({
            rawMaterialId: Number(combinationId) * -1,
            rawMaterialName: `Kombinasi`,
            unitLabel,
            items,
            isCombination: true,
        });
    });

    const groups: Record<number, GroupedCuttingMaterials> = {};

    nonCombinationItems.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: [],
            };
        }

        groups[rawMaterialId].items.push(item);
    });

    result.push(...Object.values(groups));

    return result;
}
</script>

<template>
    <div v-if="cuttings.length" class="space-y-4">
        <div v-for="cutting in cuttings" :key="cutting.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="min-w-0 space-y-2">
                    <div class="flex flex-wrap items-center gap-2">
                        <h3 class="font-medium leading-tight">
                            Cutting #{{ cutting.id }}
                        </h3>
                        <Badge variant="secondary">Menunggu Persetujuan</Badge>
                    </div>
                    <div class="text-muted-foreground text-sm">
                        <p>{{ cutting.created_at_formatted }}</p>
                        <p v-if="cutting.submitted_by">
                            Diajukan oleh {{ cutting.submitted_by.profile?.full_name ?? cutting.submitted_by.username }}
                        </p>
                        <p v-if="cutting.rejection?.reason">
                            Catatan: {{ cutting.rejection.reason }}
                        </p>
                    </div>
                    <div class="flex flex-wrap gap-x-4 gap-y-1 text-sm">
                        <span>Total Hasil Cutting <strong class="text-primary">{{ cutting.total_result_pieces ??
                            0 }} pcs</strong></span>
                    </div>
                </div>

                <div class="flex shrink-0 items-center justify-end gap-2 sm:pt-0.5">
                    <OwnerVerificationRowActions type="cutting" :id="cutting.id" />
                </div>
            </div>

            <div class="p-4 space-y-4">
                <!-- Bahan Baku Section -->
                <div v-if="cutting.materials && cutting.materials.length" class="space-y-2">
                    <h4 class="text-sm font-semibold tracking-tight text-foreground">Bahan Baku</h4>
                    <div class="rounded-md border">
                        <Table>
                            <TableHeader>
                                <TableRow>
                                    <TableHead>Varian</TableHead>
                                    <TableHead>Foto</TableHead>
                                    <TableHead>Hasil</TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                <template v-for="group in getGroupedMaterials(cutting.materials)"
                                    :key="group.rawMaterialId">
                                    <TableRow class="bg-muted/20 hover:bg-muted/20">
                                        <TableCell colspan="3" class="font-semibold text-foreground">
                                            <template v-if="group.isCombination">
                                                <span class="text-primary">{{ group.rawMaterialName }}</span>
                                                <Badge variant="default" class="ml-2 font-normal">
                                                    {{ group.items.length }} bahan
                                                </Badge>
                                                <Badge
                                                    v-if="group.items[0]?.combination_material_result !== null && group.items[0]?.combination_material_result !== undefined"
                                                    variant="secondary" class="ml-2 font-normal">
                                                    Hasil: {{ group.items[0].combination_material_result }} pcs
                                                </Badge>
                                            </template>
                                            <template v-else>
                                                {{ group.rawMaterialName }}
                                                <Badge v-if="group.unitLabel" variant="secondary"
                                                    class="ml-2 font-normal">
                                                    {{ group.unitLabel }}
                                                </Badge>
                                            </template>
                                        </TableCell>
                                    </TableRow>
                                    <TableRow v-for="material in group.items" :key="material.id">
                                        <TableCell class="pl-6 font-medium">
                                            {{ material.variant }}
                                        </TableCell>
                                        <TableCell>
                                            <MediaThumbnailCell :items="material.images ?? []" :max-visible="1" />
                                        </TableCell>
                                        <TableCell class="tabular-nums">
                                            <template
                                                v-if="!group.isCombination && material.material_result !== null && material.material_result !== undefined">
                                                {{ material.material_result }} pcs
                                            </template>
                                            <template v-else>
                                                -
                                            </template>
                                        </TableCell>
                                    </TableRow>
                                </template>
                            </TableBody>
                        </Table>
                    </div>
                </div>

                <div class="space-y-2">
                    <h4 class="text-sm font-semibold tracking-tight text-foreground">Hasil Verifikasi</h4>
                    <div class="rounded-md border">
                        <Table>
                            <TableHeader>
                                <TableRow>
                                    <TableHead>Varian</TableHead>
                                    <TableHead>Foto</TableHead>
                                    <TableHead>Hasil</TableHead>
                                    <TableHead>Bagus</TableHead>
                                    <TableHead>Reject</TableHead>
                                    <TableHead>Harga</TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                <TableRow v-if="!cutting.results.length" :key="`${cutting.id}-result-empty`">
                                    <TableCell colspan="6" class="text-muted-foreground">
                                        Belum ada hasil verifikasi
                                    </TableCell>
                                </TableRow>
                                <TableRow v-for="result in cutting.results" :key="result.id">
                                    <TableCell class="font-medium">
                                        {{ result.product_variant?.product?.name }} ({{ result.product_variant?.name }})
                                    </TableCell>
                                    <TableCell>
                                        <MediaThumbnailCell :items="result.product_variant?.images ?? []"
                                            :max-visible="1" />
                                    </TableCell>
                                    <TableCell class="tabular-nums">
                                        {{ result.cutting_result }} pcs
                                    </TableCell>
                                    <TableCell class="tabular-nums">
                                        {{ result.sample }} pcs
                                    </TableCell>
                                    <TableCell class="tabular-nums">
                                        {{ result.original_outside_sample }} pcs
                                    </TableCell>
                                    <TableCell>
                                        <div v-if="cutting.result_prices?.filter(p => p.product_variant_id === result.product_variant?.id).length"
                                            class="space-y-0.5 text-xs">
                                            <div v-for="price in cutting.result_prices.filter(p => p.product_variant_id === result.product_variant?.id)"
                                                :key="price.id"
                                                class="flex items-center justify-between gap-3">
                                                <span class="text-muted-foreground">
                                                    {{ price.type_label }}
                                                </span>
                                                <span class="font-medium tabular-nums">
                                                    {{ price.price_formatted }}
                                                </span>
                                            </div>
                                        </div>
                                        <span v-else class="text-xs text-muted-foreground">-</span>
                                    </TableCell>
                                </TableRow>
                            </TableBody>
                        </Table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div v-else class="space-y-4">
        <div class="rounded-md border px-6 py-10 text-center">
            <p class="text-muted-foreground text-sm">
                Tidak ada verifikasi yang menunggu persetujuan.
            </p>
        </div>
    </div>
</template>
