<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { EmployeeWorkCreate } from 'stores/employee/types';
import { selectFilterOptionRefMod } from 'stores/utils';
import DatePicker from '../shared/DatePicker.vue';

import {
  AddButton,
  EditButton,
  DeleteButton,
  SaveButton,
  UndoButton,
} from 'components/button';

const currentIndex = defineModel<number>('currentIndex');
const employeeWork = defineModel<EmployeeWorkCreate[]>('employeeWork');
const positionNameOption = defineModel<{ label: string; value: string }[]>(
  'positionNameOption',
  { required: true },
);
const jobTypeOption = defineModel<{ label: string; value: string }[]>(
  'jobTypeOption',
  { required: true },
);
const workplaceOption = defineModel<{ label: string; value: string }[]>(
  'workplaceOption',
  { required: true },
);

const tab = ref();

defineProps<{
  title?: string;
  dense?: boolean;
  outlined?: boolean;
  readonly?: boolean;
  prefixId: string;
  hideAction?: boolean;
}>();

defineEmits<{
  (e: 'save', index: number): void;
  (e: 'edit', index: number): void;
  (e: 'delete', index: number): void;
  (e: 'undo', index: number): void;
}>();

function addData() {
  // const canAdd = checkTabBeforeAdd(employeeWork.value || []);
  const canAdd = true;
  if (canAdd) {
    employeeWork.value?.push({
      workEndDate: null,
      workPermitExpireDate: null,
      workPermitIssuDate: null,
      workPermitNo: '',
      workplace: '',
      jobType: '',
      positionName: '',
      ownerName: '',
      remark: '',
    });
    if (employeeWork.value) {
      tab.value = `tab${employeeWork.value.length - 1}`;
      currentIndex.value = employeeWork.value.length - 1;
    }
  }
}

function removeData(index: number) {
  if (!employeeWork.value) return;
  if (employeeWork.value.length === 1) return;

  employeeWork.value.splice(index, 1);

  if (index) if (tab.value === `tab${index}`) tab.value = `tab${index - 1}`;
  if (tab.value === `tab${employeeWork.value.length}`)
    tab.value = `tab${employeeWork.value.length - 1}`;
}

onMounted(async () => {
  tab.value = 'tab0';
});

const positionNameOptions = ref<Record<string, unknown>[]>([]);
const positionNameFilter = selectFilterOptionRefMod(
  positionNameOption,
  positionNameOptions,
  'label',
);

const jobTypeOptions = ref<Record<string, unknown>[]>([]);
const jobTypeFilter = selectFilterOptionRefMod(
  jobTypeOption,
  jobTypeOptions,
  'label',
);

const workplaceOptions = ref<Record<string, unknown>[]>([]);
const workplaceFilter = selectFilterOptionRefMod(
  workplaceOption,
  workplaceOptions,
  'label',
);
</script>

