<script setup lang="ts">
import {ref} from 'vue'

const emit = defineEmits<{
  (event: 'update-value', options: { name: string }[]): void;
}>();

const options = ref<{ name: string }[]>([
  { name: "Add Param" }
]);

const sendToParent = () => {
  options.value.forEach((value) => {console.log("KID" + value + options.value.indexOf(value))})
  emit('update-value', options.value);
};
const nameInput = ref('')
const valueInput = ref('')
const selectedOption = ref(options.value[0].name)

const isNumeric = (string) => /^[+-]?\d+(\.\d+)?$/.test(string)

const selectedFunction = () => {
  const action = selectOption(selectedOption.value);
  const name = nameInput.value.trim();
  const value = valueInput.value.trim();

  if (action === "Add Param" && name && value && !isNumeric(name)) {
    options.value.push({ name: `${name} = ${value}` });
    nameInput.value = valueInput.value = "";
  }

  if (action === "Remove Param") {
    options.value = options.value.filter(option => option.name !== selectedOption.value);
    selectedOption.value = options.value.length ? options.value[0].name : "";
    nameInput.value = valueInput.value = "";
  }
  sendToParent();
};
function selectOption(option: string): string {
  return option == "Add Param" ? "Add Param" : "Remove Param"
}
</script>

<template>
  <input
      v-if="selectedOption==='Add Param'"
      id="NameTextInput"
      v-model="nameInput"
      class="text-input h-full px-3 rounded-full border border-slate-400 bg-white dark:text-slate-100 dark:bg-gray-600 w-48"
      type="text"
      placeholder="Name"
  />
  <input
      v-if="selectedOption==='Add Param'"
      id="ValueTextInput"
      v-model="valueInput"
      class="text-input h-full px-3 rounded-full border border-slate-400 bg-white dark:text-slate-100 dark:bg-gray-600 w-48"
      type="text"
      placeholder="Value"
  />
  <select
      v-model="selectedOption"
      class="flex h-full px-3 rounded-full border border-slate-400 bg-white dark:text-slate-100 dark:bg-gray-600 w-48"
  >
    <option v-for="option in options" :value="option.name" :key="option.name">
      {{ option.name }}
    </option>
  </select>
  <button class="tool-button w-24" @click="selectedFunction">{{ selectOption(selectedOption) }}</button>

</template>

