import { useFormHandler } from "./useFormHandler.js";
import { useI18n } from "../contexts/i18n.js";

import type { FormServiceGroupTemplateValues, FormServiceGroupValueProps } from "../types/formServiceGroup.js";

type ClientServiceGroupTemplate = { name: string; description: string; identifier: string; version: number };

type UseFormHandler = typeof useFormHandler<FormServiceGroupTemplateValues, ClientServiceGroupTemplate>;

function useFormServiceGroupHandler(opts: Omit<Parameters<UseFormHandler>[0], "defaultValues" | "i18n">) {
    const { __ } = useI18n();
    const { attributes, template } = opts;

    const defaultValues: FormServiceGroupValueProps = {
        // General
        name: attributes?.name || template?.name || "",
        description: attributes?.description || template?.description || "",
    };

    const handlers = useFormHandler<FormServiceGroupValueProps, ClientServiceGroupTemplate>({
        ...opts,
        defaultValues,
        i18n: {
            successMessage: __("You have successfully saved the service group."),
            validationError: __("The service group could not be saved due to missing/invalid form values."),
            unloadConfirm: __("You have unsaved changes. If you leave this page, your changes will be discarded."),
        },
    });

    return {
        ...handlers,
        defaultValues,
        contextValue: {
            defaultTemplateValues: template ? defaultValues : {},
        },
    };
}

export { useFormServiceGroupHandler };
