<script setup lang="ts">
    import { useForm } from 'vee-validate';
    import { IDocsSchemaType } from '@/modules/form/types';
    import Field from '@/modules/form/components/Field.vue';
    import { valueof } from '@/UI-kit/types';
    import { IPatentForm, TAvailableDoc } from '@/modules/documents';

    const props = withDefaults(
        defineProps<{
            fields: IDocsSchemaType[];
            initialValue?: any;
        }>(),
        {
            initialValue: () => {},
        },
    );

    const emit = defineEmits<{
        (
            e: 'submit',
            values: valueof<Pick<TAvailableDoc, 'value'> | IPatentForm>,
        ): valueof<Pick<TAvailableDoc, 'value'> | IPatentForm>;
    }>();

    const { handleSubmit } = useForm();

    const submit = handleSubmit(
        (values) => {
            emit('submit', values as valueof<Pick<TAvailableDoc, 'value'> | IPatentForm>);
        },
        ({ errors }) => {
            if (Object.keys(errors)) {
                const el = document.getElementById(Object.keys(errors)[0]);
                el && el.scrollIntoView({ block: 'center', behavior: 'smooth' });
            }
        },
    );

    defineExpose({
        submit,
    });
</script>

<template>
    <form class="wrapper" @submit.prevent="submit">
        <Field
            v-for="field in props.fields"
            :key="field.name"
            :initial-value="initialValue[field.name] || ''"
            v-bind="field"
        />
        <slot />
    </form>
</template>

<style scoped lang="scss">
    .wrapper {
        display: flex;
        width: 100%;
        flex-direction: column;
        gap: 14px;
    }
</style>
