<script setup lang="ts">
import {
  AttachmentWithDocAndStored,
  EntityWorkflow,
  isAttachmentWithDocAndStored,
  WorkflowAttachment,
} from "ChillMainAssets/types";
import GenericDocItemBox from "ChillMainAssets/vuejs/WorkflowAttachment/Component/GenericDocItemBox.vue";
import DocumentActionButtonsGroup from "ChillDocStoreAssets/vuejs/DocumentActionButtonsGroup.vue";
import { computed } from "vue";
import { trans, WORKFLOW_ATTACHMENTS_NO_ATTACHMENT } from "translator";

interface AttachmentListProps {
  attachments: WorkflowAttachment[];
  workflow: EntityWorkflow | null;
}

const emit = defineEmits<{
  // eslint-disable-next-line @typescript-eslint/prefer-function-type
  (e: "removeAttachment", payload: { attachment: WorkflowAttachment }): void;
}>();

const props = defineProps<AttachmentListProps>();

const notNullAttachments = computed<AttachmentWithDocAndStored[]>(() =>
  props.attachments.filter(
    (a: WorkflowAttachment): a is AttachmentWithDocAndStored =>
      isAttachmentWithDocAndStored(a),
  ),
);

const canRemove = computed<boolean>((): boolean => {
  if (null === props.workflow) {
    return false;
  }

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

<template>
  <p
    v-if="notNullAttachments.length === 0"
    class="chill-no-data-statement text-center"
  >
    {{ trans(WORKFLOW_ATTACHMENTS_NO_ATTACHMENT) }}
  </p>
  <div v-else class="flex-table">
    <div v-for="a in notNullAttachments" :key="a.id" class="item-bloc">
      <generic-doc-item-box :generic-doc="a.genericDoc"></generic-doc-item-box>
      <div class="item-row separator">
        <ul class="record_actions">
          <li>
            <document-action-buttons-group
              :stored-object="a.genericDoc.storedObject"
            ></document-action-buttons-group>
          </li>
          <li v-if="canRemove">
            <button
              type="button"
              class="btn btn-delete"
              @click="emit('removeAttachment', { attachment: a })"
            ></button>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

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