<template>
  <div class="row col-12">
    <div class="col-12 q-pb-sm text-weight-bold text-body1 row items-center">
      <q-icon
        flat
        size="xs"
        class="q-pa-sm rounded q-mr-xs"
        color="info"
        name="mdi-briefcase-outline"
        style="background-color: var(--surface-3)"
      />
      {{ $t(`customerEmployee.formWorkHistory.title`) }}
      <AddButton
        v-if="currentIndex === -1 && !hideAction"
        id="btn-add-bank"
        icon-only
        class="q-ml-sm"
        type="button"
        @click="addData"
        :disabled="!(currentIndex === -1)"
      />
    </div>

    <div
      v-for="(work, index) in employeeWork"
      v-bind:key="index"
      class="col-12 row q-col-gutter-sm"
      :class="{ 'q-pt-lg': index !== 0 }"
      :id="`${prefixId}-work-history-${index}`"
    >
      <q-separator
        v-if="index > 0"
        class="full-width"
        style="padding-block: 0.1px"
        spaced="lg"
      />
      <span class="col-12 flex justify-between items-center">
        {{ $t('general.times', { number: index + 1 }) }}

        <div class="row items-center" v-if="!hideAction">
          <UndoButton
            v-if="!readonly && !!work.id && !work.statusSave"
            id="btn-info-health-undo"
            icon-only
            @click="$emit('undo', index)"
            :disabled="!(currentIndex === -1) && !(currentIndex === index)"
            type="button"
          />

          <SaveButton
            type="submit"
            icon-only
            v-if="!readonly && !work.statusSave"
            @click="$emit('save', index)"
            :disabled="!(currentIndex === -1) && !(currentIndex === index)"
          />

          <EditButton
            icon-only
            v-if="!readonly && work.statusSave"
            @click="$emit('edit', index)"
            type="button"
            :disabled="!(currentIndex === -1) && !(currentIndex === index)"
          />
          <DeleteButton
            icon-only
            v-if="!readonly && !!work.id && work.statusSave"
            @click="$emit('delete', index)"
            type="button"
            :disabled="!(currentIndex === -1) && !(currentIndex === index)"
          />
        </div>
      </span>
      <q-select
        outlined
        clearable
        use-input
        fill-input
        emit-value
        map-options
        hide-selected
        hide-bottom-space
        class="col-6"
        input-debounce="0"
        option-label="label"
        option-value="value"
        v-model="work.jobType"
        :dense="dense"
        :readonly="readonly || work.statusSave"
        :options="jobTypeOptions"
        :hide-dropdown-icon="readonly"
        :for="`${prefixId}-select-job-type`"
        :label="$t('customerEmployee.formWorkHistory.jobType')"
        @filter="jobTypeFilter"
      >
        <template v-slot:no-option>
          <q-item>
            <q-item-section class="text-grey">
              {{ $t('general.noData') }}
            </q-item-section>
          </q-item>
        </template>
      </q-select>
      <q-select
        outlined
        clearable
        use-input
        fill-input
        emit-value
        map-options
        hide-selected
        hide-bottom-space
        class="col-6"
        input-debounce="0"
        option-label="label"
        option-value="value"
        v-model="work.workplace"
        :dense="dense"
        :readonly="readonly || work.statusSave"
        :options="workplaceOptions"
        :hide-dropdown-icon="readonly"
        :for="`${prefixId}-select-province`"
        :label="$t('customerEmployee.formWorkHistory.workplace')"
        @filter="workplaceFilter"
      >
        <template v-slot:no-option>
          <q-item>
            <q-item-section class="text-grey">
              {{ $t('general.noData') }}
            </q-item-section>
          </q-item>
        </template>
      </q-select>
      <q-input
        :for="`${prefixId}-input-work-end-date`"
        :label="$t('general.remark')"
        :dense="dense"
        outlined
        :readonly="readonly || work.statusSave"
        hide-bottom-space
        class="col-12"
        v-model="work.remark"
        type="textarea"
      />
      <DatePicker
        :label="$t('customerEmployee.formWorkHistory.workUntil')"
        v-model="work.workEndDate"
        class="col-3"
        :id="`${prefixId}-input-work-until-date`"
        :readonly="readonly || work.statusSave"
        clearable
      />

      <q-input
        :for="`${prefixId}-input-work-permit-no`"
        :dense="dense"
        outlined
        :readonly="readonly || work.statusSave"
        hide-bottom-space
        class="col-6"
        :label="$t('customerEmployee.formWorkHistory.permitNo')"
        v-model="work.workPermitNo"
      />
      <DatePicker
        :label="$t('customerEmployee.formWorkHistory.permitIssueDate')"
        v-model="work.workPermitIssuDate"
        class="col-3"
        :id="`${prefixId}-date-picker-work-permit-issue-date`"
        :readonly="readonly || work.statusSave"
        clearable
      />
      <DatePicker
        :label="$t('customerEmployee.formWorkHistory.permitExpireDate')"
        v-model="work.workPermitExpireDate"
        class="col-3"
        :id="`${prefixId}-date-picker-work-permit-expire-date`"
        :readonly="readonly || work.statusSave"
        clearable
      />

      <q-input
        :for="`${prefixId}-input-owner-name`"
        :dense="dense"
        outlined
        :readonly="readonly || work.statusSave"
        hide-bottom-space
        class="col-5"
        :label="$t('customerEmployee.formWorkHistory.employerName')"
        v-model="work.ownerName"
      />
      <q-select
        outlined
        clearable
        use-input
        fill-input
        emit-value
        map-options
        hide-selected
        hide-bottom-space
        class="col-4"
        input-debounce="0"
        option-value="value"
        option-label="label"
        v-model="work.positionName"
        :dense="dense"
        :readonly="readonly || work.statusSave"
        :options="positionNameOptions"
        :hide-dropdown-icon="readonly || work.statusSave"
        :for="`${prefixId}-select-position-name`"
        :label="$t('customerEmployee.formWorkHistory.jobPosition')"
        @filter="positionNameFilter"
      >
        <template v-slot:no-option>
          <q-item>
            <q-item-section class="text-grey">
              {{ $t('general.noData') }}
            </q-item-section>
          </q-item>
        </template>
      </q-select>
    </div>
  </div>
</template>

<style scoped></style>
