<script setup lang="ts">
import useUserStore from 'stores/user';
import useOptionStore from 'stores/options';
import { UserAttachmentDelete } from 'stores/user/types';
import { dialog, selectFilterOptionRefMod } from 'stores/utils';
import { onMounted, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { Icon } from '@iconify/vue';
import { QSelect } from 'quasar';
import DatePicker from '../shared/DatePicker.vue';

const { t } = useI18n();
const userStore = useUserStore();
const optionStore = useOptionStore();

const userId = defineModel<string>('userId');
const userType = defineModel<string>('userType');
const registrationNo = defineModel<string | null>('registrationNo');
const startDate = defineModel<Date | null | string>('startDate');
const retireDate = defineModel<Date | null | string>('retireDate');
const responsibleArea = defineModel<string | null | undefined>(
  'responsibleArea',
);
const discountCondition = defineModel<string | null | undefined>(
  'discountCondition',
);
const sourceNationality = defineModel<string | null | undefined>(
  'sourceNationality',
);
const importNationality = defineModel<string | null | undefined>(
  'importNationality',
);
const trainingPlace = defineModel<string | null | undefined>('trainingPlace');
const checkpoint = defineModel<string | null | undefined>('checkPoint');
const checkpointEN = defineModel<string | null | undefined>('checkPointEN');
const agencyFile = defineModel<File[]>('agencyFile');
const agencyFileList =
  defineModel<{ name: string; url: string }[]>('agencyFileList');

const attachmentRef = ref();

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

function openNewTab(url: string) {
  window.open(url, '_blank');
}

function deleteFile(name: string) {
  dialog({
    color: 'negative',
    icon: 'mdi-trash-can-outline',
    title: t('dialog.title.confirmDelete', {
      msg: t('personnel.form.attachment'),
    }),
    actionText: t('general.delete'),
    persistent: true,
    message: t('dialog.message.confirmDelete'),
    action: async () => {
      if (!userId.value) return;
      const payload: UserAttachmentDelete = {
        file: [name],
      };
      userStore.deleteAttachment(userId.value, payload);
      const result = await userStore.fetchAttachment(userId.value);
      if (result) {
        agencyFileList.value = result;
      }
    },
    cancel: () => {},
  });
}

const nationalityOptions = ref<Record<string, unknown>[]>([]);
let nationalityFilter: (
  value: string,
  update: (callbackFn: () => void, afterFn?: (ref: QSelect) => void) => void,
) => void;

const trainingPlaceOptions = ref<Record<string, unknown>[]>([]);
let trainingPlaceFilter: (
  value: string,
  update: (callbackFn: () => void, afterFn?: (ref: QSelect) => void) => void,
) => void;

const responsibleAreaOptions = ref<Record<string, unknown>[]>([]);
let responsibleAreaFilter: (
  value: string,
  update: (callbackFn: () => void, afterFn?: (ref: QSelect) => void) => void,
) => void;

onMounted(() => {
  if (optionStore.globalOption?.nationality) {
    nationalityFilter = selectFilterOptionRefMod(
      ref(optionStore.globalOption.nationality),
      nationalityOptions,
      'label',
    );
    trainingPlaceFilter = selectFilterOptionRefMod(
      ref(optionStore.globalOption.training),
      trainingPlaceOptions,
      'label',
    );
    responsibleAreaFilter = selectFilterOptionRefMod(
      ref(optionStore.globalOption.area),
      responsibleAreaOptions,
      'label',
    );
  }
});

watch(
  () => optionStore.globalOption,
  () => {
    nationalityFilter = selectFilterOptionRefMod(
      ref(optionStore.globalOption.nationality),
      nationalityOptions,
      'label',
    );
    trainingPlaceFilter = selectFilterOptionRefMod(
      ref(optionStore.globalOption.training),
      trainingPlaceOptions,
      'label',
    );
  },
);
</script>
<template>
  <div class="row col-12">
    <div v-if="userType" class="col-12 q-pb-sm text-weight-bold text-body1">
      <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('personnel.form.workInformation') }}
    </div>
    <div class="col-12 row q-col-gutter-sm">
      <div
        v-if="userType === 'USER' || userType === 'MESSENGER'"
        class="row col-12 q-col-gutter-sm"
        style="margin-left: 0px; padding-left: 0px"
      >
        <q-input
          for="input-regis-no"
          :dense="dense"
          outlined
          :readonly="readonly"
          :label="$t('personnel.form.regisNo')"
          class="col-12"
          :model-value="readonly ? registrationNo || '-' : registrationNo"
          @update:model-value="
            (v) => (typeof v === 'string' ? (registrationNo = v) : '')
          "
          @clear="registrationNo = ''"
        />
        <DatePicker
          class="col-6"
          id="input-start-date"
          :readonly="readonly"
          :label="$t('personnel.form.startDate')"
          v-model="startDate"
          clearable
        />

        <DatePicker
          class="col-6"
          id="input-retire-date"
          :readonly="readonly"
          :label="$t('personnel.form.retireDate')"
          v-model="retireDate"
          clearable
        />

        <q-select
          v-if="userType === 'MESSENGER'"
          outlined
          clearable
          use-input
          fill-input
          emit-value
          map-options
          hide-selected
          hide-bottom-space
          class="col-12"
          input-debounce="0"
          option-label="label"
          option-value="value"
          id="input-responsible-area"
          :dense="dense"
          :readonly="readonly"
          :hide-dropdown-icon="readonly"
          :label="$t('personnel.form.responsibleArea')"
          :options="responsibleAreaOptions"
          @filter="responsibleAreaFilter"
          :model-value="readonly ? responsibleArea || '-' : responsibleArea"
          @update:model-value="
            (v) => (typeof v === 'string' ? (responsibleArea = v) : '')
          "
          @clear="responsibleArea = ''"
        >
          <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
        v-if="userType === 'DELEGATE'"
        class="row col-12"
        style="row-gap: 16px"
      >
        <q-input
          for="input-discount-condition"
          :dense="dense"
          outlined
          :readonly="readonly"
          :label="$t('personnel.form.discount')"
          class="col-12"
          type="textarea"
          :model-value="readonly ? discountCondition || '-' : discountCondition"
          @update:model-value="
            (v) => (typeof v === 'string' ? (discountCondition = v) : '')
          "
          @clear="discountCondition = ''"
        />
      </div>
      <div
        v-if="userType === 'AGENCY'"
        class="row col-12 q-col-gutter-sm"
        style="margin-left: 0px; padding-left: 0px"
      >
        <q-select
          outlined
          clearable
          use-input
          fill-input
          emit-value
          map-options
          hide-selected
          hide-bottom-space
          input-debounce="0"
          option-value="value"
          option-label="label"
          class="col-md-3 col-6"
          id="input-source-nationality"
          for="input-source-nationality"
          :dense="dense"
          :readonly="readonly"
          :hide-dropdown-icon="readonly"
          :label="$t('personnel.form.sourceNationality')"
          :options="nationalityOptions"
          @filter="nationalityFilter"
          :model-value="readonly ? sourceNationality || '-' : sourceNationality"
          @update:model-value="
            (v) => (typeof v === 'string' ? (sourceNationality = v) : '')
          "
          @clear="sourceNationality = ''"
        >
          <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
          input-debounce="0"
          option-value="value"
          option-label="label"
          class="col-md-3 col-6"
          id="input-import-nationality"
          for="input-import-nationality"
          :dense="dense"
          :readonly="readonly"
          :hide-dropdown-icon="readonly"
          :label="$t('personnel.form.importNationality')"
          :options="nationalityOptions"
          @filter="nationalityFilter"
          :model-value="readonly ? importNationality || '-' : importNationality"
          @update:model-value="
            (v) => (typeof v === 'string' ? (importNationality = v) : '')
          "
          @clear="importNationality = ''"
        >
          <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
          input-debounce="0"
          option-label="label"
          option-value="label"
          class="col-md-6 col-12"
          id="select-trainig-place"
          for="select-trainig-place"
          :dense="dense"
          :readonly="readonly"
          :hide-dropdown-icon="readonly"
          :label="$t('personnel.form.trainingPlace')"
          :options="trainingPlaceOptions"
          @filter="trainingPlaceFilter"
          :model-value="readonly ? trainingPlace || '-' : trainingPlace"
          @update:model-value="
            (v) => (typeof v === 'string' ? (trainingPlace = v) : '')
          "
          @clear="trainingPlace = ''"
        >
          <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="input-checkpoint"
          :dense="dense"
          outlined
          :readonly="readonly"
          :label="$t('personnel.form.checkpoint')"
          class="col-6"
          :model-value="readonly ? checkpoint || '-' : checkpoint"
          @update:model-value="
            (v) => (typeof v === 'string' ? (checkpoint = v) : '')
          "
          @clear="checkpoint = ''"
        />
        <q-input
          for="input-checkpoint-en"
          :dense="dense"
          outlined
          :readonly="readonly"
          :label="$t('personnel.form.checkpointEN')"
          class="col-6"
          :model-value="readonly ? checkpointEN || '-' : checkpointEN"
          @update:model-value="
            (v) => (typeof v === 'string' ? (checkpointEN = v) : '')
          "
          @clear="checkpointEN = ''"
        />
        <q-file
          ref="attachmentRef"
          for="input-attachment"
          :dense="dense"
          outlined
          :readonly="readonly"
          multiple
          append
          :label="$t('personnel.form.attachment')"
          class="col-12"
          v-model="agencyFile"
        >
          <template v-slot:prepend>
            <Icon
              icon="material-symbols:attach-file"
              width="20px"
              style="color: var(--brand-1)"
            />
          </template>
          <template v-slot:file="file">
            <div class="row full-width items-center">
              <span class="col ellipsis">
                {{ file.file.name }}
              </span>
              <q-btn
                dense
                rounded
                flat
                padding="2 2"
                class="app-text-muted"
                icon="mdi-close-circle"
                @click.stop="attachmentRef.removeAtIndex(file.index)"
              />
            </div>
          </template>
        </q-file>

        <div v-if="agencyFileList && agencyFileList?.length > 0" class="col-12">
          <q-list bordered separator class="rounded" style="padding: 0">
            <q-item
              id="attachment-file"
              for="attachment-file"
              v-for="item in agencyFileList"
              clickable
              :key="item.url"
              class="items-center row"
              @click="() => openNewTab(item.url)"
            >
              <q-item-section>
                <div class="row items-center justify-between">
                  <div class="col">
                    {{ item.name }}
                  </div>
                  <q-btn
                    id="delete-file"
                    v-if="!readonly && userId"
                    rounded
                    flat
                    dense
                    unelevated
                    size="md"
                    icon="mdi-trash-can-outline"
                    class="app-text-negative"
                    @click.stop="deleteFile(item.name)"
                  />
                </div>
              </q-item-section>
            </q-item>
          </q-list>
        </div>
      </div>
    </div>
  </div>
</template>
