<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);

        if (result.status === 'success') {
            toast('Workstation Created!');
            masterDetail?.exitForm(true);
        } else {
            console.error('Failed to save workstation');
            const errorMessages = result.messages ? Object.values(result.messages).join('\n') : 'Failed to save workstation';
            toast.error(errorMessages)
        }
    }

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

    const secondaryActions = [];
</script>

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

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