<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 { untrack } from "svelte";
    import { API } from "$lib/config/api";
    import ReusableAlertDialog from "$lib/components/reusable/reusable-alert-dialog.svelte";

    let props = $props();

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

    const { formState } = masterDetail;

    const helpers = useDictionaryForm(formState);

    let showConfirm = $state(false);

    $effect(() => {
        untrack(() => {
            formFields.forEach(group => {
                group.rows.forEach(row => {
                    row.columns.forEach(col => {
                        if (col.type === "group") {
                            col.columns.forEach(child => {
                                if (child.type === "select" && child.optionsEndpoint) {
                                    formState.fetchOptions(child, formState.form);
                                }
                            });
                        } else if ((col.type === "select") && col.optionsEndpoint) {
                            formState.fetchOptions(col, formState.form);
                        }
                    });
                });
            });
        });
    });
    
    async function handleEdit() {
        const result = await formState.save(masterDetail.mode);
        
        if (result.status === 'success') {
            console.log('Site updated successfully');
            toast('Site Updated!');
            masterDetail.exitForm(true);
        } else {
            console.error('Failed to update site:', result.message);
        }
    }

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

    const secondaryActions = [];
</script>

<FormPageContainer title="Edit Site" {primaryAction} {secondaryActions}>
    <DictionaryFormRenderer
        {formState}
        formFields={formFields}
        mode="edit"
    />
</FormPageContainer>

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