<script setup lang="ts">
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { Separator } from '@/components/ui/separator';
import { formatRupiah } from '@/lib/rupiah';
import type { FormWithErrors } from '@/lib/form';
import type { CuttingMaterialCartItem, CuttingResultCartItem } from '@/types/cutting';
import CuttingPosMaterialSummaryItems from './CuttingPosMaterialSummaryItems.vue';
import CuttingPosResultSummaryItems from './CuttingPosResultSummaryItems.vue';

defineProps<{
    form: FormWithErrors & { description: string; processing?: boolean };
    materialCart: CuttingMaterialCartItem[];
    resultCart: CuttingResultCartItem[];
    materialLineCost: (item: CuttingMaterialCartItem) => number;
    totalMaterialCost: number;
    totalResultPieces: number;
    isCreateMode: boolean;
}>();

const emit = defineEmits<{
    'remove-material': [index: number];
    'sync-material-field': [index: number];
    'remove-combination': [combinationId: number];
    'sync-combination-result': [combinationId: number, result: number | null];
}>();

const open = defineModel<boolean>('open', { required: true });
</script>

<template>
    <Dialog v-model:open="open">
        <DialogContent class="sm:max-w-lg min-w-0 max-h-[90dvh] flex flex-col">
            <DialogHeader>
                <DialogTitle>Detail Keranjang</DialogTitle>
            </DialogHeader>
            <div class="scrollbar-thin flex-1 overflow-y-auto overscroll-y-contain pr-1 space-y-4">
                <div v-if="materialCart.length > 0">
                    <p class="mb-2 text-xs font-medium text-muted-foreground">Bahan Baku</p>
                    <CuttingPosMaterialSummaryItems :form="form" :material-cart="materialCart"
                        @remove="emit('remove-material', $event)" @sync-field="emit('sync-material-field', $event)"
                        @remove-combination="emit('remove-combination', $event)"
                        @sync-combination-result="(combinationId, result) => emit('sync-combination-result', combinationId, result)" />
                </div>
                <Separator v-if="materialCart.length > 0 && resultCart.length > 0" />
                <div v-if="resultCart.length > 0">
                    <p class="mb-2 text-xs font-medium text-muted-foreground">Hasil Produk</p>
                    <CuttingPosResultSummaryItems :form="form" :result-cart="resultCart"
                        :total-result-pieces="totalResultPieces" :is-create-mode="isCreateMode" />
                </div>
            </div>
            <div class="border-t pt-3">
                <div class="flex items-center justify-between text-sm font-semibold">
                    <span>Total Biaya Bahan</span>
                    <span class="text-primary">Rp {{ formatRupiah(totalMaterialCost) }}</span>
                </div>
            </div>
        </DialogContent>
    </Dialog>
</template>
