<script>
    import { Separator } from "$lib/components/ui/separator/index.js";
	import { useMasterDetail } from "$lib/components/composable/use-master-detail.svelte";
	import { getVisit, createAdmission, editAdmission } from "$lib/components/patient/admission/api/patient-admission-api";
	import MasterPage from "$lib/components/patient/admission/page/master-page.svelte";
	import ViewPage from "$lib/components/patient/admission/page/view-page.svelte";
	import CreatePage from "$lib/components/patient/admission/page/create-page.svelte";
	import EditPage from "$lib/components/patient/admission/page/edit-page.svelte";
	import { admissionSchema, admissionInitialForm, admissionDefaultErrors, admissionFormFields, getAdmissionFormActions, buildPayload } from "$lib/components/patient/admission/config/admission-form-config";

	const masterDetail = useMasterDetail({
		onSelect: async (row) => {
			const response =  await getVisit(row.PVID);
			if (response?.data) {
				response.data.isDischarge = response.data.ADTCode === "A03";
			}

			return response
		},
		formConfig: {
			schema: admissionSchema,
			initialForm: admissionInitialForm,
			defaultErrors: admissionDefaultErrors,
			mode: 'create',
			modeOpt: 'default',
			saveEndpoint: createAdmission,
			editEndpoint: editAdmission,
		}
	});

	const pageContext = {
		masterDetail,
		formFields: admissionFormFields,
		formActions: getAdmissionFormActions,
		schema: admissionSchema,
		initialForm: admissionInitialForm,
		defaultErrors: {
        	create: admissionDefaultErrors,
			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>