<script setup lang="ts">
    import {
        DocumentsType,
        IApiDocumentModule,
        IApiRequestPatent,
        IApiResponse,
        IDocumentFieldsOptions,
        ImageConfig,
        IModuleDocumentEmit,
        IModuleDocumentProps,
        TAvailableDoc,
    } from '@/modules/documents/type';
    import ModuleForm from '@/modules/form/ModuleForm.vue';
    import {
        useDefaultFields,
        useDocumentImage,
        useDocumentModuleHandlers,
        useModuleDocumentConnector,
        usePrepareFields,
    } from '@/modules/documents/composables';
    import { computed, defineAsyncComponent, onBeforeMount, ref } from 'vue';
    import { UIColor } from '@/UI-kit/constants';
    import UIButton from '@/UI-kit/components/UI/button/UIButton.vue';
    import { IButtonType } from '@/UI-kit/types/UI/ui-button.type';
    import { ELanguageLocale, UIColorName, UISize } from '@/UI-kit/types';
    import UICard from '@/UI-kit/components/UI/card/UICard.vue';
    import UIBlockSaveImageType1 from '@/UI-blocks/components/BlockSavedImage/Type1/UIBlockSaveImageType1.vue';
    import { useUIModalStore } from '@/UI-kit/store';
    import { IDocsSchemaType } from '@/modules/form/types';
    import { useI18n } from 'vue-i18n';
    import { useUiKitDirectoryStore } from '@/configs/store';
    import { storeToRefs } from 'pinia';

    const props = withDefaults(defineProps<IModuleDocumentProps>(), {
        isShowExampleImage: false,
        isShowDeleteDocBtn: false,
        isShowNotSaveDocBtn: false,
        customImageField: () => ({}) as ImageConfig,
        customDocsSchemaType: () => [] as IDocsSchemaType[],
        initialValue: () => ({}) as TAvailableDoc,
        api: () => ({}) as IApiDocumentModule,
        doc: () => ({}) as IApiResponse,
        fieldsOptions: () => ({}) as IDocumentFieldsOptions,
        rawImages: null,
    });

    const emit = defineEmits<IModuleDocumentEmit>();

    const directoryStore = useUiKitDirectoryStore();
    const { countryList, regionList } = storeToRefs(directoryStore);

    const { prepareForServer, prepareFromServer } = usePrepareFields();

    const moduleDocumentConnector = useModuleDocumentConnector();

    const { t, locale } = useI18n();

    const { openModal } = useUIModalStore();

    const formData = ref(props.initialValue);

    const api = computed<IApiDocumentModule>(() => ({ ...moduleDocumentConnector, ...props.api }));

    const { pendingImageList, deleteImageList, submitHandler, isLoading } =
        useDocumentModuleHandlers(props, emit, api.value);

    const image = computed(() => {
        if (!props.documentType) return null;
        return useDocumentImage(
            props.documentType,
            locale.value as ELanguageLocale,
            props.customImageField,
        );
    });

    const fieldsOptions = computed<IDocumentFieldsOptions>(() => ({
        ...props.fieldsOptions,
        passport: {
            citizenshipOptions: countryList.value.map((item) => ({
                label: item.name,
                value: item.code.toLowerCase(),
            })),
            regionOptions: regionList.value.map((item) => ({
                label: item.title,
                value: item.id,
            })),
        },
    }));

    const fields = computed(() => {
        if (!props.documentType) return null;
        return useDefaultFields(
            props.documentType,
            props.customDocsSchemaType,
            fieldsOptions.value,
        );
    });

    const openDeleteDocumentModal = () => {
        openModal({
            component: defineAsyncComponent(
                () => import('@/modules/documents/components/DeleteDocumentModal.vue'),
            ),
            modalProps: {
                title: t('moduleDocuments.modal.removeDocument.title'),
            },
            componentProps: {
                api: api.value,
                id: props.doc?.id,
            },
            listeners: {
                'remove:document': async (id: number) => {
                    emit('remove:document', id);
                    emit('back');
                },
            },
        });
    };

    const submit = async (data: any) => {
        const prepareData = prepareForServer(props.documentType, data);
        await submitHandler({
            type: props.documentType,
            value: prepareData.value,
            addition_fields: prepareData?.addition_fields,
        });
    };

    onBeforeMount(async () => {
        if (Object.values(props.initialValue).length) {
            formData.value = prepareFromServer(
                props.documentType,
                props.initialValue as IApiRequestPatent,
                props.doc,
            );
        }

        if (props.documentType === DocumentsType.NONRESIDENT_PASSPORT) {
            await directoryStore.getAllDirectory();
        }
    });
</script>

<template>
    <div class="document-module">
        <UIBlockSaveImageType1
            v-if="isShowSaveImageBlock"
            class="document-module__saved-image"
            :document-type="documentType"
            :preview-modal-title="saveImagePreviewModalTitle"
            :text="t('moduleDocuments.savedDocumentImage.text')"
            :raw-images="rawImages"
            :images="doc.photos"
            @get:camera-photo="emit('get:camera-photo')"
            @update:document-image-list="pendingImageList = $event"
            @update:delete-document-image-list="deleteImageList = $event"
        />
        <img
            v-if="isShowExampleImage && image"
            :src="image?.path"
            :alt="image?.alt"
            class="document-module__image"
        />
        <UICard class="document-module__card" is-box-shadow>
            <ModuleForm v-if="fields" :fields="fields" :initial-value="formData" @submit="submit">
                <slot name="submit-button">
                    <UIButton
                        :is-loading="isLoading"
                        :button-type="IButtonType.SUBMIT"
                        :size="UISize.S"
                    >
                        {{ t('moduleDocuments.btns.submit') }}
                    </UIButton>
                    <UIButton
                        v-if="isShowNotSaveDocBtn"
                        :size="UISize.S"
                        :bg-color="UIColor[UIColorName.Blue1]"
                        :color="UIColor[UIColorName.Blue500]"
                        @click="emit('back')"
                    >
                        {{ t('moduleDocuments.btns.cancel') }}
                    </UIButton>
                    <UIButton
                        v-if="isShowDeleteDocBtn && doc?.id"
                        class="document-module__button-remove"
                        :size="UISize.Custom"
                        :bg-color="UIColor[UIColorName.White]"
                        :color="UIColor[UIColorName.Red075]"
                        @click="openDeleteDocumentModal()"
                    >
                        {{ t('moduleDocuments.btns.remove') }}
                    </UIButton>
                </slot>
            </ModuleForm>
        </UICard>
    </div>
</template>

<style scoped lang="scss">
    @use '@/UI-kit/assets/scss/mixins/index.mixin';

    .document-module {
        @include index.flex(column, 12px);

        gap: 20px;
        width: 100%;
        margin: 0 auto;

        &__card {
            width: 100%;
        }

        &__saved-image {
            width: 100%;
        }

        &__image {
            display: block;
            width: 100%;
            height: auto;
            margin: 0 auto;
            max-width: 400px;
            border-radius: 15px;
        }

        &__button {
            &-remove {
                padding: 0;
            }
        }
    }
</style>
