<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";
    import { getChangedFields } from "$lib/utils/getChangedFields";

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

            if (formState.form.Province) {
                formState.fetchOptions(
                    { 
                        key: "City", 
                        optionsEndpoint: `${API.BASE_URL}${API.CITY}`,
                        dependsOn: "Province",
                        endpointParamKey: "ProvinceID"
                    }, 
                    formState.form
                );
            }
        });
    });
    
    async function handleEdit() {
        const currentPayload = formState.form;
        const originalPayload = masterDetail.formSnapshot;
        
        const changedFields = getChangedFields(originalPayload, currentPayload);

        if (Object.keys(changedFields).length === 0) {
            toast('No changes detected');
            return;
        }

        const payload = {
            LocationID: formState.form.LocationID,
            ...changedFields
        };
        
        console.log('Payload:', payload);  

        const result = await formState.save(masterDetail.mode, payload);
        
        if (result.status === 'success') {
            console.log('Location updated successfully');
            toast('Location Updated!');
            masterDetail.exitForm(true);
        } else {
            console.error('Failed to update location:', result.message);
            const errorMessages = result.messages ? Object.values(result.messages).join('\n') : 'Failed to update location';
            toast.error(errorMessages)
        }
    }

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

    const secondaryActions = [];
</script>

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

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