<script>
    import { Separator } from "$lib/components/ui/separator/index.js";
	import { useMasterDetail } from "$lib/components/composable/use-master-detail.svelte";
	import { getPatient, createPatient, editPatient } from "$lib/components/patient/list/api/patient-list-api";
	import MasterPage from "$lib/components/patient/list/page/master-page.svelte";
	import ViewPage from "$lib/components/patient/list/page/view-page.svelte";
	import CreatePage from "$lib/components/patient/list/page/create-page.svelte";
	import EditPage from "$lib/components/patient/list/page/edit-page.svelte";
	import { patientSchema, patientInitialForm, patientDefaultErrors, patientFormFields, getPatientFormActions } from "$lib/components/patient/list/config/patient-form-config";

	const masterDetail = useMasterDetail({
		onSelect: async (row) => {
			return await getPatient(row.InternalPID);
		},
		formConfig: {
			schema: patientSchema,
			initialForm: patientInitialForm,
			defaultErrors: patientDefaultErrors,
			mode: 'create',
			modeOpt: 'cascade',
			saveEndpoint: createPatient,
			editEndpoint: editPatient,
			mapToForm: (data) => ({
				...data,
				PatIdt: {
					IdentifierType: data.PatIdt?.IdentifierType ?? "",
					Identifier: data.PatIdt?.Identifier ?? ""
				},
				LinkTo: Array.isArray(data.LinkTo) ? data.LinkTo : [],
				Custodian: data.Custodian ?? {
				InternalPID: "",
				PatientID: ""
				},
			})
		}
	});

	const pageContext = {
		masterDetail,
		formFields: patientFormFields,
		formActions: getPatientFormActions,
		schema: patientSchema,
		initialForm: patientInitialForm,
		// defaultErrors: {
        // 	create: patientDefaultErrors,
		// 	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>