<script>
    import { Separator } from "$lib/components/ui/separator/index.js";
	import { useMasterDetail } from "$lib/components/composable/use-master-detail.svelte";
	import { getOrder, createOrder, editOrder } from "$lib/components/order/ordertest/api/ordertest-api";
	import MasterPage from "$lib/components/order/ordertest/page/master-page.svelte";
	import ViewPage from "$lib/components/order/ordertest/page/view-page.svelte";
	import CreatePage from "$lib/components/order/ordertest/page/create-page.svelte";
	import EditPage from "$lib/components/order/ordertest/page/edit-page.svelte";
	import { orderTestSchema, orderTestInitialForm, orderTestDefaultErrors, orderTestFormFields, getOrderTestFormActions } from "$lib/components/order/ordertest/config/ordertest-form-config";

	const masterDetail = useMasterDetail({
		onSelect: async (row) => {
			return await getOrder(row.OrderID);
		},
		formConfig: {
			schema: orderTestSchema,
			initialForm: orderTestInitialForm,
			defaultErrors: orderTestDefaultErrors,
			mode: 'create',
			modeOpt: 'default',
			saveEndpoint: createOrder,
			editEndpoint: editOrder,
			idKey: 'OrderID',
			mapToForm: (data) => ({
				...data,
				Tests: (data.Tests || []).map((t, i) => ({
					...t,
					id: t.id ?? i + 1
				}))
			})
		}
	});

	const pageContext = {
		masterDetail,
		formFields: orderTestFormFields,
		formActions: getOrderTestFormActions,
		schema: orderTestSchema,
		initialForm: orderTestInitialForm,
		defaultErrors: {
        	create: orderTestDefaultErrors,
			edit: {}
		}
	}
</script>

<div class="flex w-full h-full overflow-hidden">
	{#if masterDetail.showMaster}
		<MasterPage {masterDetail} />
	{/if}
    	<Separator orientation="vertical"/>
	{#if masterDetail.showDetail}
		 <main class={`${masterDetail.isMobile ? 'w-full' : masterDetail.isFormMode ? 'w-[97%] flex flex-col items-start' : 'w-[65%]'} h-full overflow-y-auto flex flex-col items-center transition-all duration-300`}>
			{#if masterDetail.mode === "view"}
				<ViewPage context={pageContext}/>
			{:else if masterDetail.mode === "create"}
				<CreatePage context={pageContext}/>
			{:else if masterDetail.mode === "edit"}
				<EditPage context={pageContext}/>
			{/if}
		</main>
	{/if}
</div>