import { ref, watch, onMounted, computed } from 'vue';
import { useRequest } from '@/composables/useRequest';
import { useErrorMessageHandler } from '@/composables/useErrorMessageHandler';
import { useQueueStore } from '@/stores/queue';
import { useUiStore } from '@/stores/ui';

export function useFormHandler<T extends Record<string, any>>(props: { section?: string; data?: T | null }) {
    const uiStore = useUiStore();
    const queueStore = useQueueStore();
    const { submit: requestSubmit } = useRequest();
    const { error, errorMessageHandler } = useErrorMessageHandler();

    const parameters = ref<T | Record<string, any>>({});
    const localLoading = ref(false);

    /**
     * isLoading is tied to the section provided in props.
     * If no section is provided, it falls back to a local loading state.
     */
    const isLoading = computed(() => {
        if (props.section) {
            return uiStore.isLoading(props.section);
        }
        return localLoading.value;
    });

    onMounted(() => {
        if (props.data) {
            parameters.value = { ...props.data };
            if ('gRecaptchaResponse' in parameters.value) {
                parameters.value.gRecaptchaResponse = null;
            }
        }
    });

    watch(() => props.data, (newData) => {
        if (newData) {
            parameters.value = { ...newData };
        }
    }, { deep: true, immediate: true });

    const closeModal = () => {
        if ((window as any).$) {
            (window as any).$('.modal.show').modal('hide');
        }
    };

    const formHandler = (errorMessage?: string) => {
        localLoading.value = false;
        if (props.section) {
            queueStore.reloadList({ name: props.section });
        }
        if (errorMessage) {
            errorMessageHandler(errorMessage);
        }
    };

    const errorHandler = (err: any) => {
        formHandler(err.message || 'An error occurred');
    };

    const successHandler = () => {
        closeModal();
        formHandler();
    };

    /**
     * Enhanced submit method that automatically manages local loading/error states
     * while utilizing the core useRequest submit logic.
     */
    const submit = async (
        url: string,
        method: string,
        section?: string,
        successNotification = true,
        errorNotification = true,
        params?: any,
        options: any = {}
    ) => {
        const activeSection = section || props.section;

        if (!activeSection) {
            localLoading.value = true;
        }
        errorMessageHandler('');

        const customSuccessHandler = options.successHandler;
        const customErrorHandler = options.errorHandler;

        options.successHandler = (resp: any, sec?: string, p?: any) => {
            if (customSuccessHandler) {
                customSuccessHandler(resp, sec, p);
            }
            else {
                successHandler();
            }
        };

        options.errorHandler = (resp: any, code: number, sec?: string) => {
            if (customErrorHandler) {
                customErrorHandler(resp, code, sec);
            }
            else{
                localLoading.value = false;
                errorMessageHandler(resp.message || 'An error occurred');
            }
        };

        return requestSubmit(
            url,
            method,
            activeSection,
            successNotification,
            errorNotification,
            params || parameters.value,
            options
        );
    };

    return {
        isLoading,
        error,
        parameters,
        closeModal,
        formHandler,
        submit
    };
}
