<script setup lang="ts">
import { computed, onMounted, ref, useTemplateRef } from "vue";
import type { EntityWorkflow, 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";
import { fetchWorkflow } from "ChillMainAssets/lib/workflow/api";
import { trans, WORKFLOW_ATTACHMENTS_ADD_AN_ATTACHMENT } from "translator";

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 workflow = ref<EntityWorkflow | null>(null);

onMounted(async () => {
  workflow.value = await fetchWorkflow(Number(props.workflowId));
  console.log("workflow", workflow.value);
});

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

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

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

const canEditAttachement = computed<boolean>(() => {
  if (null === workflow.value) {
    return false;
  }

  return workflow.value._permissions.CHILL_MAIN_WORKFLOW_ATTACHMENT_EDIT;
});
</script>

<template>
  <pick-generic-doc-modal
    :workflow="workflow"
    :accompanying-period-id="props.accompanyingPeriodId"
    :to-remove="attachedGenericDoc"
    ref="pickDocModal"
    @pickGenericDoc="onPickGenericDoc"
  ></pick-generic-doc-modal>
  <attachment-list
    :workflow="workflow"
    :attachments="props.attachments"
    @removeAttachment="onRemoveAttachment"
  ></attachment-list>
  <ul v-if="canEditAttachement" class="record_actions">
    <li>
      <button type="button" class="btn btn-create" @click="openModal">
        {{ trans(WORKFLOW_ATTACHMENTS_ADD_AN_ATTACHMENT) }}
      </button>
    </li>
  </ul>
</template>

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