<template>
  <div>
    <table>
      <thead>
      <tr>
        <th>Goal Amount</th>
        <th>Percent Bonus</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="kv in bonuses" v-bind:key="kv.id">
        <td class="p-0">
          <input
            type="text"

            v-model="kv.goal"
            :aria-label="`Goal #${bonuses.length}`"
            @input="checkInputs"
            @blur="saveValues"
          >
        </td>
        <td class="p-0">
          <input
            type="text"

            :class="kv.percent < 1 ? 'is-danger' : ''"
            v-model="kv.percent"
            :aria-label="`Cashback percent #${bonuses.length}`"
            @input="checkInputs"
            @blur="saveValues"
          >
        </td>
      </tr>
      </tbody>
    </table>
  </div>
</template>

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

interface Bonus {
  id: number;
  goal: string | undefined;
  percent: string | undefined;
}

// eslint-disable-next-line no-undef
const emits = defineEmits(['save']);

const bonuses = ref([{
  id: 1,
  goal: undefined,
  percent: undefined,
}] as Bonus[]);

const getNextId = () => bonuses.value.length + 1;

const checkInputs = () => {
  if (bonuses.value.every((b) => Object.values(b)
    .every((v) => !!v))) {
    bonuses.value.push({
      id: getNextId(),
      goal: undefined,
      percent: undefined,
    });
  }
};

const saveValues = () => {
  emits('save', bonuses.value.filter((b) => !!b.goal && !!b.percent)
    .map((b) => (
      {
        goal: parseFloat(b.goal as string),
        percent: parseFloat(b.percent as string),
      }
    )));
};
</script>

<style scoped lang="stylus">

</style>
