<template>
  <span v-if="hasNoResults" class="chill-no-data-statement">
    {{ trans(NO_DATA) }}
  </span>
  <tab-table v-else>
    <template #thead>
      <th scope="col">
        {{ trans(OBJECT_WORKFLOW) }}
      </th>
      <th scope="col">
        {{ trans(STEP) }}
      </th>
      <th scope="col">
        {{ trans(CONCERNED_USERS) }}
      </th>
      <th scope="col" />
    </template>
    <template #tbody>
      <tr v-for="(w, i) in workflows.results" :key="`workflow-${i}`">
        <td>
          {{ w.title }}
        </td>
        <td>
          <div class="workflow">
            <div class="breadcrumb">
              <i class="fa fa-circle me-1 text-chill-yellow mx-2" />
              <span class="mx-2">{{ getStep(w) }}</span>
            </div>
            <span
              v-if="w.isOnHoldAtCurrentStep"
              class="badge bg-success rounded-pill"
              >{{ trans(ON_HOLD) }}</span
            >
          </div>
        </td>
        <td v-if="w.datas.persons !== null">
          <span v-for="p in w.datas.persons" class="me-1" :key="p.id">
            <on-the-fly
              :type="p.type"
              :id="p.id"
              :button-text="p.textAge"
              :display-badge="'true' === 'true'"
              action="show"
            />
          </span>
        </td>
        <td>
          <a class="btn btn-sm btn-show" :href="getUrl(w)">
            {{ trans(SHOW_ENTITY, { entity: trans(THE_WORKFLOW) }) }}
          </a>
        </td>
      </tr>
    </template>
  </tab-table>
</template>

<script lang="ts" setup>
import { computed } from "vue";
import { useStore } from "vuex";
import TabTable from "./TabTable.vue";
import OnTheFly from "ChillMainAssets/vuejs/OnTheFly/components/OnTheFly.vue";
import { Workflow } from "ChillPersonAssets/types";
import {
  CONCERNED_USERS,
  OBJECT_WORKFLOW,
  ON_HOLD,
  SHOW_ENTITY,
  THE_WORKFLOW,
  NO_DATA,
  STEP,
  trans,
} from "translator";
import { PaginationResponse } from "ChillMainAssets/lib/api/apiMethods";

const props = defineProps<{
  workflows: PaginationResponse<Workflow>;
}>();

const store = useStore();

const isWorkflowsLoaded = computed(() => store.getters.isWorkflowsLoaded);

const hasNoResults = computed(() => {
  if (!isWorkflowsLoaded.value) {
    return false;
  } else {
    return props.workflows.count === 0;
  }
});

function getUrl(w: Workflow): string {
  return `/fr/main/workflow/${w.id}/show`;
}

function getStep(w: Workflow): string {
  const lastStep = w.steps.length - 1;
  return w.steps[lastStep].currentStep.text;
}
</script>

<style scoped>
span.outdated {
  font-weight: bold;
  color: var(--bs-warning);
}
</style>
