<script setup lang="ts">
import { computed, useTemplateRef } from "vue";
import type { WorkflowAttachment } from "ChillMainAssets/types";
import PickGenericDocModal from "ChillMainAssets/vuejs/WorkflowAttachment/Component/PickGenericDocModal.vue";
import { GenericDocForAccompanyingPeriod } from "ChillDocStoreAssets/types/generic_doc";
import AttachmentList from "ChillMainAssets/vuejs/WorkflowAttachment/Component/AttachmentList.vue";
import { GenericDoc } from "ChillDocStoreAssets/types";

interface AppConfig {
    workflowId: number;
    accompanyingPeriodId: number;
    attachments: WorkflowAttachment[];
}

const emit = defineEmits<{
    (
        e: "pickGenericDoc",
        payload: { genericDoc: GenericDocForAccompanyingPeriod },
    ): void;
    (e: "removeAttachment", payload: { attachment: WorkflowAttachment }): void;
}>();

type PickGenericModalType = InstanceType<typeof PickGenericDocModal>;

const pickDocModal = useTemplateRef<PickGenericModalType>("pickDocModal");
const props = defineProps<AppConfig>();

const attachedGenericDoc = computed<GenericDocForAccompanyingPeriod[]>(
    () =>
        props.attachments
            .map((a: WorkflowAttachment) => a.genericDoc)
            .filter(
                (g: GenericDoc | null) => g !== null,
            ) as GenericDocForAccompanyingPeriod[],
);

const openModal = function () {
    pickDocModal.value?.openModal();
};

const onPickGenericDoc = ({
    genericDoc,
}: {
    genericDoc: GenericDocForAccompanyingPeriod;
}) => {
    emit("pickGenericDoc", { genericDoc });
};

const onRemoveAttachment = (payload: { attachment: WorkflowAttachment }) => {
    emit("removeAttachment", payload);
};
</script>

<template>
    <pick-generic-doc-modal
        :accompanying-period-id="props.accompanyingPeriodId"
        :to-remove="attachedGenericDoc"
        ref="pickDocModal"
        @pickGenericDoc="onPickGenericDoc"
    ></pick-generic-doc-modal>
    <attachment-list
        :attachments="props.attachments"
        @removeAttachment="onRemoveAttachment"
    ></attachment-list>
    <ul class="record_actions">
        <li>
            <button type="button" class="btn btn-create" @click="openModal">
                Ajouter une pièce jointe
            </button>
        </li>
    </ul>
</template>

<style scoped lang="scss"></style>
