<script>
    import { usePatientForm } from "$lib/components/composable/use-patient-form.svelte";
    import FormPageContainer from "$lib/components/patient/reusable/form-page-container.svelte";
    import PatientFormRenderer from "$lib/components/patient/reusable/patient-form-renderer.svelte";
    import { buildPayload } from "$lib/components/patient/admission/config/admission-form-config";
    import { toast } from "svelte-sonner";
    import ReusableAlertDialog from "$lib/components/reusable/reusable-alert-dialog.svelte";

    let props = $props();

    const { masterDetail, formFields, formActions, schema } = props.context;

    const { formState } = masterDetail;

    const helpers = usePatientForm(formState, schema);

    const handlers = {
        clearForm: () => {
            formState.reset();
        }
    };

    const actions = formActions(handlers);

    let showConfirm = $state(false);

    function handleExit() {
        const ok = masterDetail.exitForm();
        if (!ok) {
        showConfirm = true;
        }
    }

    function confirmDiscard() {
        masterDetail.exitForm(true);
    }

    async function handleSave() {
        const payload = buildPayload(formState.form);

        const result = await formState.save(masterDetail.mode, payload);
    
        console.log(payload);
        toast('Visit Created!');
        masterDetail?.exitForm(true);
    }

    const primaryAction = $derived({
        label: 'Save',
        onClick: handleSave,
        disabled: helpers.hasErrors || formState.isSaving.current,
        loading: formState.isSaving.current
    });

    const secondaryActions = [];

    $effect(() => {
        if (masterDetail.form?.PatientID) {
            formState.setForm({
                ...formState.form,
                ...masterDetail.form
            });
        }
    });
</script>

<FormPageContainer title="Create Admission" {primaryAction} {secondaryActions} {actions}>
    <PatientFormRenderer 
        {formState}
        formFields={formFields}
        mode="create"
    />
</FormPageContainer>

<ReusableAlertDialog
    bind:open={masterDetail.showExitConfirm}
    onConfirm={masterDetail.confirmExit}
/>