import {
    IApiDocumentModule,
    IApiResponse,
    IModuleDocumentEmit,
    IModuleDocumentProps,
    useUserImageDocument,
} from '@/modules/documents';
import { useRequestHandler } from '@/UI-kit/composables';
import { useToastNotification } from '@/UI-kit/components/UI/toaster/UIToaster';
import { TAvailableDoc } from '@/modules/documents/type';
import { useI18n } from 'vue-i18n';
import { scrollToElement } from '@/UI-kit/utils';

export default function (
    props: IModuleDocumentProps,
    emit: IModuleDocumentEmit,
    api: IApiDocumentModule,
) {
    const { errorToast } = useToastNotification();

    const { t } = useI18n();

    const { pendingImageList, deleteImageList, saveImageDocument, removeImageHandler } =
        useUserImageDocument(api);

    const { isLoading, requestHandler: submitHandler } = useRequestHandler<TAvailableDoc, any>({
        request: async (formData: TAvailableDoc) => api.saveDocument({ formData }),
        then: async (data: IApiResponse) => {
            try {
                if (!props.isShowDeleteDocBtn) {
                    const docList = await api.getDocuments();
                    const findDocListForType = docList.find(
                        (doc) => doc.type === props.documentType,
                    );
                    if (findDocListForType && findDocListForType.photos.length) {
                        for (const item of findDocListForType.photos) {
                            await removeImageHandler({ imageId: item.id });
                        }
                    }
                }

                if (pendingImageList.value.length) {
                    for (const item of pendingImageList.value) {
                        await saveImageDocument({ formData: item, documentId: data.id });
                    }
                }

                if (deleteImageList.value.length) {
                    for (const item of deleteImageList.value) {
                        await removeImageHandler({ imageId: item.id });
                    }
                }
                emit('update:document', data);
            } catch (err) {
                console.warn('[ModuleDocuments/submitHandler]: ' + err);
                errorToast(t('helpers.error'));
            }
        },
        catch: async (error: any) => {
            if (error?.status === 422 && error?.response?.data?.errors) {
                for (const item in error.response.data.errors) {
                    const key = item.split('.')?.[1];
                    const HTMLElement = document.querySelector(`#${key}`);
                    if (HTMLElement) {
                        HTMLElement.classList.add('--error');
                        setTimeout(() => {
                            HTMLElement.classList.remove('--error');
                        }, 3200);

                        scrollToElement(HTMLElement, 140);
                        break;
                    }
                }
            }
            errorToast(error?.response?.data?.message || t('helpers.error'));
        },
    });

    return {
        pendingImageList,
        deleteImageList,
        submitHandler,
        isLoading,
    };
}
