<script setup lang="ts">
import { ref, watch, onMounted } from 'vue';
import { QSelect } from 'quasar';
import { useI18n } from 'vue-i18n';

import { selectFilterOptionRefMod } from 'stores/utils';
import { calculateAge, disabledAfterToday } from 'src/utils/datetime';
import useOptionStore from 'stores/options';

import DatePicker from '../shared/DatePicker.vue';

const optionStore = useOptionStore();
const { locale } = useI18n();

const birthCountry = defineModel<string>('birthCountry');
const previousPassportRef = defineModel<string>('previousPassportRef');
const issuePlace = defineModel<string>('issuePlace');
const issueCountry = defineModel<string>('issueCountry');
const issueDate = defineModel<Date | null | string>('issueDate');
const type = defineModel<string>('type');
const expireDate = defineModel<Date>('expireDate');
const birthDate = defineModel<Date>('birthDate');
const workerStatus = defineModel<string>('workerStatus');
const nationality = defineModel<string>('nationality');
const gender = defineModel<string>('gender');
const lastNameEN = defineModel<string>('lastNameEn');
const lastName = defineModel<string>('lastName');
const middleNameEN = defineModel<string>('middleNameEn');
const middleName = defineModel<string>('middleName');
const firstNameEN = defineModel<string>('firstNameEn');
const firstName = defineModel<string>('firstName');
const namePrefix = defineModel<string>('namePrefix');
const passportNumber = defineModel<string>('passportNumber');

const passportValidator = /[a-zA-Z]{1}[a-zA-Z0-9]{1}[0-9]{5,7}$/;

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

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

const props = defineProps<{
  title?: string;
  dense?: boolean;
  fullName?: boolean;
  outlined?: boolean;
  readonly?: boolean;
  separator?: boolean;
  img?: string;
  ocr?: boolean;
  hideTitle?: boolean;

  prefixId: string;
}>();

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

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

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

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

function matPreFixName() {
  if (!gender.value) return;

  if (gender.value === 'male') namePrefix.value = 'mr';
  else namePrefix.value = 'mrs';
}

onMounted(() => {
  if (
    optionStore.globalOption?.nationality &&
    optionStore.globalOption?.passportType &&
    optionStore.globalOption?.prefix
  ) {
    passportTypeFilter = selectFilterOptionRefMod(
      ref(optionStore.globalOption.passportType),
      passportTypeOptions,
      'label',
    );
    passportIssuingCountryFilter = selectFilterOptionRefMod(
      ref(optionStore.rawOption?.eng.nationality),
      passportIssuingCountryOptions,
      'label',
    );

    prefixNameFilter = selectFilterOptionRefMod(
      ref(optionStore.globalOption?.prefix),
      prefixNameOptions,
      'label',
    );

    workerStatusFilter = selectFilterOptionRefMod(
      ref(optionStore.globalOption?.workerStatus),
      workerStatusOptions,
      'label',
    );

    genderFilter = selectFilterOptionRefMod(
      ref(optionStore.rawOption?.eng.gender),
      genderOptions,
      'label',
    );

    nationalityFilter = selectFilterOptionRefMod(
      ref(optionStore.rawOption?.eng.nationality),
      nationalityOptions,
      'label',
    );
  }

  matPreFixName();
});

watch(
  () => optionStore.globalOption,
  () => {
    prefixNameFilter = selectFilterOptionRefMod(
      ref(optionStore.globalOption.prefix),
      prefixNameOptions,
      'label',
    );

    passportTypeFilter = selectFilterOptionRefMod(
      ref(optionStore.globalOption.passportType),
      passportTypeOptions,
      'label',
    );

    passportIssuingCountryFilter = selectFilterOptionRefMod(
      ref(optionStore.rawOption?.eng.nationality),
      passportIssuingCountryOptions,
      'label',
    );

    workerStatusFilter = selectFilterOptionRefMod(
      ref(optionStore.globalOption?.workerStatus),
      workerStatusOptions,
      'label',
    );

    genderFilter = selectFilterOptionRefMod(
      ref(optionStore.rawOption?.eng.gender),
      genderOptions,
      'label',
    );

    nationalityFilter = selectFilterOptionRefMod(
      ref(optionStore.rawOption?.eng.nationality),
      nationalityOptions,
      'label',
    );
  },
);

