<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 { toast } from "svelte-sonner";
    import ReusableAlertDialog from "$lib/components/reusable/reusable-alert-dialog.svelte";
    import { buildPatientPayload } from "$lib/components/patient/list/config/patient-form-config";

    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;
        }
    }
// $inspect(formState.form)
    function confirmDiscard() {
        masterDetail.exitForm(true);
    }

    async function handleSave() {
        const payload = buildPatientPayload(formState.form);
        console.log(payload);
        const result = await formState.save(masterDetail.mode, payload);
        
        if (result.status === 'success') {
            toast('Patient Created!');
            masterDetail?.exitForm(true);
        } else {
            console.error('Failed to save patient');
            const errorMessages = result.messages ? Object.values(result.messages).join('\n') : 'Failed to save patient';
            toast.error(errorMessages)
        }
    }

    function handleSaveAndOrder() {
        console.log('save and order');
    }

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

    const secondaryActions = [
        {
            label: 'Save and Order',
            onClick: handleSaveAndOrder,
            disabled: formState.isSaving.current
        }
    ];
    // $inspect(formState.selectOptions)
</script>

<FormPageContainer title="Create Patient" {primaryAction} {secondaryActions} {actions}>
    <PatientFormRenderer 
        {formState}
        formFields={formFields}
        uploadErrors={helpers.uploadErrors} 
        isChecking={helpers.isChecking} 
        linkToDisplay={helpers.linkToDisplay} 
        validateIdentifier={helpers.validateIdentifier}
        validateFieldAsync={helpers.validateFieldAsync}
        mode="create"
    />
</FormPageContainer>

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