<script>
    import { useDictionaryForm } from "$lib/components/composable/use-dictionary-form.svelte";
    import FormPageContainer from "$lib/components/reusable/form/form-page-container.svelte";
    import DictionaryFormRenderer from "$lib/components/reusable/form/dictionary-form-renderer.svelte";
    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 = useDictionaryForm(formState);

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

    const actions = formActions(handlers);

    let showConfirm = $state(false);

    async function handleSave() {
        const result = await formState.save(masterDetail.mode);

        toast('Container Created!');
        masterDetail?.exitForm(true);
    }

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

    const secondaryActions = [];
</script>

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

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