<script setup lang="ts">
import { computed, ref } from "vue";
import AutoCompleteInput from "./Inputs/AutoCompleteInput.vue";

const activityModel = ref([
  { activityCode: "1001", operationCodes: ["00"] },
  { activityCode: "5201", operationCodes: ["01", "03"] },
  { activityCode: "3199", operationCodes: ["00"] },
]);

const activityCode = ref("");
const operationCode = ref("");
const price = ref<number | null>(null);

const activityCodeOptions = computed<string[]>(() => {
  return activityModel.value.map((e) => e.activityCode);
});

const operationCodeOptions = computed<string[]>(() => {
  return (
    activityModel.value.find((e) => e.activityCode === activityCode.value)
      ?.operationCodes ?? []
  );
});

const onActivityCodeChange = (value: string) => {
  activityCode.value = value;
  operationCode.value = "";
  price.value = null;
};

const onActivityCodeAutocomplete = () => {
  operationCode.value =
    activityModel.value.find((e) => e.activityCode === activityCode.value)
      ?.operationCodes[0] ?? "";

  const operationCodeInput = document.getElementsByName("operationCodeInput");
  if (operationCodeInput.length > 0) {
    setTimeout(() => operationCodeInput[0].focus(), 1);
  }
};

const onOperationCodeChange = (value: string) => {
  operationCode.value = value;
  price.value = null;
};

const onOperationCodeAutocomplete = () => {
  // Generate a random price value of between 0.00 and 10.00
  price.value = Math.round(Math.random() * 1000) / 100;
};
</script>

<template>
  <div class="input-group" style="margin-bottom: 10px">
    <label style="width: 8em">Activiteitscode</label>
    <AutoCompleteInput
      :model-value="activityCode"
      :options="activityCodeOptions"
      @update:model-value="onActivityCodeChange"
      @autocomplete="onActivityCodeAutocomplete"
    />
  </div>

  <div class="input-group">
    <label style="width: 8em">Bewerkingscode</label>
    <AutoCompleteInput
      :model-value="operationCode"
      @update:model-value="onOperationCodeChange"
      @autocomplete="onOperationCodeAutocomplete"
      :options="operationCodeOptions"
      :disabled="operationCodeOptions.length < 2"
      name="operationCodeInput"
      always-show-suggestions
    />
  </div>

  <p v-if="price">Berekende prijs: {{ price }} euro</p>
</template>

<style>
.input-group {
  display: flex;
  gap: 10px;
}
</style>