watch(
  () => namePrefix.value,
  (v) => {
    if (v === 'mr') gender.value = 'male';
    else if (v !== '') gender.value = 'female';
  },
);

watch(
  () => gender.value,
  () => {
    if (props.readonly) return;
    matPreFixName();
  },
);
</script>

<template>
  <div class="row col-12">
    <div v-if="!hideTitle" 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-passport"
        style="background-color: var(--surface-3)"
      />
      {{ title }}
    </div>

    <div
      class="col-12 row justify-between items-center q-pb-sm text-weight-bold"
    >
      <div class="app-text-muted">
        <slot name="expiryDate" />
      </div>

      <div>
        <slot name="button"></slot>
      </div>
    </div>

    <div class="q-col-gutter-sm" :class="{ row: $q.screen.gt.sm }">
      <div
        class="col row justify-center q-col-gutter-sml"
        style="max-height: 50%"
        v-if="!ocr"
      >
        <q-avatar
          style="border: 1px dashed; border-color: black"
          square
          size="100px"
          font-size="50px"
          color="grey-4"
          text-color="grey"
          icon="mdi-image-outline"
        />
      </div>
      <div
        class="row q-col-gutter-sm"
        :class="{ 'col-10': !ocr, 'col-12': ocr }"
      >
        <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-6 col-12"
          :dense="dense"
          :readonly="readonly"
          :options="workerStatusOptions"
          :hide-dropdown-icon="readonly"
          :for="`${prefixId}-select-visa-type`"
          :label="$t('customerEmployee.form.workerStatus')"
          @filter="workerStatusFilter"
          :model-value="readonly ? workerStatus || '-' : workerStatus"
          @update:model-value="
            (v) => (typeof v === 'string' ? (workerStatus = v) : '')
          "
          @clear="workerStatus = ''"
          :rules="[
            (val) => (val && val.length > 0) || $t('form.error.required'),
          ]"
        >
          <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-previous-passport-Number`"
          :dense="dense"
          outlined
          :readonly="readonly"
          hide-bottom-space
          class="col-md-6 col-12"
          :label="$t('customerEmployee.form.previousPassportNumber')"
          v-model="previousPassportRef"
          :rules="[
            (v) =>
              !v ||
              passportValidator.test(v) ||
              $t('form.error.passportFormat'),
          ]"
        />

        <q-select
          outlined
          use-input
          fill-input
          emit-value
          map-options
          hide-selected
          hide-bottom-space
          input-debounce="0"
          option-label="label"
          option-value="value"
          hide-dropdown-icon
          class="col-md-2 col-6"
          :dense="dense"
          :readonly="readonly"
          :options="prefixNameOptions"
          :for="`${prefixId}-select-prefix-name`"
          :label="$t('personnel.form.prefixName')"
          @filter="prefixNameFilter"
          :model-value="readonly ? namePrefix || '-' : namePrefix"
          @update:model-value="
            (v) => (typeof v === 'string' ? (namePrefix = v) : '')
          "
          @clear="namePrefix = ''"
        >
          <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-first-name`"
          :dense="dense"
          outlined
          :readonly="readonly"
          hide-bottom-space
          class="col-md col-6"
          :label="$t('form.firstName')"
          :model-value="readonly ? firstName || '-' : firstName"
          @update:model-value="
            (v) => (typeof v === 'string' ? (firstName = v.trim()) : '')
          "
        />

        <q-input
          :for="`${prefixId}-input-middle-name`"
          :dense="dense"
          outlined
          :readonly="readonly"
          hide-bottom-space
          class="col"
          :label="$t('form.middleName')"
          :model-value="readonly ? middleName || '-' : middleName"
          @update:model-value="
            (v) => (typeof v === 'string' ? (middleName = v.trim()) : '')
          "
        />

        <q-input
          :for="`${prefixId}-input-last-name`"
          :dense="dense"
          outlined
          :readonly="readonly"
          hide-bottom-space
          class="col"
          :label="$t('form.lastName')"
          :model-value="readonly ? lastName || '-' : lastName"
          @update:model-value="
            (v) => (typeof v === 'string' ? (lastName = v.trim()) : '')
          "
        />

        <q-input
          :for="`${prefixId}-input-full-name`"
          :dense="dense"
          outlined
          :readonly="readonly"
          hide-bottom-space
          class="col-12"
          :disable="!readonly"
          :label="$t('customer.table.fullname')"
          :model-value="`${(prefixNameOptions.find((v) => v.value === namePrefix) || {}).label || ''} ${firstName || ''} ${lastName || ''}`"
        />

        <q-input
          :for="`${prefixId}-input-first-name-en`"
          :dense="dense"
          outlined
          :readonly="readonly"
          hide-bottom-space
          class="col-md-4 col-6"
          :label="$t('form.firstNameEN')"
          :model-value="readonly ? firstNameEN || '-' : firstNameEN"
          @update:model-value="
            (v) => (typeof v === 'string' ? (firstNameEN = v.trim()) : '')
          "
          :rules="[
            (val) => (val && val.length > 0) || $t('form.error.required'),
          ]"
        />

        <q-input
          :for="`${prefixId}-input-middle-name-en`"
          :dense="dense"
          outlined
          :readonly="readonly"
          hide-bottom-space
          class="col-md-4 col-6"
          :label="$t('form.middleNameEN')"
          :model-value="readonly ? middleNameEN || '-' : middleNameEN"
          @update:model-value="
            (v) => (typeof v === 'string' ? (middleNameEN = v.trim()) : '')
          "
        />

        <q-input
          :for="`${prefixId}-input-last-name-en`"
          :dense="dense"
          outlined
          :readonly="readonly"
          hide-bottom-space
          class="col-md-4 col-6"
          :label="$t('form.lastNameEN')"
          :model-value="readonly ? lastNameEN || '-' : lastNameEN"
          @update:model-value="
            (v) => (typeof v === 'string' ? (lastNameEN = v.trim()) : '')
          "
          :rules="[
            (val) => (val && val.length > 0) || $t('form.error.required'),
          ]"
        />

        <q-input
          :for="`${prefixId}-input-full-name-en`"
          :dense="dense"
          outlined
          :readonly="readonly"
          hide-bottom-space
          class="col-12"
          :label="$t('customer.table.fullnameEN')"
          :disable="!readonly"
          :model-value="`${(prefixNameOptions.find((v) => v.value === namePrefix) || {}).value || ''} ${firstNameEN || ''} ${lastNameEN || ''}`"
        />

        <q-select
          outlined
          use-input
          fill-input
          emit-value
          map-options
          hide-selected
          hide-bottom-space
          input-debounce="0"
          option-label="label"
          option-value="value"
          class="col-md-2 col-4"
          dense
          :readonly="readonly"
          :options="genderOptions"
          :hide-dropdown-icon="readonly"
          :for="`${prefixId}-select-gender`"
          :label="$t('form.gender')"
          @filter="genderFilter"
          :model-value="readonly ? gender || '-' : gender"
          @update:model-value="
            (v) => (typeof v === 'string' ? (gender = v) : '')
          "
          @clear="gender = ''"
        >
          <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-passport-no`"
          :dense="dense"
          outlined
          :readonly="readonly"
          hide-bottom-space
          class="col-8 col-md-3"
          :label="$t('customerEmployee.form.passportNo')"
          v-model="passportNumber"
          :rules="[
            (val) => !!val || $t('form.error.required'),
            (val) =>
              passportValidator.test(val) || $t('form.error.passportFormat'),
          ]"
        />

        <DatePicker
          v-model="birthDate"
          class="col-md-2 col-6"
          :id="`${prefixId}-input-birth-date`"
          :readonly="readonly"
          :label="$t('form.birthDate')"
          :disabled-dates="disabledAfterToday"
          :rules="[
            (val: string) =>
              !!val ||
              $t('form.error.selectField', { field: $t('form.birthDate') }),
          ]"
        />

        <q-input
          :for="`${prefixId}-input-age`"
          :id="`${prefixId}-input-age`"
          dense
          outlined
          readonly
          :label="$t('personnel.age')"
          class="col-md-2 col-6"
          :model-value="
            birthDate?.toString() === 'Invalid Date' ||
            birthDate?.toString() === undefined
              ? ''
              : calculateAge(birthDate)
          "
        />

        <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 col-6"
          :dense="dense"
          :readonly="readonly"
          :options="nationalityOptions"
          :hide-dropdown-icon="readonly"
          :for="`${prefixId}-select-visa-type`"
          :label="$t('general.nationality')"
          @filter="nationalityFilter"
          :model-value="readonly ? nationality || '-' : nationality"
          @update:model-value="
            (v) =>
              typeof v === 'string' ? (birthCountry = nationality = v) : ''
          "
          @clear="nationality = ''"
          :rules="[
            (val) => (val && val.length > 0) || $t('form.error.required'),
          ]"
        >
          <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-place-of-birth`"
          :dense="dense"
          outlined
          :readonly="readonly"
          hide-bottom-space
          class="col-md-4 col-6"
          :label="$t('customerEmployee.form.placeOfBirth')"
          :model-value="optionStore.mapOption(birthCountry || '')"
          @update:model-value="
            (v) => (typeof v === 'string' ? (birthCountry = v) : '')
          "
          :rules="[(val) => !!val || $t('form.error.required')]"
        />

        <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-6 col-md-4"
          v-model="issueCountry"
          :dense="dense"
          :readonly="readonly"
          :hide-dropdown-icon="readonly"
          :options="passportIssuingCountryOptions"
          :for="`${prefixId}-select-passport-country`"
          :label="$t('customerEmployee.form.passportIssuer')"
          @update:model-value="(v) => (issuePlace = v)"
          :rules="[
            (val) =>
              (val && val.length > 0) ||
              $t('form.error.selectField', {
                field: $t('customerEmployee.form.passportIssuer'),
              }),
          ]"
          @filter="passportIssuingCountryFilter"
        >
          <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-passport-place`"
          :dense="dense"
          outlined
          :readonly="readonly"
          hide-bottom-space
          class="col-md-4 col-6"
          :label="$t('customerEmployee.form.passportPlace')"
          :model-value="
            readonly
              ? optionStore.mapOption(issuePlace || '') || '-'
              : optionStore.mapOption(issuePlace || '')
          "
          @update:model-value="
            (v) => (typeof v === 'string' ? (issuePlace = v) : '')
          "
          :rules="[
            (val) => (val && val.length > 0) || $t('form.error.required'),
          ]"
        />

        <DatePicker
          :id="`${prefixId}-date-picker-passport-issueance`"
          :label="$t('customerEmployee.form.passportIssueDate')"
          v-model="issueDate"
          @update:model-value="
            (v) => {
              if (!v) return;
              if (!expireDate) return;
              if (new Date(v).getTime() >= new Date(expireDate).getTime()) {
                const newValue = new Date(v);
                newValue.setDate(newValue.getDate() + 1);
                expireDate = newValue;
              }
            }
          "
          class="col-6 col-md-3"
          :readonly="readonly"
          :rules="[
            (val) =>
              (val && val.length > 0) ||
              $t('form.error.selectField', {
                field: $t('customerEmployee.form.passportIssueDate'),
              }),
          ]"
        />
        <DatePicker
          :id="`${prefixId}-date-picker-passport-expire`"
          :label="$t('customerEmployee.form.passportExpireDate')"
          v-model="expireDate"
          class="col-6 col-md-3"
          :disabled-dates="
            (date: Date) =>
              date.getTime() <
              ((issueDate && new Date(issueDate).getTime()) || Date.now())
          "
          :readonly="readonly"
          :rules="[
            (val) =>
              (val && val.length > 0) ||
              $t('form.error.selectField', {
                field: $t('customerEmployee.form.passportExpireDate'),
              }),
          ]"
        />
      </div>
    </div>
  </div>
</template>

<style scoped></style>
