<template>
  <template v-if="props.workflowsAvailables.length >= 1">
    <div
      v-if="countExistingWorkflows == 0 || embeddedWithinListModal"
      class="dropdown d-grid gap-2"
    >
      <button
        class="btn btn-primary dropdown-toggle"
        type="button"
        id="createWorkflowButton"
        data-bs-toggle="dropdown"
        aria-expanded="false"
      >
        Créer un workflow
      </button>
      <ul class="dropdown-menu" aria-labelledby="createWorkflowButton">
        <li v-for="w in props.workflowsAvailables" :key="w.name">
          <button
            class="dropdown-item"
            type="button"
            @click.prevent="goToGenerateWorkflow($event, w.name)"
          >
            {{ w.text }}
          </button>
        </li>
      </ul>
    </div>
    <div v-else>
      <div class="btn-group">
        <button @click="emit('clickOpenList')" class="btn btn-primary">
          <template v-if="countExistingWorkflows === 1">
            1 workflow associé
          </template>
          <template v-else>
            {{ countExistingWorkflows }} workflows associés
          </template>
        </button>
        <button
          class="btn btn-primary dropdown-toggle dropdown-toggle-split"
          type="button"
          id="createWorkflowButton"
          data-bs-toggle="dropdown"
          aria-expanded="false"
        >
          <span class="visually-hidden">Liste des workflows disponibles</span>
        </button>
        <ul class="dropdown-menu" aria-labelledby="createWorkflowButton">
          <li v-for="w in props.workflowsAvailables" :key="w.name">
            <button
              class="dropdown-item"
              type="button"
              @click.prevent="goToGenerateWorkflow($event, w.name)"
            >
              {{ w.text }}
            </button>
          </li>
        </ul>
      </div>
    </div>
  </template>
  <template v-else>
    <div v-if="countExistingWorkflows > 0" class="dropdown d-grid gap-2">
      <button
        @click="emit('clickOpenList')"
        class="btn btn-primary"
        type="button"
        id="createWorkflowButton"
        data-bs-toggle="dropdown"
        aria-expanded="false"
      >
        <template v-if="countExistingWorkflows === 1">
          1 workflow associé
        </template>
        <template v-else>
          {{ countExistingWorkflows }} workflows associés
        </template>
      </button>
    </div>
  </template>
</template>

<script setup lang="ts">
import { buildLinkCreate } from "../../../lib/entity-workflow/api";
import { WorkflowAvailable } from "../../../types";

interface PickWorkflowConfig {
  relatedEntityClass: string;
  /**
   * Represents the identifier of a related entity.
   * This variable can store either a numerical value representing the entity's ID or an undefined value
   * if the related entity is not specified or available, for instance when the entity is created within
   * the interface and the id will be available later
   */
  relatedEntityId: number | undefined;
  workflowsAvailables: WorkflowAvailable[];
  preventDefaultMoveToGenerate: boolean;
  goToGenerateWorkflowPayload: object;
  countExistingWorkflows: number;
  /**
   * if true, this button will not present a splitted button
   */
  embeddedWithinListModal: boolean;
}

const props = withDefaults(defineProps<PickWorkflowConfig>(), {
  preventDefaultMoveToGenerate: false,
  goToGenerateWorkflowPayload: {},
  allowCreateWorkflow: false,
});

const emit = defineEmits<{
  (
    e: "goToGenerateWorkflow",
    {
      event: MouseEvent,
      workflowName: string,
      isLinkValid: boolean,
      link: string,
      payload: object,
    },
  ): void;
  (e: "clickOpenList"): void;
}>();

const makeLink = (workflowName: string): string =>
  buildLinkCreate(
    workflowName,
    props.relatedEntityClass,
    props.relatedEntityId,
  );

const goToGenerateWorkflow = (
  event: MouseEvent,
  workflowName: string,
): void => {
  console.log("goToGenerateWorkflow", event, workflowName);
  let link = "";
  let isLinkValid = false;

  try {
    link = makeLink(workflowName);
    isLinkValid = true;
  } catch (e) {
    console.info(
      "could not generate link to create workflow, maybe the relatedEntityId is not yet known",
      e,
    );
  }

  if (!props.preventDefaultMoveToGenerate) {
    window.location.assign(link);
  }

  emit("goToGenerateWorkflow", {
    event,
    workflowName,
    link,
    isLinkValid,
    payload: props.goToGenerateWorkflowPayload,
  });
};

const goToDuplicateRelatedEntity = (
  event: MouseEvent,
  workflowName: string,
): void => {};
</script>

<style scoped></style>
