<script setup lang="ts">
import { Head } from '@inertiajs/vue3';
import { computed } from 'vue';
import BackButton from '@/components/button/BackButton.vue';
import AdminLayout from '@/layouts/AdminLayout.vue';
import { index, update } from '@/routes/admin/manage/cuttings';
import type {
    CuttingEditItem,
    CuttingProductCatalogItem,
    CuttingRawMaterialCatalogItem,
} from '@/types/cutting';
import type { CategoryOption } from '@/types/product';
import type { EnumOption } from '@/types/raw-material';
import CuttingPosForm from './form/CuttingPosForm.vue';

const props = defineProps<{
    cutting: CuttingEditItem;
    rawMaterialCatalog: CuttingRawMaterialCatalogItem[];
    productCatalog: CuttingProductCatalogItem[];
    categories: CategoryOption[];
    units: EnumOption[];
}>();

const initialData = computed(() => ({
    description: props.cutting.description ?? '',
    images: props.cutting.images ?? [],
    sewing_cost: String(props.cutting.sewing_cost ?? 0),
    other_cost: String(props.cutting.other_cost ?? 0),
    materials: props.cutting.materials.map((item) => ({
        raw_material_price_id: item.raw_material_price_id,
        raw_material_name: item.raw_material_name ?? '',
        variant: item.variant ?? '',
        unit: item.unit ?? 'kilogram',
        unit_abbreviation: item.unit_abbreviation ?? '',
        stock_input: item.stock_input ?? '',
        material_usage: item.material_usage_input,
        material_result: item.material_result_input !== null && item.material_result_input !== undefined ? String(item.material_result_input) : null,
        images: item.images ?? [],
        combination_id: item.combination_id ?? null,
        combination_material_result: item.combination_material_result ?? null,
    })),
    results: props.cutting.results.map((item) => ({
        product_variant_id: item.product_variant_id,
        product_name: item.product_variant?.product?.name ?? '',
        variant_name: item.product_variant?.name ?? '',
        stock: item.product_variant?.stock ?? 0,
        cutting_result: String(item.cutting_result ?? 0),
        sample: String(item.sample ?? 0),
        original_outside_sample: String(item.original_outside_sample ?? 0),
        images: item.product_variant?.images ?? [],
    })),
}));
</script>

<template>

    <Head title="Ubah Cutting" />

    <AdminLayout>
        <div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
            <div class="space-y-1">
                <h2 class="text-2xl font-bold tracking-tight">Ubah Cutting</h2>
            </div>

            <BackButton :href="index.url()" />
        </div>

        <CuttingPosForm :raw-material-catalog="rawMaterialCatalog" :product-catalog="productCatalog"
            :categories="categories" :units="units" :initial-data="initialData"
            :submit-url="update.url(props.cutting.id)" method="put" submit-label="Perbarui" />
    </AdminLayout>
</template>
