<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import { moveItemUp, moveItemDown, deleteItem, dialog } from 'stores/utils';

import NoData from 'components/NoData.vue';
import WorkManagementComponent from './WorkManagementComponent.vue';
import AddButton from '../button/AddButton.vue';
import { WorkItems } from 'stores/product-service/types';

const { t } = useI18n();

const workItems = defineModel<WorkItems[]>('workItems', { default: [] });

defineProps<{
  dense?: boolean;
  outlined?: boolean;
  readonly?: boolean;
  separator?: boolean;
}>();

defineEmits<{
  (e: 'addProduct', index: number): void;
  (e: 'manageWorkName'): void;
  (e: 'workProperties', index: number): void;
}>();

function addWork() {
  workItems.value.push({
    id: '',
    name: '',
    attributes: { additional: [] },
    product: [],
  });
}

function confirmDelete(items: unknown[], index: number) {
  dialog({
    color: 'negative',
    icon: 'mdi-alert',
    title: t('deleteConfirmTitle'),
    actionText: t('delete'),
    message: t('deleteConfirmMessage'),
    action: async () => {
      deleteItem(items, index);
    },
    cancel: () => {},
  });
}
</script>

<template>
  <div class="column col-12 full-height no-wrap">
    <div class="text-weight-bold text-body1 row items-center q-pb-md">
      <q-icon
        flat
        size="xs"
        class="q-pa-sm rounded q-mr-sm"
        color="info"
        name="mdi-briefcase-outline"
        style="background-color: var(--surface-3)"
      />
      {{ $t(`workInformation`) }}
      <AddButton
        v-if="!readonly"
        id="btn-add-work"
        icon-only
        class="q-ml-sm"
        @click="addWork"
      />
    </div>

    <div v-if="workItems.length > 0" class="q-gutter-y-md row">
      <WorkManagementComponent
        class="col-12"
        v-for="(work, index) in workItems"
        :key="work.id"
        :index="index"
        :length="workItems.length"
        :workIndex="index"
        :readonly="readonly"
        v-model:work-name="workItems[index].name"
        v-model:product-items="work.product"
        v-model:attributes="work.attributes"
        @add-product="$emit('addProduct', index)"
        @move-work-up="moveItemUp(workItems, index)"
        @move-work-down="moveItemDown(workItems, index)"
        @delete-work="confirmDelete(workItems, index)"
        @move-product-up="moveItemUp"
        @move-product-down="moveItemDown"
        @delete-product="confirmDelete"
        @manage-work-name="$emit('manageWorkName')"
        @work-properties="$emit('workProperties', index)"
      ></WorkManagementComponent>
      <div class="col-12" style="height: 12px"></div>
    </div>

    <div
      v-else
      class="col row rounded bordered surface-2 justify-center items-center"
    >
      <NoData />
    </div>
  </div>
</template>

<style scoped lang="scss"></style>
