<script setup lang="ts">
import { Card } from '@/components/ui/card';
import type { CuttingListItem } from '@/types/cutting';
import DataTableActions from './data-table-actions.vue';

function formatMaterialUsage(mat: any): string {
    return String(parseFloat(Number(mat.material_usage ?? 0).toFixed(2)));
}

function getMaterialUnit(mat: any): string {
    return mat.unit_abbreviation ?? '';
}

interface MaterialUsageGroup {
    total: string;
    unit: string;
}

function getGroupedMaterialUsage(materials: any[]): MaterialUsageGroup[] {
    const groups: Record<string, number> = {};

    materials.forEach((mat) => {
        const unit = mat.unit_abbreviation ?? '';
        const usage = Number(mat.material_usage ?? 0);
        groups[unit] = (groups[unit] ?? 0) + usage;
    });

    return Object.entries(groups)
        .filter(([, total]) => total > 0)
        .map(([unit, total]) => ({
            total: String(parseFloat(total.toFixed(2))),
            unit,
        }));
}

interface MaterialGroup {
    type: 'combination' | 'single';
    name: string;
    items: any[];
}

function getMaterialGroups(materials: any[]): MaterialGroup[] {
    const combinationMap: Record<number, any[]> = {};
    const singleItems: any[] = [];

    materials.forEach((mat) => {
        if (mat.combination_id) {
            if (!combinationMap[mat.combination_id]) {
                combinationMap[mat.combination_id] = [];
            }

            combinationMap[mat.combination_id].push(mat);
        } else {
            singleItems.push(mat);
        }
    });

    const result: MaterialGroup[] = [];

    Object.entries(combinationMap).forEach(([, items]) => {
        result.push({ type: 'combination', name: 'Kombinasi', items });
    });

    if (singleItems.length > 0) {
        result.push({ type: 'single', name: '', items: singleItems });
    }

    return result;
}

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

</script>

<template>
    <div v-if="cuttings.length" class="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
        <Card v-for="cutting in cuttings" :key="cutting.id"
            class="flex flex-col justify-between overflow-hidden border bg-card/50 py-0 gap-0">
            <div class="border-b bg-muted/20 px-4 py-3 flex items-center justify-between gap-2">
                <div class="min-w-0">
                    <h4 class="font-medium text-sm truncate">
                        Cutting #{{ cutting.id }}
                    </h4>
                    <span class="text-[10px] text-muted-foreground block truncate">
                        {{ cutting.created_at_formatted }}
                    </span>
                </div>
                <div class="flex shrink-0 items-center">
                    <DataTableActions :cutting="cutting" />
                </div>
            </div>

            <div class="p-4 space-y-3 flex-1 text-xs">
                <div v-if="cutting.description" class="text-muted-foreground pb-2 border-b">
                    <span class="font-medium text-foreground">Catatan:</span> {{ cutting.description }}
                </div>

                <div class="space-y-1">
                    <span class="font-medium text-foreground">Bahan Baku:</span>
                    <template v-if="cutting.materials.length">
                        <div v-for="(group, gi) in getMaterialGroups(cutting.materials)" :key="gi" class="mt-1">
                            <div v-if="group.type === 'combination'" class="mb-1">
                                <span class="text-primary font-medium text-[11px]">{{ group.name }} ({{ group.items.length }} bahan)</span>
                                <span v-if="group.items[0]?.combination_material_result !== null && group.items[0]?.combination_material_result !== undefined" class="text-primary font-medium text-[11px] ml-1">
                                    - Hasil: {{ group.items[0].combination_material_result }} pcs
                                </span>
                                <ul class="list-disc pl-4 space-y-0.5 text-muted-foreground">
                                    <li v-for="mat in group.items" :key="mat.id">
                                        {{ mat.raw_material_name }} ({{ mat.variant }}) - {{ formatMaterialUsage(mat) }} {{ getMaterialUnit(mat) }}
                                    </li>
                                </ul>
                            </div>
                            <ul v-else class="list-disc pl-4 space-y-0.5 text-muted-foreground">
                                <li v-for="mat in group.items" :key="mat.id">
                                    {{ mat.raw_material_name }} ({{ mat.variant }}) - {{ formatMaterialUsage(mat) }} {{ getMaterialUnit(mat) }}
                                    <template v-if="mat.material_result !== null && mat.material_result !== undefined">
                                        → {{ mat.material_result }} pcs
                                    </template>
                                </li>
                            </ul>
                        </div>
                    </template>
                    <ul v-else class="list-disc pl-4 space-y-0.5 text-muted-foreground">
                        <li>Belum ada bahan baku</li>
                    </ul>
                </div>

                <div class="space-y-1">
                    <span class="font-medium text-foreground">Hasil Produk:</span>
                    <ul class="list-disc pl-4 space-y-0.5 text-muted-foreground">
                        <li v-for="res in cutting.results" :key="res.id">
                            {{ res.product_variant?.product?.name }} ({{ res.product_variant?.name }})<span v-if="res.cutting_result !== null && res.cutting_result !== undefined"> - {{ res.cutting_result }} pcs</span>
                        </li>
                        <li v-if="!cutting.results.length">Belum ada hasil produk</li>
                    </ul>
                </div>

                <div v-if="cutting.results.length" class="space-y-1.5 pt-2 border-t">
                    <div v-if="cutting.results.some(res => res.cutting_result !== null && res.cutting_result !== undefined)" class="flex items-center justify-between text-[11px]">
                        <span class="text-muted-foreground">Total Hasil Cutting:</span>
                        <span class="font-semibold tabular-nums">{{ cutting.total_result_pieces ?? 0 }}
                            pcs</span>
                    </div>
                    <div v-if="cutting.materials.length" class="flex items-center justify-between text-[11px]">
                        <span class="text-muted-foreground">Total Pemakaian Bahan:</span>
                        <span class="font-semibold tabular-nums">{{ getGroupedMaterialUsage(cutting.materials).map(g => `${g.total} ${g.unit}`).join(', ') }}</span>
                    </div>
                    <div class="flex items-center justify-between text-[11px]">
                        <span class="text-muted-foreground">Biaya Bahan:</span>
                        <span class="font-semibold tabular-nums">{{ cutting.total_material_cost_formatted ?? 'Rp 0' }}</span>
                    </div>
                    <div class="flex items-center justify-between text-[11px]">
                        <span class="text-muted-foreground">Biaya per Produk:</span>
                        <span class="font-semibold tabular-nums">{{ cutting.material_cost_per_product_formatted ?? 'Rp 0' }}</span>
                    </div>
                </div>

                <div class="text-[11px] text-muted-foreground pt-2 border-t flex items-center justify-between">
                    <span>Pembuat:</span>
                    <span class="font-medium text-foreground">
                        {{ cutting.created_by?.profile?.full_name ?? cutting.created_by?.username }}
                    </span>
                </div>
            </div>
        </Card>
    </div>
</template>
